From 78fc45f9b2cfd9ada521ac2e9554c0f4c117ccb5 Mon Sep 17 00:00:00 2001 From: ericek111 Date: Sat, 10 Oct 2026 14:43:34 +0000 Subject: [PATCH] Rename to TeamSpook TS3j, package eu.lixko.ts3j.client Java/Kotlin sources move from com.ts3client to eu.lixko.ts3j.client, and the Android application id becomes eu.lixko.ts3j.client. The product name shows as "TeamSpook TS3j" in window titles, the tray, the launcher entries, notifications and PipeWire streams. The desktop profile directory, WM_CLASS and ts3j.* system properties keep their names so existing settings and launchers carry on working. Co-Authored-By: Claude Opus 5.5 --- android/app/build.gradle.kts | 6 +- android/app/proguard-rules.pro | 2 +- .../com/ts3client/android/AudioRoutePrefs.kt | 30 - .../ts3client/android/BookmarkShortcuts.kt | 80 - .../main/java/com/ts3client/android/Chats.kt | 88 - .../ts3client/android/ConnectionService.kt | 238 -- .../com/ts3client/android/FileTransfers.kt | 132 -- .../java/com/ts3client/android/IconTheme.kt | 143 -- .../com/ts3client/android/IdentityManager.kt | 170 -- .../com/ts3client/android/LevelMonitor.kt | 95 - .../java/com/ts3client/android/LocalCopy.kt | 21 - .../com/ts3client/android/MainActivity.kt | 56 - .../com/ts3client/android/MessageNotifier.kt | 141 -- .../com/ts3client/android/NetworkFollower.kt | 220 -- .../java/com/ts3client/android/Picture.kt | 42 - .../java/com/ts3client/android/PttOverlay.kt | 176 -- .../com/ts3client/android/ReplyReceiver.kt | 17 - .../com/ts3client/android/SavedPictures.kt | 39 - .../com/ts3client/android/ServerController.kt | 582 ----- .../com/ts3client/android/ServerImages.kt | 61 - .../java/com/ts3client/android/ServerTree.kt | 192 -- .../ts3client/android/SessionController.kt | 657 ------ .../ts3client/android/SoundPackInstaller.kt | 53 - .../ts3client/android/SpeakingSoundPlayer.kt | 31 - .../com/ts3client/android/Ts3Application.kt | 18 - .../java/com/ts3client/android/WebPictures.kt | 64 - .../main/java/com/ts3client/android/ui/App.kt | 115 - .../com/ts3client/android/ui/Attachments.kt | 102 - .../com/ts3client/android/ui/BanListScreen.kt | 313 --- .../ts3client/android/ui/BookmarkScreen.kt | 152 -- .../ts3client/android/ui/ChannelEditScreen.kt | 211 -- .../com/ts3client/android/ui/ChannelTree.kt | 349 --- .../java/com/ts3client/android/ui/ChatPane.kt | 185 -- .../java/com/ts3client/android/ui/ChatText.kt | 318 --- .../com/ts3client/android/ui/ConnectScreen.kt | 231 -- .../android/ui/ConnectionInfoScreen.kt | 150 -- .../ts3client/android/ui/ContactsScreen.kt | 271 --- .../ts3client/android/ui/DetailsSection.kt | 137 -- .../com/ts3client/android/ui/FilesScreen.kt | 239 -- .../java/com/ts3client/android/ui/FindBar.kt | 190 -- .../com/ts3client/android/ui/HostButton.kt | 64 - .../ts3client/android/ui/IdentitiesScreen.kt | 282 --- .../com/ts3client/android/ui/Moderation.kt | 225 -- .../ts3client/android/ui/MyTeamSpeakScreen.kt | 247 -- .../android/ui/NetworkSettingsScreen.kt | 88 - .../java/com/ts3client/android/ui/PackIcon.kt | 42 - .../com/ts3client/android/ui/PictureViewer.kt | 220 -- .../com/ts3client/android/ui/PushToTalk.kt | 95 - .../ts3client/android/ui/RowColorPicker.kt | 120 - .../com/ts3client/android/ui/ServerImage.kt | 140 -- .../com/ts3client/android/ui/ServerScreen.kt | 686 ------ .../ts3client/android/ui/SettingsScreen.kt | 127 -- .../ts3client/android/ui/SettingsWidgets.kt | 175 -- .../java/com/ts3client/android/ui/Sheets.kt | 238 -- .../android/ui/SoundSettingsScreen.kt | 260 --- .../java/com/ts3client/android/ui/Theme.kt | 38 - .../java/com/ts3client/android/ui/Whisper.kt | 254 --- .../ts3j/client/android/AudioRoutePrefs.kt | 30 + .../ts3j/client/android/BookmarkShortcuts.kt | 80 + .../eu/lixko/ts3j/client/android/Chats.kt | 88 + .../ts3j/client/android/ConnectionService.kt | 238 ++ .../ts3j/client/android/FileTransfers.kt | 132 ++ .../eu/lixko/ts3j/client/android/IconTheme.kt | 143 ++ .../ts3j/client/android/IdentityManager.kt | 170 ++ .../lixko/ts3j/client/android/LevelMonitor.kt | 95 + .../eu/lixko/ts3j/client/android/LocalCopy.kt | 21 + .../lixko/ts3j/client/android/MainActivity.kt | 56 + .../ts3j/client/android/MessageNotifier.kt | 141 ++ .../ts3j/client/android/NetworkFollower.kt | 220 ++ .../eu/lixko/ts3j/client/android/Picture.kt | 42 + .../lixko/ts3j/client/android/PttOverlay.kt | 176 ++ .../ts3j/client/android/ReplyReceiver.kt | 17 + .../ts3j/client/android/SavedPictures.kt | 39 + .../ts3j/client/android/ServerController.kt | 582 +++++ .../lixko/ts3j/client/android/ServerImages.kt | 61 + .../lixko/ts3j/client/android/ServerTree.kt | 192 ++ .../ts3j/client/android/SessionController.kt | 657 ++++++ .../ts3j/client/android/SoundPackInstaller.kt | 53 + .../client/android/SpeakingSoundPlayer.kt | 31 + .../ts3j/client/android/Ts3Application.kt | 18 + .../lixko/ts3j/client/android/WebPictures.kt | 64 + .../eu/lixko/ts3j/client/android/ui/App.kt | 115 + .../ts3j/client/android/ui/Attachments.kt | 102 + .../ts3j/client/android/ui/BanListScreen.kt | 313 +++ .../ts3j/client/android/ui/BookmarkScreen.kt | 152 ++ .../client/android/ui/ChannelEditScreen.kt | 211 ++ .../ts3j/client/android/ui/ChannelTree.kt | 349 +++ .../lixko/ts3j/client/android/ui/ChatPane.kt | 185 ++ .../lixko/ts3j/client/android/ui/ChatText.kt | 318 +++ .../ts3j/client/android/ui/ConnectScreen.kt | 231 ++ .../client/android/ui/ConnectionInfoScreen.kt | 150 ++ .../ts3j/client/android/ui/ContactsScreen.kt | 271 +++ .../ts3j/client/android/ui/DetailsSection.kt | 137 ++ .../ts3j/client/android/ui/FilesScreen.kt | 239 ++ .../lixko/ts3j/client/android/ui/FindBar.kt | 190 ++ .../ts3j/client/android/ui/HostButton.kt | 64 + .../client/android/ui/IdentitiesScreen.kt | 282 +++ .../ts3j/client/android/ui/Moderation.kt | 225 ++ .../client/android/ui/MyTeamSpeakScreen.kt | 247 ++ .../android/ui/NetworkSettingsScreen.kt | 88 + .../lixko/ts3j/client/android/ui/PackIcon.kt | 42 + .../ts3j/client/android/ui/PictureViewer.kt | 220 ++ .../ts3j/client/android/ui/PushToTalk.kt | 95 + .../ts3j/client/android/ui/RowColorPicker.kt | 120 + .../ts3j/client/android/ui/ServerImage.kt | 140 ++ .../ts3j/client/android/ui/ServerScreen.kt | 686 ++++++ .../ts3j/client/android/ui/SettingsScreen.kt | 127 ++ .../ts3j/client/android/ui/SettingsWidgets.kt | 175 ++ .../eu/lixko/ts3j/client/android/ui/Sheets.kt | 238 ++ .../client/android/ui/SoundSettingsScreen.kt | 260 +++ .../eu/lixko/ts3j/client/android/ui/Theme.kt | 38 + .../lixko/ts3j/client/android/ui/Whisper.kt | 254 +++ android/app/src/main/res/values/strings.xml | 2 +- android/audio/build.gradle.kts | 2 +- android/audio/src/main/cpp/audio_line.cpp | 16 +- android/audio/src/main/cpp/opus_jni.cpp | 18 +- .../android/audio/AndroidAudioBackend.java | 60 - .../android/audio/AndroidAudioIo.java | 332 --- .../ts3client/android/audio/AudioRoute.java | 49 - .../ts3client/android/audio/NativeOpus.java | 119 - .../com/ts3client/android/audio/OboeLine.java | 115 - .../android/audio/AndroidAudioBackend.java | 60 + .../client/android/audio/AndroidAudioIo.java | 332 +++ .../ts3j/client/android/audio/AudioRoute.java | 49 + .../ts3j/client/android/audio/NativeOpus.java | 119 + .../ts3j/client/android/audio/OboeLine.java | 115 + ts3-client/README.md | 8 +- ts3-client/core/pom.xml | 4 +- .../com/ts3client/audio/AudioBackend.java | 37 - .../com/ts3client/audio/AudioCapture.java | 26 - .../java/com/ts3client/audio/AudioDevice.java | 13 - .../ts3client/audio/AudioFrameListener.java | 17 - .../java/com/ts3client/audio/AudioIo.java | 23 - .../com/ts3client/audio/AudioPlayback.java | 31 - .../ts3client/audio/CaptureVoiceInput.java | 592 ----- .../main/java/com/ts3client/audio/Fft.java | 68 - .../java/com/ts3client/audio/InputLevel.java | 58 - .../com/ts3client/audio/JitterBuffer.java | 595 ----- .../com/ts3client/audio/MixedPlayout.java | 116 - .../com/ts3client/audio/OpusParameters.java | 37 - .../main/java/com/ts3client/audio/Pcm16.java | 20 - .../ts3client/audio/PerSpeakerPlayout.java | 181 -- .../java/com/ts3client/audio/Playout.java | 13 - .../audio/SpeechProbabilityDetector.java | 27 - .../ts3client/audio/StreamingVoiceOutput.java | 221 -- .../java/com/ts3client/audio/VoiceFormat.java | 16 - .../java/com/ts3client/audio/VoiceInput.java | 110 - .../java/com/ts3client/audio/VoiceOutput.java | 58 - .../ts3client/audio/VoiceReceiveStats.java | 31 - .../java/com/ts3client/audio/VoiceStream.java | 489 ---- .../java/com/ts3client/audio/VoiceTap.java | 15 - .../ts3client/audio/ogg/OggPageWriter.java | 113 - .../com/ts3client/audio/ogg/OpusHeaders.java | 78 - .../audio/ogg/SelfDelimitedOpus.java | 104 - .../ts3client/audio/opus/CtlOpusEncoder.java | 38 - .../com/ts3client/audio/opus/LibOpus.java | 26 - .../com/ts3client/audio/opus/OpusCodec.java | 16 - .../com/ts3client/audio/opus/OpusDecoder.java | 28 - .../com/ts3client/audio/opus/OpusEncoder.java | 25 - .../audio/processing/AudioProcessor.java | 161 -- .../audio/processing/HighPassFilter.java | 32 - .../audio/processing/ThreeBandFilterBank.java | 152 -- .../agc2/AdaptiveDigitalConfig.java | 11 - .../agc2/AdaptiveDigitalGainController.java | 103 - .../audio/processing/agc2/Agc2Common.java | 41 - .../audio/processing/agc2/GainApplier.java | 46 - .../processing/agc2/GainController2.java | 92 - .../agc2/InterpolatedGainCurve.java | 76 - .../audio/processing/agc2/Limiter.java | 91 - .../processing/agc2/NoiseFloorEstimator.java | 90 - .../processing/agc2/SaturationProtector.java | 122 - .../processing/agc2/SpeechLevelEstimator.java | 106 - .../audio/processing/ns/FastMath.java | 49 - .../audio/processing/ns/NoiseEstimator.java | 145 -- .../audio/processing/ns/NoiseSuppressor.java | 320 --- .../audio/processing/ns/NsCommon.java | 29 - .../processing/ns/QuantileNoiseEstimator.java | 79 - .../processing/ns/SignalModelEstimator.java | 255 --- .../ns/SpeechProbabilityEstimator.java | 53 - .../audio/processing/ns/SuppressionLevel.java | 30 - .../audio/processing/ns/WienerFilter.java | 93 - .../transients/TransientDetector.java | 125 -- .../transients/TransientSuppressor.java | 186 -- .../transients/WaveletPacketTree.java | 124 - .../ts3client/audio/vad/LinearPrediction.java | 99 - .../ts3client/audio/vad/PitchEstimator.java | 329 --- .../java/com/ts3client/audio/vad/RealFft.java | 224 -- .../com/ts3client/audio/vad/RnnNetwork.java | 203 -- .../audio/vad/RnnSpeechDetector.java | 145 -- .../java/com/ts3client/audio/vad/RnnVad.java | 111 - .../ts3client/audio/vad/RnnVadWeights.java | 273 --- .../ts3client/audio/vad/SpectralFeatures.java | 281 --- .../com/ts3client/audio/vad/VadConstants.java | 54 - .../com/ts3client/chatlog/ChatLogScope.java | 7 - .../com/ts3client/chatlog/ChatLogStore.java | 321 --- .../java/com/ts3client/config/AppDirs.java | 61 - .../com/ts3client/config/AwayMessages.java | 84 - .../ts3client/config/BanReasonPresets.java | 75 - .../java/com/ts3client/config/Bookmark.java | 66 - .../java/com/ts3client/config/Bookmarks.java | 143 -- .../com/ts3client/config/ClientRowColors.java | 77 - .../com/ts3client/config/ClientVersion.java | 88 - .../com/ts3client/config/IdentityEntry.java | 76 - .../com/ts3client/config/IdentityStore.java | 385 ---- .../com/ts3client/config/InstallDirs.java | 60 - .../com/ts3client/config/ProfileFiles.java | 77 - .../ts3client/config/ServerLogSettings.java | 133 -- .../java/com/ts3client/config/Settings.java | 445 ---- .../com/ts3client/config/WhisperList.java | 40 - .../com/ts3client/config/WhisperLists.java | 93 - .../java/com/ts3client/contacts/Contact.java | 199 -- .../ts3client/contacts/ContactDefaults.java | 99 - .../com/ts3client/contacts/ContactStore.java | 267 --- .../com/ts3client/contacts/ContactType.java | 29 - .../ts3client/contacts/NicknameDisplay.java | 43 - .../java/com/ts3client/gfx/CountryFlags.java | 86 - .../main/java/com/ts3client/gfx/IconKeys.java | 37 - .../main/java/com/ts3client/gfx/IconPack.java | 388 ---- .../java/com/ts3client/gfx/IconPacks.java | 108 - .../com/ts3client/hotkey/GlobalInputHook.java | 38 - .../java/com/ts3client/hotkey/Hotkey.java | 74 - .../com/ts3client/hotkey/HotkeyAction.java | 366 --- .../com/ts3client/hotkey/HotkeyCombo.java | 94 - .../com/ts3client/hotkey/HotkeyEngine.java | 152 -- .../java/com/ts3client/hotkey/HotkeyKey.java | 88 - .../java/com/ts3client/hotkey/Hotkeys.java | 109 - .../java/com/ts3client/myts/AccountInfo.java | 38 - .../com/ts3client/myts/ChatAttachment.java | 137 -- .../com/ts3client/myts/ChatAttachments.java | 67 - .../java/com/ts3client/myts/MyTeamSpeak.java | 244 -- .../com/ts3client/myts/MyTeamSpeakLogin.java | 143 -- .../java/com/ts3client/myts/MyTsCrypto.java | 136 -- .../com/ts3client/myts/MyTsException.java | 30 - .../java/com/ts3client/myts/MyTsFiles.java | 183 -- .../com/ts3client/myts/MyTsTransport.java | 54 - .../java/com/ts3client/net/AvatarAdmin.java | 120 - .../main/java/com/ts3client/net/BanAdmin.java | 115 - .../java/com/ts3client/net/ChannelAdmin.java | 282 --- .../java/com/ts3client/net/ChannelCodec.java | 73 - .../java/com/ts3client/net/ChannelNode.java | 66 - .../com/ts3client/net/ChannelSettings.java | 219 -- .../java/com/ts3client/net/ClientEntry.java | 90 - .../java/com/ts3client/net/ClientStatus.java | 29 - .../java/com/ts3client/net/Complaint.java | 35 - .../com/ts3client/net/ComplaintAdmin.java | 79 - .../ts3client/net/ConnectionEventHandler.java | 743 ------ .../com/ts3client/net/ConnectionListener.java | 62 - .../com/ts3client/net/ConnectionStats.java | 83 - .../net/ConnectionStatsCollector.java | 288 --- .../ts3client/net/ConnectionStatsFormat.java | 186 -- .../com/ts3client/net/DatabaseClient.java | 9 - .../main/java/com/ts3client/net/Details.java | 125 -- .../main/java/com/ts3client/net/Group.java | 34 - .../java/com/ts3client/net/GroupChoice.java | 5 - .../java/com/ts3client/net/HostButton.java | 19 - .../com/ts3client/net/IconRepository.java | 200 -- .../com/ts3client/net/OfflineMessage.java | 39 - .../ts3client/net/OfflineMessageAdmin.java | 163 -- .../com/ts3client/net/PictureDownloads.java | 202 -- .../java/com/ts3client/net/PrivilegeKey.java | 36 - .../com/ts3client/net/PrivilegeKeyAdmin.java | 90 - .../com/ts3client/net/ServerLogAdmin.java | 82 - .../com/ts3client/net/ServerLogEntry.java | 49 - .../java/com/ts3client/net/ServerLogPage.java | 15 - .../java/com/ts3client/net/ServerModel.java | 612 ----- .../main/java/com/ts3client/net/Spacers.java | 83 - .../ts3client/net/TeamspeakConnection.java | 1997 ----------------- .../java/com/ts3client/net/TreeMatch.java | 22 - .../main/java/com/ts3client/net/Whisper.java | 76 - .../java/com/ts3client/net/avatar/Avatar.java | 17 - .../ts3client/net/avatar/AvatarNaming.java | 67 - .../net/avatar/AvatarRepository.java | 148 -- .../com/ts3client/net/avatar/ImageFormat.java | 22 - .../java/com/ts3client/net/ban/BanEntry.java | 107 - .../com/ts3client/net/ban/BanPattern.java | 126 -- .../java/com/ts3client/net/ban/BanRule.java | 44 - .../java/com/ts3client/net/ban/BanUnit.java | 45 - .../net/filetransfer/FileTransfer.java | 156 -- .../net/filetransfer/FileTransferManager.java | 522 ----- .../net/filetransfer/RemoteFile.java | 49 - .../com/ts3client/proto/ProtobufReader.java | 107 - .../com/ts3client/proto/ProtobufWriter.java | 47 - .../com/ts3client/recording/MixdownSink.java | 85 - .../ts3client/recording/MultitrackSink.java | 242 -- .../ts3client/recording/OggOpusStream.java | 55 - .../recording/RecordingEncoders.java | 33 - .../ts3client/recording/RecordingSink.java | 26 - .../java/com/ts3client/recording/Track.java | 49 - .../ts3client/recording/VoiceRecorder.java | 171 -- .../java/com/ts3client/session/SelfState.java | 36 - .../com/ts3client/session/ServerLink.java | 145 -- .../com/ts3client/session/ServerSession.java | 844 ------- .../java/com/ts3client/session/Sessions.java | 165 -- .../ts3client/sound/NotificationSettings.java | 91 - .../java/com/ts3client/sound/OggOpusFile.java | 148 -- .../com/ts3client/sound/PackSoundPlayer.java | 229 -- .../java/com/ts3client/sound/SoundEvent.java | 220 -- .../com/ts3client/sound/SoundNotifier.java | 165 -- .../java/com/ts3client/sound/SoundPack.java | 167 -- .../ts3client/sound/SoundPackConverter.java | 54 - .../java/com/ts3client/sound/SoundPacks.java | 53 - .../java/com/ts3client/sound/SoundPlayer.java | 33 - .../java/com/ts3client/sound/SoundScript.java | 60 - .../java/com/ts3client/sound/WaveFile.java | 112 - .../com/ts3client/teamspeak/SqliteReader.java | 288 --- .../com/ts3client/teamspeak/SyncItem.java | 42 - .../ts3client/teamspeak/SyncItemDecoder.java | 107 - .../com/ts3client/teamspeak/SyncOrder.java | 69 - .../teamspeak/TeamSpeakImporter.java | 227 -- .../teamspeak/TeamSpeakSettingsDb.java | 100 - .../main/java/com/ts3client/text/BBCode.java | 303 --- .../java/com/ts3client/text/ChatHtml.java | 152 -- .../java/com/ts3client/text/HtmlText.java | 56 - .../main/java/com/ts3client/text/Json.java | 167 -- .../java/com/ts3client/text/TextQuery.java | 86 - .../main/java/com/ts3client/text/TsLink.java | 120 - .../lixko/ts3j/client/audio/AudioBackend.java | 37 + .../lixko/ts3j/client/audio/AudioCapture.java | 26 + .../lixko/ts3j/client/audio/AudioDevice.java | 13 + .../ts3j/client/audio/AudioFrameListener.java | 17 + .../eu/lixko/ts3j/client/audio/AudioIo.java | 23 + .../ts3j/client/audio/AudioPlayback.java | 31 + .../ts3j/client/audio/CaptureVoiceInput.java | 592 +++++ .../java/eu/lixko/ts3j/client/audio/Fft.java | 68 + .../lixko/ts3j/client/audio/InputLevel.java | 58 + .../lixko/ts3j/client/audio/JitterBuffer.java | 595 +++++ .../lixko/ts3j/client/audio/MixedPlayout.java | 116 + .../ts3j/client/audio/OpusParameters.java | 37 + .../eu/lixko/ts3j/client/audio/Pcm16.java | 20 + .../ts3j/client/audio/PerSpeakerPlayout.java | 181 ++ .../eu/lixko/ts3j/client/audio/Playout.java | 13 + .../audio/SpeechProbabilityDetector.java | 27 + .../client/audio/StreamingVoiceOutput.java | 221 ++ .../lixko/ts3j/client/audio/VoiceFormat.java | 16 + .../lixko/ts3j/client/audio/VoiceInput.java | 110 + .../lixko/ts3j/client/audio/VoiceOutput.java | 58 + .../ts3j/client/audio/VoiceReceiveStats.java | 31 + .../lixko/ts3j/client/audio/VoiceStream.java | 489 ++++ .../eu/lixko/ts3j/client/audio/VoiceTap.java | 15 + .../ts3j/client/audio/ogg/OggPageWriter.java | 113 + .../ts3j/client/audio/ogg/OpusHeaders.java | 78 + .../client/audio/ogg/SelfDelimitedOpus.java | 104 + .../client/audio/opus/CtlOpusEncoder.java | 38 + .../lixko/ts3j/client/audio/opus/LibOpus.java | 26 + .../ts3j/client/audio/opus/OpusCodec.java | 16 + .../ts3j/client/audio/opus/OpusDecoder.java | 28 + .../ts3j/client/audio/opus/OpusEncoder.java | 25 + .../audio/processing/AudioProcessor.java | 161 ++ .../audio/processing/HighPassFilter.java | 32 + .../audio/processing/ThreeBandFilterBank.java | 152 ++ .../agc2/AdaptiveDigitalConfig.java | 11 + .../agc2/AdaptiveDigitalGainController.java | 103 + .../audio/processing/agc2/Agc2Common.java | 41 + .../audio/processing/agc2/GainApplier.java | 46 + .../processing/agc2/GainController2.java | 92 + .../agc2/InterpolatedGainCurve.java | 76 + .../client/audio/processing/agc2/Limiter.java | 91 + .../processing/agc2/NoiseFloorEstimator.java | 90 + .../processing/agc2/SaturationProtector.java | 122 + .../processing/agc2/SpeechLevelEstimator.java | 106 + .../client/audio/processing/ns/FastMath.java | 49 + .../audio/processing/ns/NoiseEstimator.java | 145 ++ .../audio/processing/ns/NoiseSuppressor.java | 320 +++ .../client/audio/processing/ns/NsCommon.java | 29 + .../processing/ns/QuantileNoiseEstimator.java | 79 + .../processing/ns/SignalModelEstimator.java | 255 +++ .../ns/SpeechProbabilityEstimator.java | 53 + .../audio/processing/ns/SuppressionLevel.java | 30 + .../audio/processing/ns/WienerFilter.java | 93 + .../transients/TransientDetector.java | 125 ++ .../transients/TransientSuppressor.java | 186 ++ .../transients/WaveletPacketTree.java | 124 + .../client/audio/vad/LinearPrediction.java | 99 + .../ts3j/client/audio/vad/PitchEstimator.java | 329 +++ .../lixko/ts3j/client/audio/vad/RealFft.java | 224 ++ .../ts3j/client/audio/vad/RnnNetwork.java | 203 ++ .../client/audio/vad/RnnSpeechDetector.java | 145 ++ .../lixko/ts3j/client/audio/vad/RnnVad.java | 111 + .../ts3j/client/audio/vad/RnnVadWeights.java | 273 +++ .../client/audio/vad/SpectralFeatures.java | 281 +++ .../ts3j/client/audio/vad/VadConstants.java | 54 + .../ts3j/client/chatlog/ChatLogScope.java | 7 + .../ts3j/client/chatlog/ChatLogStore.java | 321 +++ .../eu/lixko/ts3j/client/config/AppDirs.java | 61 + .../ts3j/client/config/AwayMessages.java | 84 + .../ts3j/client/config/BanReasonPresets.java | 75 + .../eu/lixko/ts3j/client/config/Bookmark.java | 66 + .../lixko/ts3j/client/config/Bookmarks.java | 143 ++ .../ts3j/client/config/ClientRowColors.java | 77 + .../ts3j/client/config/ClientVersion.java | 88 + .../ts3j/client/config/IdentityEntry.java | 76 + .../ts3j/client/config/IdentityStore.java | 385 ++++ .../lixko/ts3j/client/config/InstallDirs.java | 60 + .../ts3j/client/config/ProfileFiles.java | 77 + .../ts3j/client/config/ServerLogSettings.java | 133 ++ .../eu/lixko/ts3j/client/config/Settings.java | 445 ++++ .../lixko/ts3j/client/config/WhisperList.java | 40 + .../ts3j/client/config/WhisperLists.java | 93 + .../lixko/ts3j/client/contacts/Contact.java | 199 ++ .../ts3j/client/contacts/ContactDefaults.java | 99 + .../ts3j/client/contacts/ContactStore.java | 267 +++ .../ts3j/client/contacts/ContactType.java | 29 + .../ts3j/client/contacts/NicknameDisplay.java | 43 + .../lixko/ts3j/client/gfx/CountryFlags.java | 86 + .../eu/lixko/ts3j/client/gfx/IconKeys.java | 37 + .../eu/lixko/ts3j/client/gfx/IconPack.java | 388 ++++ .../eu/lixko/ts3j/client/gfx/IconPacks.java | 108 + .../ts3j/client/hotkey/GlobalInputHook.java | 38 + .../eu/lixko/ts3j/client/hotkey/Hotkey.java | 74 + .../ts3j/client/hotkey/HotkeyAction.java | 366 +++ .../lixko/ts3j/client/hotkey/HotkeyCombo.java | 94 + .../ts3j/client/hotkey/HotkeyEngine.java | 152 ++ .../lixko/ts3j/client/hotkey/HotkeyKey.java | 88 + .../eu/lixko/ts3j/client/hotkey/Hotkeys.java | 109 + .../lixko/ts3j/client/myts/AccountInfo.java | 38 + .../ts3j/client/myts/ChatAttachment.java | 137 ++ .../ts3j/client/myts/ChatAttachments.java | 67 + .../lixko/ts3j/client/myts/MyTeamSpeak.java | 244 ++ .../ts3j/client/myts/MyTeamSpeakLogin.java | 143 ++ .../eu/lixko/ts3j/client/myts/MyTsCrypto.java | 136 ++ .../lixko/ts3j/client/myts/MyTsException.java | 30 + .../eu/lixko/ts3j/client/myts/MyTsFiles.java | 183 ++ .../lixko/ts3j/client/myts/MyTsTransport.java | 54 + .../eu/lixko/ts3j/client/net/AvatarAdmin.java | 120 + .../eu/lixko/ts3j/client/net/BanAdmin.java | 115 + .../lixko/ts3j/client/net/ChannelAdmin.java | 282 +++ .../lixko/ts3j/client/net/ChannelCodec.java | 73 + .../eu/lixko/ts3j/client/net/ChannelNode.java | 66 + .../ts3j/client/net/ChannelSettings.java | 219 ++ .../eu/lixko/ts3j/client/net/ClientEntry.java | 90 + .../lixko/ts3j/client/net/ClientStatus.java | 29 + .../eu/lixko/ts3j/client/net/Complaint.java | 35 + .../lixko/ts3j/client/net/ComplaintAdmin.java | 79 + .../client/net/ConnectionEventHandler.java | 743 ++++++ .../ts3j/client/net/ConnectionListener.java | 62 + .../ts3j/client/net/ConnectionStats.java | 83 + .../client/net/ConnectionStatsCollector.java | 288 +++ .../client/net/ConnectionStatsFormat.java | 186 ++ .../lixko/ts3j/client/net/DatabaseClient.java | 9 + .../eu/lixko/ts3j/client/net/Details.java | 125 ++ .../java/eu/lixko/ts3j/client/net/Group.java | 34 + .../eu/lixko/ts3j/client/net/GroupChoice.java | 5 + .../eu/lixko/ts3j/client/net/HostButton.java | 19 + .../lixko/ts3j/client/net/IconRepository.java | 200 ++ .../lixko/ts3j/client/net/OfflineMessage.java | 39 + .../ts3j/client/net/OfflineMessageAdmin.java | 163 ++ .../ts3j/client/net/PictureDownloads.java | 202 ++ .../lixko/ts3j/client/net/PrivilegeKey.java | 36 + .../ts3j/client/net/PrivilegeKeyAdmin.java | 90 + .../lixko/ts3j/client/net/ServerLogAdmin.java | 82 + .../lixko/ts3j/client/net/ServerLogEntry.java | 49 + .../lixko/ts3j/client/net/ServerLogPage.java | 15 + .../eu/lixko/ts3j/client/net/ServerModel.java | 612 +++++ .../eu/lixko/ts3j/client/net/Spacers.java | 83 + .../ts3j/client/net/TeamspeakConnection.java | 1997 +++++++++++++++++ .../eu/lixko/ts3j/client/net/TreeMatch.java | 22 + .../eu/lixko/ts3j/client/net/Whisper.java | 76 + .../lixko/ts3j/client/net/avatar/Avatar.java | 17 + .../ts3j/client/net/avatar/AvatarNaming.java | 67 + .../client/net/avatar/AvatarRepository.java | 148 ++ .../ts3j/client/net/avatar/ImageFormat.java | 22 + .../lixko/ts3j/client/net/ban/BanEntry.java | 107 + .../lixko/ts3j/client/net/ban/BanPattern.java | 126 ++ .../eu/lixko/ts3j/client/net/ban/BanRule.java | 44 + .../eu/lixko/ts3j/client/net/ban/BanUnit.java | 45 + .../client/net/filetransfer/FileTransfer.java | 156 ++ .../net/filetransfer/FileTransferManager.java | 522 +++++ .../client/net/filetransfer/RemoteFile.java | 49 + .../ts3j/client/proto/ProtobufReader.java | 107 + .../ts3j/client/proto/ProtobufWriter.java | 47 + .../ts3j/client/recording/MixdownSink.java | 85 + .../ts3j/client/recording/MultitrackSink.java | 242 ++ .../ts3j/client/recording/OggOpusStream.java | 55 + .../client/recording/RecordingEncoders.java | 33 + .../ts3j/client/recording/RecordingSink.java | 26 + .../eu/lixko/ts3j/client/recording/Track.java | 49 + .../ts3j/client/recording/VoiceRecorder.java | 171 ++ .../lixko/ts3j/client/session/SelfState.java | 36 + .../lixko/ts3j/client/session/ServerLink.java | 145 ++ .../ts3j/client/session/ServerSession.java | 844 +++++++ .../lixko/ts3j/client/session/Sessions.java | 165 ++ .../client/sound/NotificationSettings.java | 91 + .../lixko/ts3j/client/sound/OggOpusFile.java | 148 ++ .../ts3j/client/sound/PackSoundPlayer.java | 229 ++ .../lixko/ts3j/client/sound/SoundEvent.java | 220 ++ .../ts3j/client/sound/SoundNotifier.java | 165 ++ .../eu/lixko/ts3j/client/sound/SoundPack.java | 167 ++ .../ts3j/client/sound/SoundPackConverter.java | 54 + .../lixko/ts3j/client/sound/SoundPacks.java | 53 + .../lixko/ts3j/client/sound/SoundPlayer.java | 33 + .../lixko/ts3j/client/sound/SoundScript.java | 60 + .../eu/lixko/ts3j/client/sound/WaveFile.java | 112 + .../ts3j/client/teamspeak/SqliteReader.java | 288 +++ .../lixko/ts3j/client/teamspeak/SyncItem.java | 42 + .../client/teamspeak/SyncItemDecoder.java | 107 + .../ts3j/client/teamspeak/SyncOrder.java | 69 + .../client/teamspeak/TeamSpeakImporter.java | 227 ++ .../client/teamspeak/TeamSpeakSettingsDb.java | 100 + .../eu/lixko/ts3j/client/text/BBCode.java | 303 +++ .../eu/lixko/ts3j/client/text/ChatHtml.java | 152 ++ .../eu/lixko/ts3j/client/text/HtmlText.java | 56 + .../java/eu/lixko/ts3j/client/text/Json.java | 167 ++ .../eu/lixko/ts3j/client/text/TextQuery.java | 86 + .../eu/lixko/ts3j/client/text/TsLink.java | 120 + .../java/com/ts3client/audio/FakeOpus.java | 70 - .../com/ts3client/audio/JitterBufferTest.java | 374 --- .../com/ts3client/audio/MixedPlayoutTest.java | 102 - .../com/ts3client/audio/VoiceStreamTest.java | 246 -- .../audio/processing/AudioProcessorTest.java | 194 -- .../com/ts3client/audio/vad/RealFftTest.java | 58 - .../com/ts3client/audio/vad/RnnVadTest.java | 129 -- .../ts3client/chatlog/ChatLogStoreTest.java | 99 - .../ts3client/config/IdentityStoreTest.java | 72 - .../ts3client/config/ProfileFilesTest.java | 49 - .../config/ServerLogSettingsTest.java | 77 - .../com/ts3client/config/SettingsTest.java | 74 - .../ts3client/contacts/ContactStoreTest.java | 121 - .../com/ts3client/contacts/ContactTest.java | 83 - .../com/ts3client/gfx/CountryFlagsTest.java | 22 - .../java/com/ts3client/gfx/IconPackTest.java | 160 -- .../ts3client/hotkey/HotkeyEngineTest.java | 120 - .../com/ts3client/myts/AccountInfoTest.java | 33 - .../ts3client/myts/ChatAttachmentTest.java | 69 - .../ts3client/myts/MyTeamSpeakLoginTest.java | 65 - .../com/ts3client/myts/MyTeamSpeakTest.java | 125 -- .../com/ts3client/myts/MyTsCryptoTest.java | 117 - .../com/ts3client/myts/MyTsFilesTest.java | 88 - .../net/ConnectionEventHandlerTest.java | 211 -- .../java/com/ts3client/net/DetailsTest.java | 47 - .../com/ts3client/net/EventFieldsTest.java | 40 - .../com/ts3client/net/ServerLogEntryTest.java | 39 - .../ts3client/net/ServerModelRulesTest.java | 59 - .../ts3client/net/ServerModelTreeTest.java | 101 - .../net/avatar/AvatarNamingTest.java | 39 - .../net/avatar/AvatarRepositoryTest.java | 83 - .../ts3client/net/avatar/ImageFormatTest.java | 20 - .../com/ts3client/net/ban/BanPatternTest.java | 67 - .../com/ts3client/net/ban/BanUnitTest.java | 24 - .../com/ts3client/session/ServerLinkTest.java | 62 - .../sound/NotificationSettingsTest.java | 51 - .../com/ts3client/sound/SoundPackTest.java | 89 - .../com/ts3client/sound/WaveFileTest.java | 74 - .../ts3client/teamspeak/SyncItemsTest.java | 82 - .../ts3client/teamspeak/SyncOrderTest.java | 55 - .../teamspeak/TeamSpeakImporterTest.java | 130 -- .../teamspeak/TeamSpeakSettingsDbTest.java | 64 - .../com/ts3client/text/BBCodeLinksTest.java | 48 - .../com/ts3client/text/BBCodePlainTest.java | 15 - .../com/ts3client/text/BBCodeTagsTest.java | 67 - .../text/ChatHtmlAttachmentTest.java | 58 - .../com/ts3client/text/TextQueryTest.java | 47 - .../eu/lixko/ts3j/client/audio/FakeOpus.java | 70 + .../ts3j/client/audio/JitterBufferTest.java | 374 +++ .../ts3j/client/audio/MixedPlayoutTest.java | 102 + .../ts3j/client/audio/VoiceStreamTest.java | 246 ++ .../audio/processing/AudioProcessorTest.java | 194 ++ .../ts3j/client/audio/vad/RealFftTest.java | 58 + .../ts3j/client/audio/vad/RnnVadTest.java | 129 ++ .../ts3j/client/chatlog/ChatLogStoreTest.java | 99 + .../ts3j/client/config/IdentityStoreTest.java | 72 + .../ts3j/client/config/ProfileFilesTest.java | 49 + .../client/config/ServerLogSettingsTest.java | 77 + .../ts3j/client/config/SettingsTest.java | 74 + .../client/contacts/ContactStoreTest.java | 121 + .../ts3j/client/contacts/ContactTest.java | 83 + .../ts3j/client/gfx/CountryFlagsTest.java | 22 + .../lixko/ts3j/client/gfx/IconPackTest.java | 160 ++ .../ts3j/client/hotkey/HotkeyEngineTest.java | 120 + .../ts3j/client/myts/AccountInfoTest.java | 33 + .../ts3j/client/myts/ChatAttachmentTest.java | 69 + .../client/myts/MyTeamSpeakLoginTest.java | 65 + .../ts3j/client/myts/MyTeamSpeakTest.java | 125 ++ .../ts3j/client/myts/MyTsCryptoTest.java | 117 + .../lixko/ts3j/client/myts/MyTsFilesTest.java | 88 + .../net/ConnectionEventHandlerTest.java | 211 ++ .../eu/lixko/ts3j/client/net/DetailsTest.java | 47 + .../ts3j/client/net/EventFieldsTest.java | 40 + .../ts3j/client/net/ServerLogEntryTest.java | 39 + .../ts3j/client/net/ServerModelRulesTest.java | 59 + .../ts3j/client/net/ServerModelTreeTest.java | 101 + .../client/net/avatar/AvatarNamingTest.java | 39 + .../net/avatar/AvatarRepositoryTest.java | 83 + .../client/net/avatar/ImageFormatTest.java | 20 + .../ts3j/client/net/ban/BanPatternTest.java | 67 + .../ts3j/client/net/ban/BanUnitTest.java | 24 + .../ts3j/client/session/ServerLinkTest.java | 62 + .../sound/NotificationSettingsTest.java | 51 + .../ts3j/client/sound/SoundPackTest.java | 89 + .../lixko/ts3j/client/sound/WaveFileTest.java | 74 + .../ts3j/client/teamspeak/SyncItemsTest.java | 82 + .../ts3j/client/teamspeak/SyncOrderTest.java | 55 + .../teamspeak/TeamSpeakImporterTest.java | 130 ++ .../teamspeak/TeamSpeakSettingsDbTest.java | 64 + .../ts3j/client/text/BBCodeLinksTest.java | 48 + .../ts3j/client/text/BBCodePlainTest.java | 15 + .../ts3j/client/text/BBCodeTagsTest.java | 67 + .../client/text/ChatHtmlAttachmentTest.java | 58 + .../lixko/ts3j/client/text/TextQueryTest.java | 47 + .../client}/audio/processing/golden-ns0.s16 | Bin .../audio/processing/golden-ns1-typing.s16 | Bin .../client}/audio/processing/golden-ns1.s16 | Bin .../client}/audio/processing/golden-ns2.s16 | Bin .../client}/audio/processing/golden-ns3.s16 | Bin ts3-client/desktop/pom.xml | 6 +- .../ts3client/audio/desktop/AudioDevices.java | 210 -- .../audio/desktop/DesktopAudioBackend.java | 50 - .../audio/desktop/EncodeSoundPacks.java | 26 - .../audio/desktop/JavaSoundCapture.java | 51 - .../audio/desktop/JavaSoundPlayback.java | 53 - .../audio/desktop/NativeOpusCodec.java | 25 - .../audio/desktop/NativeOpusDecoder.java | 97 - .../audio/desktop/NativeOpusEncoder.java | 95 - .../com/ts3client/audio/desktop/Opus.java | 264 --- .../audio/desktop/pipewire/PcmRing.java | 141 -- .../audio/desktop/pipewire/PipeWire.java | 78 - .../desktop/pipewire/PipeWireCapture.java | 28 - .../desktop/pipewire/PipeWireLibrary.java | 409 ---- .../desktop/pipewire/PipeWirePlayback.java | 49 - .../desktop/pipewire/PipeWireSession.java | 287 --- .../desktop/pipewire/PipeWireStream.java | 222 -- .../audio/desktop/pipewire/SpaPod.java | 161 -- .../hotkey/desktop/DesktopInputHooks.java | 102 - .../hotkey/desktop/EvdevInputHook.java | 151 -- .../ts3client/hotkey/desktop/KeyNames.java | 47 - .../ts3client/hotkey/desktop/RawInput.java | 109 - .../com/ts3client/hotkey/desktop/Win32.java | 210 -- .../hotkey/desktop/WindowsInputHook.java | 234 -- .../hotkey/desktop/WindowsKeyNamer.java | 37 - .../ts3client/hotkey/desktop/X11KeyNamer.java | 47 - .../hotkey/desktop/XInput2InputHook.java | 206 -- .../hotkey/desktop/XRecordInputHook.java | 212 -- .../com/ts3client/hotkey/desktop/Xlib.java | 400 ---- .../notify/desktop/DBusConnection.java | 215 -- .../ts3client/notify/desktop/DBusWire.java | 322 --- .../notify/desktop/DesktopNotifications.java | 36 - .../desktop/FreedesktopNotifications.java | 126 -- .../client/audio/desktop/AudioDevices.java | 210 ++ .../audio/desktop/DesktopAudioBackend.java | 50 + .../audio/desktop/EncodeSoundPacks.java | 26 + .../audio/desktop/JavaSoundCapture.java | 51 + .../audio/desktop/JavaSoundPlayback.java | 53 + .../client/audio/desktop/NativeOpusCodec.java | 25 + .../audio/desktop/NativeOpusDecoder.java | 97 + .../audio/desktop/NativeOpusEncoder.java | 95 + .../lixko/ts3j/client/audio/desktop/Opus.java | 264 +++ .../audio/desktop/pipewire/PcmRing.java | 141 ++ .../audio/desktop/pipewire/PipeWire.java | 78 + .../desktop/pipewire/PipeWireCapture.java | 28 + .../desktop/pipewire/PipeWireLibrary.java | 409 ++++ .../desktop/pipewire/PipeWirePlayback.java | 49 + .../desktop/pipewire/PipeWireSession.java | 287 +++ .../desktop/pipewire/PipeWireStream.java | 222 ++ .../client/audio/desktop/pipewire/SpaPod.java | 161 ++ .../hotkey/desktop/DesktopInputHooks.java | 102 + .../client/hotkey/desktop/EvdevInputHook.java | 151 ++ .../ts3j/client/hotkey/desktop/KeyNames.java | 47 + .../ts3j/client/hotkey/desktop/RawInput.java | 109 + .../ts3j/client/hotkey/desktop/Win32.java | 210 ++ .../hotkey/desktop/WindowsInputHook.java | 234 ++ .../hotkey/desktop/WindowsKeyNamer.java | 37 + .../client/hotkey/desktop/X11KeyNamer.java | 47 + .../hotkey/desktop/XInput2InputHook.java | 206 ++ .../hotkey/desktop/XRecordInputHook.java | 212 ++ .../ts3j/client/hotkey/desktop/Xlib.java | 400 ++++ .../client/notify/desktop/DBusConnection.java | 215 ++ .../ts3j/client/notify/desktop/DBusWire.java | 322 +++ .../notify/desktop/DesktopNotifications.java | 36 + .../desktop/FreedesktopNotifications.java | 126 ++ .../audio/desktop/pipewire/SpaPodTest.java | 44 - .../hotkey/desktop/RawInputTest.java | 92 - .../notify/desktop/DBusWireTest.java | 47 - .../recording/LibOpusMultistream.java | 59 - .../recording/VoiceRecorderTest.java | 313 --- .../com/ts3client/sound/OggOpusFileTest.java | 65 - .../audio/desktop/pipewire/SpaPodTest.java | 44 + .../client/hotkey/desktop/RawInputTest.java | 92 + .../client/notify/desktop/DBusWireTest.java | 47 + .../client/recording/LibOpusMultistream.java | 59 + .../client/recording/VoiceRecorderTest.java | 313 +++ .../ts3j/client/sound/OggOpusFileTest.java | 65 + ts3-client/docs/myteamspeak/CRYPTO_RE_SALT.md | 6 +- ts3-client/docs/myteamspeak/IMPLEMENTATION.md | 2 +- ts3-client/docs/myteamspeak/PROTOCOL.md | 2 +- ts3-client/pom.xml | 8 +- ts3-client/swing/pom.xml | 16 +- .../src/main/java/com/ts3client/Main.java | 48 - .../com/ts3client/ui/ApplicationPanel.java | 35 - .../ui/AttachmentTransferHandler.java | 128 -- .../java/com/ts3client/ui/AudioDevices.java | 39 - .../java/com/ts3client/ui/AvatarActions.java | 76 - .../java/com/ts3client/ui/AvatarHtml.java | 61 - .../com/ts3client/ui/AwayMessagesDialog.java | 149 -- .../java/com/ts3client/ui/BanAddDialog.java | 257 --- .../main/java/com/ts3client/ui/BanDialog.java | 86 - .../com/ts3client/ui/BanDurationPicker.java | 86 - .../java/com/ts3client/ui/BanListDialog.java | 646 ------ .../com/ts3client/ui/BookmarksDialog.java | 318 --- .../java/com/ts3client/ui/CapturePanel.java | 129 -- .../ts3client/ui/ChannelAdvancedPanel.java | 199 -- .../com/ts3client/ui/ChannelAudioPanel.java | 153 -- .../java/com/ts3client/ui/ChannelDialog.java | 434 ---- .../java/com/ts3client/ui/ChannelMenu.java | 82 - .../ts3client/ui/ChannelPermissionsPanel.java | 151 -- .../ts3client/ui/ChannelStandardPanel.java | 197 -- .../ts3client/ui/ChatAttachmentActions.java | 145 -- .../java/com/ts3client/ui/ChatLogsPanel.java | 88 - .../main/java/com/ts3client/ui/ChatPanel.java | 761 ------- .../java/com/ts3client/ui/ChatSearch.java | 270 --- .../java/com/ts3client/ui/ClientMenu.java | 161 -- .../com/ts3client/ui/ClientVersionPanel.java | 187 -- .../com/ts3client/ui/ClientVolumeDialog.java | 80 - .../com/ts3client/ui/ComplaintsDialog.java | 511 ----- .../java/com/ts3client/ui/ConnectDialog.java | 130 -- .../ts3client/ui/ConnectionInfoDialog.java | 337 --- .../ts3client/ui/ContactDefaultsDialog.java | 201 -- .../java/com/ts3client/ui/ContactsDialog.java | 569 ----- .../java/com/ts3client/ui/ContactsPanel.java | 74 - .../com/ts3client/ui/CountryFlagIcons.java | 40 - .../ts3client/ui/DescriptionEditorDialog.java | 172 -- .../com/ts3client/ui/DescriptionPictures.java | 166 -- .../java/com/ts3client/ui/DesignPanel.java | 282 --- .../java/com/ts3client/ui/DesktopEntry.java | 140 -- .../com/ts3client/ui/DesktopNotifier.java | 159 -- .../main/java/com/ts3client/ui/Dialogs.java | 44 - .../java/com/ts3client/ui/DisplayScale.java | 134 -- .../ts3client/ui/DropDownToggleButton.java | 122 - .../com/ts3client/ui/DropIndicatorTree.java | 342 --- .../com/ts3client/ui/FileBrowserDialog.java | 482 ---- .../main/java/com/ts3client/ui/FindBar.java | 379 ---- .../main/java/com/ts3client/ui/FormPanel.java | 178 -- .../java/com/ts3client/ui/GiantPttWindow.java | 111 - .../java/com/ts3client/ui/GroupIcons.java | 140 -- .../java/com/ts3client/ui/HostButtonView.java | 74 - .../java/com/ts3client/ui/HotkeyActions.java | 170 -- .../com/ts3client/ui/HotkeyArguments.java | 16 - .../java/com/ts3client/ui/HotkeyDialog.java | 386 ---- .../java/com/ts3client/ui/HotkeyService.java | 111 - .../java/com/ts3client/ui/HotkeysPanel.java | 167 -- .../java/com/ts3client/ui/HtmlStyles.java | 213 -- .../com/ts3client/ui/IconChooserDialog.java | 272 --- .../main/java/com/ts3client/ui/IconFiles.java | 64 - .../main/java/com/ts3client/ui/IconTheme.java | 194 -- .../src/main/java/com/ts3client/ui/Icons.java | 487 ---- .../com/ts3client/ui/IdentitiesDialog.java | 432 ---- .../com/ts3client/ui/IdentityChooser.java | 65 - .../main/java/com/ts3client/ui/InfoPanel.java | 479 ---- .../com/ts3client/ui/InstanceChannel.java | 81 - .../java/com/ts3client/ui/LevelMeter.java | 88 - .../src/main/java/com/ts3client/ui/Links.java | 46 - .../com/ts3client/ui/ListEditorDialog.java | 184 -- .../com/ts3client/ui/LookAndFeelManager.java | 52 - .../main/java/com/ts3client/ui/MainFrame.java | 1170 ---------- .../java/com/ts3client/ui/MainMenuBar.java | 449 ---- .../java/com/ts3client/ui/MainToolbar.java | 237 -- .../java/com/ts3client/ui/MicrophoneTest.java | 182 -- .../com/ts3client/ui/MyTeamSpeakPanel.java | 394 ---- .../java/com/ts3client/ui/NetworkPanel.java | 150 -- .../com/ts3client/ui/NicknameCellEditor.java | 125 -- .../com/ts3client/ui/NotificationsPanel.java | 412 ---- .../ui/OfflineMessageComposeDialog.java | 457 ---- .../ts3client/ui/OfflineMessagesDialog.java | 573 ----- .../java/com/ts3client/ui/OptionsPage.java | 26 - .../java/com/ts3client/ui/OptionsSidebar.java | 109 - .../java/com/ts3client/ui/PictureViewer.java | 78 - .../java/com/ts3client/ui/PlaybackPanel.java | 62 - .../ui/PrivilegeKeyCreateDialog.java | 168 -- .../com/ts3client/ui/PrivilegeKeysDialog.java | 355 --- .../java/com/ts3client/ui/ReasonDialog.java | 99 - .../com/ts3client/ui/RecordingActions.java | 51 - .../java/com/ts3client/ui/RowColorCombo.java | 123 - .../com/ts3client/ui/ServerGroupsDialog.java | 107 - .../com/ts3client/ui/ServerLogDialog.java | 364 --- .../ts3client/ui/ServerLogExcludeDialog.java | 27 - .../ui/ServerLogHighlightDialog.java | 145 -- .../java/com/ts3client/ui/ServerMenu.java | 28 - .../main/java/com/ts3client/ui/ServerTab.java | 371 --- .../ui/ServerTabConnectionEvents.java | 209 -- .../java/com/ts3client/ui/ServerTabPane.java | 198 -- .../ts3client/ui/ServerTabTreeActions.java | 366 --- .../ts3client/ui/ServerTreeCellRenderer.java | 118 - .../ts3client/ui/ServerTreeDragAndDrop.java | 236 -- .../com/ts3client/ui/ServerTreePanel.java | 493 ---- .../com/ts3client/ui/ServerTreeSearch.java | 233 -- .../java/com/ts3client/ui/SettingsDialog.java | 224 -- .../main/java/com/ts3client/ui/Spinners.java | 29 - .../main/java/com/ts3client/ui/StatusBar.java | 82 - .../java/com/ts3client/ui/TabDragReorder.java | 285 --- .../main/java/com/ts3client/ui/TextZoom.java | 109 - .../src/main/java/com/ts3client/ui/Theme.java | 183 -- .../java/com/ts3client/ui/TrayController.java | 253 --- .../com/ts3client/ui/TrayNotifications.java | 36 - .../ts3client/ui/VoiceActivationSection.java | 336 --- .../java/com/ts3client/ui/WindowClass.java | 46 - .../java/com/ts3client/ui/tray/AwtTray.java | 107 - .../com/ts3client/ui/tray/TrayBackend.java | 51 - .../java/com/ts3client/ui/tray/TrayLog.java | 20 - .../main/java/com/ts3client/ui/tray/X11.java | 470 ---- .../java/com/ts3client/ui/tray/X11Tray.java | 508 ----- .../main/java/eu/lixko/ts3j/client/Main.java | 48 + .../ts3j/client/ui/ApplicationPanel.java | 35 + .../client/ui/AttachmentTransferHandler.java | 128 ++ .../eu/lixko/ts3j/client/ui/AudioDevices.java | 39 + .../lixko/ts3j/client/ui/AvatarActions.java | 76 + .../eu/lixko/ts3j/client/ui/AvatarHtml.java | 61 + .../ts3j/client/ui/AwayMessagesDialog.java | 149 ++ .../eu/lixko/ts3j/client/ui/BanAddDialog.java | 257 +++ .../eu/lixko/ts3j/client/ui/BanDialog.java | 86 + .../ts3j/client/ui/BanDurationPicker.java | 86 + .../lixko/ts3j/client/ui/BanListDialog.java | 646 ++++++ .../lixko/ts3j/client/ui/BookmarksDialog.java | 318 +++ .../eu/lixko/ts3j/client/ui/CapturePanel.java | 129 ++ .../ts3j/client/ui/ChannelAdvancedPanel.java | 199 ++ .../ts3j/client/ui/ChannelAudioPanel.java | 153 ++ .../lixko/ts3j/client/ui/ChannelDialog.java | 434 ++++ .../eu/lixko/ts3j/client/ui/ChannelMenu.java | 82 + .../client/ui/ChannelPermissionsPanel.java | 151 ++ .../ts3j/client/ui/ChannelStandardPanel.java | 197 ++ .../ts3j/client/ui/ChatAttachmentActions.java | 145 ++ .../lixko/ts3j/client/ui/ChatLogsPanel.java | 88 + .../eu/lixko/ts3j/client/ui/ChatPanel.java | 761 +++++++ .../eu/lixko/ts3j/client/ui/ChatSearch.java | 270 +++ .../eu/lixko/ts3j/client/ui/ClientMenu.java | 161 ++ .../ts3j/client/ui/ClientVersionPanel.java | 187 ++ .../ts3j/client/ui/ClientVolumeDialog.java | 80 + .../ts3j/client/ui/ComplaintsDialog.java | 511 +++++ .../lixko/ts3j/client/ui/ConnectDialog.java | 130 ++ .../ts3j/client/ui/ConnectionInfoDialog.java | 337 +++ .../ts3j/client/ui/ContactDefaultsDialog.java | 201 ++ .../lixko/ts3j/client/ui/ContactsDialog.java | 569 +++++ .../lixko/ts3j/client/ui/ContactsPanel.java | 74 + .../ts3j/client/ui/CountryFlagIcons.java | 40 + .../client/ui/DescriptionEditorDialog.java | 172 ++ .../ts3j/client/ui/DescriptionPictures.java | 166 ++ .../eu/lixko/ts3j/client/ui/DesignPanel.java | 282 +++ .../eu/lixko/ts3j/client/ui/DesktopEntry.java | 140 ++ .../lixko/ts3j/client/ui/DesktopNotifier.java | 159 ++ .../java/eu/lixko/ts3j/client/ui/Dialogs.java | 44 + .../eu/lixko/ts3j/client/ui/DisplayScale.java | 134 ++ .../ts3j/client/ui/DropDownToggleButton.java | 122 + .../ts3j/client/ui/DropIndicatorTree.java | 342 +++ .../ts3j/client/ui/FileBrowserDialog.java | 482 ++++ .../java/eu/lixko/ts3j/client/ui/FindBar.java | 379 ++++ .../eu/lixko/ts3j/client/ui/FormPanel.java | 178 ++ .../lixko/ts3j/client/ui/GiantPttWindow.java | 111 + .../eu/lixko/ts3j/client/ui/GroupIcons.java | 140 ++ .../lixko/ts3j/client/ui/HostButtonView.java | 74 + .../lixko/ts3j/client/ui/HotkeyActions.java | 170 ++ .../lixko/ts3j/client/ui/HotkeyArguments.java | 16 + .../eu/lixko/ts3j/client/ui/HotkeyDialog.java | 386 ++++ .../lixko/ts3j/client/ui/HotkeyService.java | 111 + .../eu/lixko/ts3j/client/ui/HotkeysPanel.java | 167 ++ .../eu/lixko/ts3j/client/ui/HtmlStyles.java | 213 ++ .../ts3j/client/ui/IconChooserDialog.java | 272 +++ .../eu/lixko/ts3j/client/ui/IconFiles.java | 64 + .../eu/lixko/ts3j/client/ui/IconTheme.java | 194 ++ .../java/eu/lixko/ts3j/client/ui/Icons.java | 487 ++++ .../ts3j/client/ui/IdentitiesDialog.java | 432 ++++ .../lixko/ts3j/client/ui/IdentityChooser.java | 65 + .../eu/lixko/ts3j/client/ui/InfoPanel.java | 479 ++++ .../lixko/ts3j/client/ui/InstanceChannel.java | 81 + .../eu/lixko/ts3j/client/ui/LevelMeter.java | 88 + .../java/eu/lixko/ts3j/client/ui/Links.java | 46 + .../ts3j/client/ui/ListEditorDialog.java | 184 ++ .../ts3j/client/ui/LookAndFeelManager.java | 52 + .../eu/lixko/ts3j/client/ui/MainFrame.java | 1170 ++++++++++ .../eu/lixko/ts3j/client/ui/MainMenuBar.java | 449 ++++ .../eu/lixko/ts3j/client/ui/MainToolbar.java | 237 ++ .../lixko/ts3j/client/ui/MicrophoneTest.java | 182 ++ .../ts3j/client/ui/MyTeamSpeakPanel.java | 394 ++++ .../eu/lixko/ts3j/client/ui/NetworkPanel.java | 150 ++ .../ts3j/client/ui/NicknameCellEditor.java | 125 ++ .../ts3j/client/ui/NotificationsPanel.java | 412 ++++ .../ui/OfflineMessageComposeDialog.java | 457 ++++ .../ts3j/client/ui/OfflineMessagesDialog.java | 573 +++++ .../eu/lixko/ts3j/client/ui/OptionsPage.java | 26 + .../lixko/ts3j/client/ui/OptionsSidebar.java | 109 + .../lixko/ts3j/client/ui/PictureViewer.java | 78 + .../lixko/ts3j/client/ui/PlaybackPanel.java | 62 + .../client/ui/PrivilegeKeyCreateDialog.java | 168 ++ .../ts3j/client/ui/PrivilegeKeysDialog.java | 355 +++ .../eu/lixko/ts3j/client/ui/ReasonDialog.java | 99 + .../ts3j/client/ui/RecordingActions.java | 51 + .../lixko/ts3j/client/ui/RowColorCombo.java | 123 + .../ts3j/client/ui/ServerGroupsDialog.java | 107 + .../lixko/ts3j/client/ui/ServerLogDialog.java | 364 +++ .../client/ui/ServerLogExcludeDialog.java | 27 + .../client/ui/ServerLogHighlightDialog.java | 145 ++ .../eu/lixko/ts3j/client/ui/ServerMenu.java | 28 + .../eu/lixko/ts3j/client/ui/ServerTab.java | 371 +++ .../client/ui/ServerTabConnectionEvents.java | 209 ++ .../lixko/ts3j/client/ui/ServerTabPane.java | 198 ++ .../ts3j/client/ui/ServerTabTreeActions.java | 366 +++ .../client/ui/ServerTreeCellRenderer.java | 118 + .../ts3j/client/ui/ServerTreeDragAndDrop.java | 236 ++ .../lixko/ts3j/client/ui/ServerTreePanel.java | 493 ++++ .../ts3j/client/ui/ServerTreeSearch.java | 233 ++ .../lixko/ts3j/client/ui/SettingsDialog.java | 224 ++ .../eu/lixko/ts3j/client/ui/Spinners.java | 29 + .../eu/lixko/ts3j/client/ui/StatusBar.java | 82 + .../lixko/ts3j/client/ui/TabDragReorder.java | 285 +++ .../eu/lixko/ts3j/client/ui/TextZoom.java | 109 + .../java/eu/lixko/ts3j/client/ui/Theme.java | 183 ++ .../lixko/ts3j/client/ui/TrayController.java | 253 +++ .../ts3j/client/ui/TrayNotifications.java | 36 + .../client/ui/VoiceActivationSection.java | 336 +++ .../eu/lixko/ts3j/client/ui/WindowClass.java | 46 + .../eu/lixko/ts3j/client/ui/tray/AwtTray.java | 107 + .../ts3j/client/ui/tray/TrayBackend.java | 51 + .../eu/lixko/ts3j/client/ui/tray/TrayLog.java | 20 + .../eu/lixko/ts3j/client/ui/tray/X11.java | 470 ++++ .../eu/lixko/ts3j/client/ui/tray/X11Tray.java | 508 +++++ .../lixko/ts3j/client}/ui/app-icon-small.svg | 0 .../lixko/ts3j/client}/ui/app-icon.svg | 0 .../client}/ui/laf/FlatDarkLaf.properties | 0 .../ts3j/client}/ui/laf/FlatLaf.properties | 0 .../com/ts3client/ui/DisplayScaleTest.java | 32 - .../com/ts3client/ui/MicrophoneTestTest.java | 48 - .../ts3j/client/ui/DisplayScaleTest.java | 32 + .../ts3j/client/ui/MicrophoneTestTest.java | 48 + ts3-client/tools/AppIcon.java | 2 +- 920 files changed, 69645 insertions(+), 69645 deletions(-) delete mode 100644 android/app/src/main/java/com/ts3client/android/AudioRoutePrefs.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/BookmarkShortcuts.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/Chats.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ConnectionService.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/FileTransfers.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/IconTheme.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/IdentityManager.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/LevelMonitor.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/LocalCopy.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/MainActivity.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/MessageNotifier.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/NetworkFollower.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/Picture.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/PttOverlay.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ReplyReceiver.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/SavedPictures.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ServerController.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ServerImages.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ServerTree.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/SessionController.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/SoundPackInstaller.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/SpeakingSoundPlayer.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/Ts3Application.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/WebPictures.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/App.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/Attachments.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/BanListScreen.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/BookmarkScreen.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/ChannelEditScreen.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/ChannelTree.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/ChatPane.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/ChatText.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/ConnectScreen.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/ConnectionInfoScreen.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/ContactsScreen.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/DetailsSection.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/FilesScreen.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/FindBar.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/HostButton.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/IdentitiesScreen.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/Moderation.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/MyTeamSpeakScreen.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/NetworkSettingsScreen.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/PackIcon.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/PictureViewer.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/PushToTalk.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/RowColorPicker.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/ServerImage.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/ServerScreen.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/SettingsScreen.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/SettingsWidgets.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/Sheets.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/SoundSettingsScreen.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/Theme.kt delete mode 100644 android/app/src/main/java/com/ts3client/android/ui/Whisper.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/AudioRoutePrefs.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/BookmarkShortcuts.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/Chats.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ConnectionService.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/FileTransfers.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/IconTheme.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/IdentityManager.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/LevelMonitor.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/LocalCopy.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/MainActivity.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/MessageNotifier.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/NetworkFollower.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/Picture.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/PttOverlay.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ReplyReceiver.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/SavedPictures.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ServerImages.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ServerTree.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/SessionController.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/SoundPackInstaller.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/SpeakingSoundPlayer.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/Ts3Application.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/WebPictures.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/App.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Attachments.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/BanListScreen.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/BookmarkScreen.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChannelEditScreen.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChannelTree.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChatPane.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChatText.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ConnectScreen.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ConnectionInfoScreen.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ContactsScreen.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/DetailsSection.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/FilesScreen.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/FindBar.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/HostButton.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/IdentitiesScreen.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Moderation.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/MyTeamSpeakScreen.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/NetworkSettingsScreen.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/PackIcon.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/PictureViewer.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/PushToTalk.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/RowColorPicker.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerImage.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SettingsScreen.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SettingsWidgets.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Sheets.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SoundSettingsScreen.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Theme.kt create mode 100644 android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Whisper.kt delete mode 100644 android/audio/src/main/java/com/ts3client/android/audio/AndroidAudioBackend.java delete mode 100644 android/audio/src/main/java/com/ts3client/android/audio/AndroidAudioIo.java delete mode 100644 android/audio/src/main/java/com/ts3client/android/audio/AudioRoute.java delete mode 100644 android/audio/src/main/java/com/ts3client/android/audio/NativeOpus.java delete mode 100644 android/audio/src/main/java/com/ts3client/android/audio/OboeLine.java create mode 100644 android/audio/src/main/java/eu/lixko/ts3j/client/android/audio/AndroidAudioBackend.java create mode 100644 android/audio/src/main/java/eu/lixko/ts3j/client/android/audio/AndroidAudioIo.java create mode 100644 android/audio/src/main/java/eu/lixko/ts3j/client/android/audio/AudioRoute.java create mode 100644 android/audio/src/main/java/eu/lixko/ts3j/client/android/audio/NativeOpus.java create mode 100644 android/audio/src/main/java/eu/lixko/ts3j/client/android/audio/OboeLine.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/AudioBackend.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/AudioCapture.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/AudioDevice.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/AudioFrameListener.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/AudioIo.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/AudioPlayback.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/CaptureVoiceInput.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/Fft.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/InputLevel.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/JitterBuffer.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/MixedPlayout.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/OpusParameters.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/Pcm16.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/PerSpeakerPlayout.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/Playout.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/SpeechProbabilityDetector.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/StreamingVoiceOutput.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/VoiceFormat.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/VoiceInput.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/VoiceOutput.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/VoiceReceiveStats.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/VoiceStream.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/VoiceTap.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/ogg/OggPageWriter.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/ogg/OpusHeaders.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/ogg/SelfDelimitedOpus.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/opus/CtlOpusEncoder.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/opus/LibOpus.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/opus/OpusCodec.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/opus/OpusDecoder.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/opus/OpusEncoder.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/AudioProcessor.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/HighPassFilter.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/ThreeBandFilterBank.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/AdaptiveDigitalConfig.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/AdaptiveDigitalGainController.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/Agc2Common.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/GainApplier.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/GainController2.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/InterpolatedGainCurve.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/Limiter.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/NoiseFloorEstimator.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/SaturationProtector.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/SpeechLevelEstimator.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/FastMath.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/NoiseEstimator.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/NoiseSuppressor.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/NsCommon.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/QuantileNoiseEstimator.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/SignalModelEstimator.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/SpeechProbabilityEstimator.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/SuppressionLevel.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/WienerFilter.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/transients/TransientDetector.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/transients/TransientSuppressor.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/processing/transients/WaveletPacketTree.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/vad/LinearPrediction.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/vad/PitchEstimator.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/vad/RealFft.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/vad/RnnNetwork.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/vad/RnnSpeechDetector.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/vad/RnnVad.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/vad/RnnVadWeights.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/vad/SpectralFeatures.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/audio/vad/VadConstants.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/chatlog/ChatLogScope.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/chatlog/ChatLogStore.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/config/AppDirs.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/config/AwayMessages.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/config/BanReasonPresets.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/config/Bookmark.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/config/Bookmarks.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/config/ClientRowColors.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/config/ClientVersion.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/config/IdentityEntry.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/config/IdentityStore.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/config/InstallDirs.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/config/ProfileFiles.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/config/ServerLogSettings.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/config/Settings.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/config/WhisperList.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/config/WhisperLists.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/contacts/Contact.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/contacts/ContactDefaults.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/contacts/ContactStore.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/contacts/ContactType.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/contacts/NicknameDisplay.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/gfx/CountryFlags.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/gfx/IconKeys.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/gfx/IconPack.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/gfx/IconPacks.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/hotkey/GlobalInputHook.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/hotkey/Hotkey.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/hotkey/HotkeyAction.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/hotkey/HotkeyCombo.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/hotkey/HotkeyEngine.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/hotkey/HotkeyKey.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/hotkey/Hotkeys.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/myts/AccountInfo.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/myts/ChatAttachment.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/myts/ChatAttachments.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/myts/MyTeamSpeak.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/myts/MyTeamSpeakLogin.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/myts/MyTsCrypto.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/myts/MyTsException.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/myts/MyTsFiles.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/myts/MyTsTransport.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/AvatarAdmin.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/BanAdmin.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ChannelAdmin.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ChannelCodec.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ChannelNode.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ChannelSettings.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ClientEntry.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ClientStatus.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/Complaint.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ComplaintAdmin.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ConnectionEventHandler.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ConnectionListener.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ConnectionStats.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsCollector.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsFormat.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/DatabaseClient.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/Details.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/Group.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/GroupChoice.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/HostButton.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/IconRepository.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/OfflineMessage.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/OfflineMessageAdmin.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/PictureDownloads.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/PrivilegeKey.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/PrivilegeKeyAdmin.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ServerLogAdmin.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ServerLogEntry.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ServerLogPage.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ServerModel.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/Spacers.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/TeamspeakConnection.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/TreeMatch.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/Whisper.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/avatar/Avatar.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/avatar/AvatarNaming.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/avatar/AvatarRepository.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/avatar/ImageFormat.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ban/BanEntry.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ban/BanPattern.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ban/BanRule.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ban/BanUnit.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/filetransfer/FileTransfer.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/filetransfer/FileTransferManager.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/net/filetransfer/RemoteFile.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/proto/ProtobufReader.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/proto/ProtobufWriter.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/recording/MixdownSink.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/recording/MultitrackSink.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/recording/OggOpusStream.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/recording/RecordingEncoders.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/recording/RecordingSink.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/recording/Track.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/recording/VoiceRecorder.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/session/SelfState.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/session/ServerLink.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/session/Sessions.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/sound/NotificationSettings.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/sound/OggOpusFile.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/sound/PackSoundPlayer.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/sound/SoundEvent.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/sound/SoundNotifier.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/sound/SoundPack.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/sound/SoundPackConverter.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/sound/SoundPacks.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/sound/SoundPlayer.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/sound/SoundScript.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/sound/WaveFile.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/teamspeak/SqliteReader.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/teamspeak/SyncItem.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/teamspeak/SyncItemDecoder.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/teamspeak/SyncOrder.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/teamspeak/TeamSpeakImporter.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/teamspeak/TeamSpeakSettingsDb.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/text/BBCode.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/text/ChatHtml.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/text/HtmlText.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/text/Json.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/text/TextQuery.java delete mode 100644 ts3-client/core/src/main/java/com/ts3client/text/TsLink.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioBackend.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioCapture.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioDevice.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioFrameListener.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioIo.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioPlayback.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/CaptureVoiceInput.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/Fft.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/InputLevel.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/JitterBuffer.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/MixedPlayout.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/OpusParameters.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/Pcm16.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/PerSpeakerPlayout.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/Playout.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/SpeechProbabilityDetector.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/StreamingVoiceOutput.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceFormat.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceInput.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceOutput.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceReceiveStats.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceStream.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceTap.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/ogg/OggPageWriter.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/ogg/OpusHeaders.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/ogg/SelfDelimitedOpus.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/opus/CtlOpusEncoder.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/opus/LibOpus.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/opus/OpusCodec.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/opus/OpusDecoder.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/opus/OpusEncoder.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/AudioProcessor.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/HighPassFilter.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ThreeBandFilterBank.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/AdaptiveDigitalConfig.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/AdaptiveDigitalGainController.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/Agc2Common.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/GainApplier.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/GainController2.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/InterpolatedGainCurve.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/Limiter.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/NoiseFloorEstimator.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/SaturationProtector.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/SpeechLevelEstimator.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/FastMath.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/NoiseEstimator.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/NoiseSuppressor.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/NsCommon.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/QuantileNoiseEstimator.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/SignalModelEstimator.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/SpeechProbabilityEstimator.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/SuppressionLevel.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/WienerFilter.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/transients/TransientDetector.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/transients/TransientSuppressor.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/transients/WaveletPacketTree.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/LinearPrediction.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/PitchEstimator.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/RealFft.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/RnnNetwork.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/RnnSpeechDetector.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/RnnVad.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/RnnVadWeights.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/SpectralFeatures.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/VadConstants.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/chatlog/ChatLogScope.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/chatlog/ChatLogStore.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/AppDirs.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/AwayMessages.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/BanReasonPresets.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/Bookmark.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/Bookmarks.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/ClientRowColors.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/ClientVersion.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/IdentityEntry.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/IdentityStore.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/InstallDirs.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/ProfileFiles.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/ServerLogSettings.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/Settings.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/WhisperList.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/WhisperLists.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/contacts/Contact.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/contacts/ContactDefaults.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/contacts/ContactStore.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/contacts/ContactType.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/contacts/NicknameDisplay.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/gfx/CountryFlags.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/gfx/IconKeys.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/gfx/IconPack.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/gfx/IconPacks.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/GlobalInputHook.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/Hotkey.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/HotkeyAction.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/HotkeyCombo.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/HotkeyEngine.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/HotkeyKey.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/Hotkeys.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/AccountInfo.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/ChatAttachment.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/ChatAttachments.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTeamSpeak.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTeamSpeakLogin.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTsCrypto.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTsException.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTsFiles.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTsTransport.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/AvatarAdmin.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/BanAdmin.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelAdmin.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelCodec.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelNode.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelSettings.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ClientEntry.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ClientStatus.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Complaint.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ComplaintAdmin.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionEventHandler.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionListener.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionStats.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionStatsCollector.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionStatsFormat.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/DatabaseClient.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Details.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Group.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/GroupChoice.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/HostButton.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/IconRepository.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/OfflineMessage.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/OfflineMessageAdmin.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/PictureDownloads.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/PrivilegeKey.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/PrivilegeKeyAdmin.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerLogAdmin.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerLogEntry.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerLogPage.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerModel.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Spacers.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TreeMatch.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Whisper.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/avatar/Avatar.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/avatar/AvatarNaming.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/avatar/AvatarRepository.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/avatar/ImageFormat.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ban/BanEntry.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ban/BanPattern.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ban/BanRule.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ban/BanUnit.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/filetransfer/FileTransfer.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/filetransfer/FileTransferManager.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/filetransfer/RemoteFile.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/proto/ProtobufReader.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/proto/ProtobufWriter.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/MixdownSink.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/MultitrackSink.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/OggOpusStream.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/RecordingEncoders.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/RecordingSink.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/Track.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/VoiceRecorder.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/SelfState.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerLink.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/Sessions.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/NotificationSettings.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/OggOpusFile.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/PackSoundPlayer.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundEvent.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundNotifier.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundPack.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundPackConverter.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundPacks.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundPlayer.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundScript.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/WaveFile.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/SqliteReader.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/SyncItem.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/SyncItemDecoder.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/SyncOrder.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakImporter.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakSettingsDb.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/text/BBCode.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/text/ChatHtml.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/text/HtmlText.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/text/Json.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/text/TextQuery.java create mode 100644 ts3-client/core/src/main/java/eu/lixko/ts3j/client/text/TsLink.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/audio/FakeOpus.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/audio/JitterBufferTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/audio/MixedPlayoutTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/audio/VoiceStreamTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/audio/processing/AudioProcessorTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/audio/vad/RealFftTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/audio/vad/RnnVadTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/chatlog/ChatLogStoreTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/config/IdentityStoreTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/config/ProfileFilesTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/config/ServerLogSettingsTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/config/SettingsTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/contacts/ContactStoreTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/contacts/ContactTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/gfx/CountryFlagsTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/gfx/IconPackTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/hotkey/HotkeyEngineTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/myts/AccountInfoTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/myts/ChatAttachmentTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/myts/MyTeamSpeakLoginTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/myts/MyTeamSpeakTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/myts/MyTsCryptoTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/myts/MyTsFilesTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/net/ConnectionEventHandlerTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/net/DetailsTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/net/EventFieldsTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/net/ServerLogEntryTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/net/ServerModelRulesTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/net/ServerModelTreeTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/net/avatar/AvatarNamingTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/net/avatar/AvatarRepositoryTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/net/avatar/ImageFormatTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/net/ban/BanPatternTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/net/ban/BanUnitTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/session/ServerLinkTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/sound/NotificationSettingsTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/sound/SoundPackTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/sound/WaveFileTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/teamspeak/SyncItemsTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/teamspeak/SyncOrderTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/teamspeak/TeamSpeakImporterTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/teamspeak/TeamSpeakSettingsDbTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/text/BBCodeLinksTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/text/BBCodePlainTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/text/BBCodeTagsTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/text/ChatHtmlAttachmentTest.java delete mode 100644 ts3-client/core/src/test/java/com/ts3client/text/TextQueryTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/FakeOpus.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/JitterBufferTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/MixedPlayoutTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/VoiceStreamTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/processing/AudioProcessorTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/vad/RealFftTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/vad/RnnVadTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/chatlog/ChatLogStoreTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/config/IdentityStoreTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/config/ProfileFilesTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/config/ServerLogSettingsTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/config/SettingsTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/contacts/ContactStoreTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/contacts/ContactTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/gfx/CountryFlagsTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/gfx/IconPackTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/hotkey/HotkeyEngineTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/AccountInfoTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/ChatAttachmentTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/MyTeamSpeakLoginTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/MyTeamSpeakTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/MyTsCryptoTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/MyTsFilesTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ConnectionEventHandlerTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/DetailsTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/EventFieldsTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ServerLogEntryTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ServerModelRulesTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ServerModelTreeTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/avatar/AvatarNamingTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/avatar/AvatarRepositoryTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/avatar/ImageFormatTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ban/BanPatternTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ban/BanUnitTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/session/ServerLinkTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/sound/NotificationSettingsTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/sound/SoundPackTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/sound/WaveFileTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/teamspeak/SyncItemsTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/teamspeak/SyncOrderTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakImporterTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakSettingsDbTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/text/BBCodeLinksTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/text/BBCodePlainTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/text/BBCodeTagsTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/text/ChatHtmlAttachmentTest.java create mode 100644 ts3-client/core/src/test/java/eu/lixko/ts3j/client/text/TextQueryTest.java rename ts3-client/core/src/test/resources/{com/ts3client => eu/lixko/ts3j/client}/audio/processing/golden-ns0.s16 (100%) rename ts3-client/core/src/test/resources/{com/ts3client => eu/lixko/ts3j/client}/audio/processing/golden-ns1-typing.s16 (100%) rename ts3-client/core/src/test/resources/{com/ts3client => eu/lixko/ts3j/client}/audio/processing/golden-ns1.s16 (100%) rename ts3-client/core/src/test/resources/{com/ts3client => eu/lixko/ts3j/client}/audio/processing/golden-ns2.s16 (100%) rename ts3-client/core/src/test/resources/{com/ts3client => eu/lixko/ts3j/client}/audio/processing/golden-ns3.s16 (100%) delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/AudioDevices.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/DesktopAudioBackend.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/EncodeSoundPacks.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/JavaSoundCapture.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/JavaSoundPlayback.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/NativeOpusCodec.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/NativeOpusDecoder.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/NativeOpusEncoder.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/Opus.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PcmRing.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWire.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWireCapture.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWireLibrary.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWirePlayback.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWireSession.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWireStream.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/SpaPod.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/DesktopInputHooks.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/EvdevInputHook.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/KeyNames.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/RawInput.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/Win32.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/WindowsInputHook.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/WindowsKeyNamer.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/X11KeyNamer.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/XInput2InputHook.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/XRecordInputHook.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/Xlib.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/notify/desktop/DBusConnection.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/notify/desktop/DBusWire.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/notify/desktop/DesktopNotifications.java delete mode 100644 ts3-client/desktop/src/main/java/com/ts3client/notify/desktop/FreedesktopNotifications.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/AudioDevices.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/DesktopAudioBackend.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/EncodeSoundPacks.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/JavaSoundCapture.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/JavaSoundPlayback.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/NativeOpusCodec.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/NativeOpusDecoder.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/NativeOpusEncoder.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/Opus.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PcmRing.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWire.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWireCapture.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWireLibrary.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWirePlayback.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWireSession.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWireStream.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/SpaPod.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/DesktopInputHooks.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/EvdevInputHook.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/KeyNames.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/RawInput.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/Win32.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/WindowsInputHook.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/WindowsKeyNamer.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/X11KeyNamer.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/XInput2InputHook.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/XRecordInputHook.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/Xlib.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/notify/desktop/DBusConnection.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/notify/desktop/DBusWire.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/notify/desktop/DesktopNotifications.java create mode 100644 ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/notify/desktop/FreedesktopNotifications.java delete mode 100644 ts3-client/desktop/src/test/java/com/ts3client/audio/desktop/pipewire/SpaPodTest.java delete mode 100644 ts3-client/desktop/src/test/java/com/ts3client/hotkey/desktop/RawInputTest.java delete mode 100644 ts3-client/desktop/src/test/java/com/ts3client/notify/desktop/DBusWireTest.java delete mode 100644 ts3-client/desktop/src/test/java/com/ts3client/recording/LibOpusMultistream.java delete mode 100644 ts3-client/desktop/src/test/java/com/ts3client/recording/VoiceRecorderTest.java delete mode 100644 ts3-client/desktop/src/test/java/com/ts3client/sound/OggOpusFileTest.java create mode 100644 ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/audio/desktop/pipewire/SpaPodTest.java create mode 100644 ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/hotkey/desktop/RawInputTest.java create mode 100644 ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/notify/desktop/DBusWireTest.java create mode 100644 ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/recording/LibOpusMultistream.java create mode 100644 ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/recording/VoiceRecorderTest.java create mode 100644 ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/sound/OggOpusFileTest.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/Main.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ApplicationPanel.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/AttachmentTransferHandler.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/AudioDevices.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/AvatarActions.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/AvatarHtml.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/AwayMessagesDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/BanAddDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/BanDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/BanDurationPicker.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/BanListDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/BookmarksDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/CapturePanel.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ChannelAdvancedPanel.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ChannelAudioPanel.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ChannelDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ChannelMenu.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ChannelPermissionsPanel.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ChannelStandardPanel.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ChatAttachmentActions.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ChatLogsPanel.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ChatPanel.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ChatSearch.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ClientMenu.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ClientVersionPanel.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ClientVolumeDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ComplaintsDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ConnectDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ConnectionInfoDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ContactDefaultsDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ContactsDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ContactsPanel.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/CountryFlagIcons.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/DescriptionEditorDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/DescriptionPictures.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/DesignPanel.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/DesktopEntry.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/DesktopNotifier.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/Dialogs.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/DisplayScale.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/DropDownToggleButton.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/DropIndicatorTree.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/FileBrowserDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/FindBar.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/FormPanel.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/GiantPttWindow.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/GroupIcons.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/HostButtonView.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/HotkeyActions.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/HotkeyArguments.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/HotkeyDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/HotkeyService.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/HotkeysPanel.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/HtmlStyles.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/IconChooserDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/IconFiles.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/IconTheme.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/Icons.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/IdentitiesDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/IdentityChooser.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/InfoPanel.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/InstanceChannel.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/LevelMeter.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/Links.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ListEditorDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/LookAndFeelManager.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/MainFrame.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/MainMenuBar.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/MainToolbar.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/MicrophoneTest.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/MyTeamSpeakPanel.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/NetworkPanel.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/NicknameCellEditor.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/NotificationsPanel.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/OfflineMessageComposeDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/OfflineMessagesDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/OptionsPage.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/OptionsSidebar.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/PictureViewer.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/PlaybackPanel.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/PrivilegeKeyCreateDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/PrivilegeKeysDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ReasonDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/RecordingActions.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/RowColorCombo.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ServerGroupsDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogExcludeDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogHighlightDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ServerMenu.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ServerTab.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ServerTabConnectionEvents.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ServerTabPane.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ServerTabTreeActions.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ServerTreeCellRenderer.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ServerTreeDragAndDrop.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ServerTreePanel.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ServerTreeSearch.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/SettingsDialog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/Spinners.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/StatusBar.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/TabDragReorder.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/TextZoom.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/Theme.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/TrayController.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/TrayNotifications.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/VoiceActivationSection.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/WindowClass.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/tray/AwtTray.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/tray/TrayBackend.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/tray/TrayLog.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/tray/X11.java delete mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/tray/X11Tray.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/Main.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ApplicationPanel.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AttachmentTransferHandler.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AudioDevices.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AvatarActions.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AvatarHtml.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AwayMessagesDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanAddDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanDurationPicker.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanListDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BookmarksDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/CapturePanel.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelAdvancedPanel.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelAudioPanel.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelMenu.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelPermissionsPanel.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelStandardPanel.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatAttachmentActions.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatLogsPanel.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatPanel.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatSearch.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ClientMenu.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ClientVersionPanel.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ClientVolumeDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ComplaintsDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ConnectDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ConnectionInfoDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ContactDefaultsDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ContactsDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ContactsPanel.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/CountryFlagIcons.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DescriptionEditorDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DescriptionPictures.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesignPanel.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesktopEntry.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesktopNotifier.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/Dialogs.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DisplayScale.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DropDownToggleButton.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DropIndicatorTree.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/FileBrowserDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/FindBar.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/FormPanel.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/GiantPttWindow.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/GroupIcons.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HostButtonView.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HotkeyActions.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HotkeyArguments.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HotkeyDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HotkeyService.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HotkeysPanel.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HtmlStyles.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IconChooserDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IconFiles.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IconTheme.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/Icons.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IdentitiesDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IdentityChooser.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/InfoPanel.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/InstanceChannel.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/LevelMeter.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/Links.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ListEditorDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/LookAndFeelManager.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainFrame.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainMenuBar.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainToolbar.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MicrophoneTest.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MyTeamSpeakPanel.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/NetworkPanel.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/NicknameCellEditor.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/NotificationsPanel.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessageComposeDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessagesDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OptionsPage.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OptionsSidebar.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PictureViewer.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PlaybackPanel.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeyCreateDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeysDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ReasonDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/RecordingActions.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/RowColorCombo.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerGroupsDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerLogDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerLogExcludeDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerLogHighlightDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerMenu.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabConnectionEvents.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabPane.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabTreeActions.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreeCellRenderer.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreeDragAndDrop.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreePanel.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreeSearch.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/SettingsDialog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/Spinners.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/StatusBar.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/TabDragReorder.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/TextZoom.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/Theme.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/TrayController.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/TrayNotifications.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/VoiceActivationSection.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/WindowClass.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/tray/AwtTray.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/tray/TrayBackend.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/tray/TrayLog.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/tray/X11.java create mode 100644 ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/tray/X11Tray.java rename ts3-client/swing/src/main/resources/{com/ts3client => eu/lixko/ts3j/client}/ui/app-icon-small.svg (100%) rename ts3-client/swing/src/main/resources/{com/ts3client => eu/lixko/ts3j/client}/ui/app-icon.svg (100%) rename ts3-client/swing/src/main/resources/{com/ts3client => eu/lixko/ts3j/client}/ui/laf/FlatDarkLaf.properties (100%) rename ts3-client/swing/src/main/resources/{com/ts3client => eu/lixko/ts3j/client}/ui/laf/FlatLaf.properties (100%) delete mode 100644 ts3-client/swing/src/test/java/com/ts3client/ui/DisplayScaleTest.java delete mode 100644 ts3-client/swing/src/test/java/com/ts3client/ui/MicrophoneTestTest.java create mode 100644 ts3-client/swing/src/test/java/eu/lixko/ts3j/client/ui/DisplayScaleTest.java create mode 100644 ts3-client/swing/src/test/java/eu/lixko/ts3j/client/ui/MicrophoneTestTest.java diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index a9baab9..b1508d2 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -37,7 +37,7 @@ abstract class BundleSoundPacks : DefaultTask() { } exec.javaexec { classpath = encoder - mainClass.set("com.ts3client.audio.desktop.EncodeSoundPacks") + mainClass.set("eu.lixko.ts3j.client.audio.desktop.EncodeSoundPacks") jvmArgs("--enable-native-access=ALL-UNNAMED") args(source.path, File(out, "sound").path) } @@ -77,12 +77,12 @@ val releaseKeystore = rootDir.resolve("keystore.properties").takeIf { it.isFile } android { - namespace = "com.ts3client.android" + namespace = "eu.lixko.ts3j.client.android" compileSdk = 37 ndkVersion = "30.0.16248370" defaultConfig { - applicationId = "com.ts3client.android" + applicationId = "eu.lixko.ts3j.client" minSdk = 33 targetSdk = 36 versionCode = 1 diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro index fb64767..4176170 100644 --- a/android/app/proguard-rules.pro +++ b/android/app/proguard-rules.pro @@ -2,7 +2,7 @@ -dontwarn javax.naming.** # Reached from native code by name. --keepclasseswithmembernames class com.ts3client.android.audio.** { +-keepclasseswithmembernames class eu.lixko.ts3j.client.android.audio.** { native ; } diff --git a/android/app/src/main/java/com/ts3client/android/AudioRoutePrefs.kt b/android/app/src/main/java/com/ts3client/android/AudioRoutePrefs.kt deleted file mode 100644 index 4027b86..0000000 --- a/android/app/src/main/java/com/ts3client/android/AudioRoutePrefs.kt +++ /dev/null @@ -1,30 +0,0 @@ -package com.ts3client.android - -import android.content.Context -import com.ts3client.android.audio.AudioRoute - -/** Where the Android-only audio choices are kept; the rest live in the shared settings. */ -class AudioRoutePrefs(context: Context) { - - private val prefs = context.getSharedPreferences("audio", Context.MODE_PRIVATE) - - fun load(): AudioRoute = AudioRoute( - enumOr(prefs.getString(INPUT_PRESET, null), AudioRoute.DEFAULT.inputPreset()), - enumOr(prefs.getString(USAGE, null), AudioRoute.DEFAULT.usage()), - ) - - fun save(route: AudioRoute) { - prefs.edit() - .putString(INPUT_PRESET, route.inputPreset().name) - .putString(USAGE, route.usage().name) - .apply() - } - - private inline fun > enumOr(name: String?, default: E): E = - enumValues().firstOrNull { it.name == name } ?: default - - private companion object { - const val INPUT_PRESET = "inputPreset" - const val USAGE = "usage" - } -} diff --git a/android/app/src/main/java/com/ts3client/android/BookmarkShortcuts.kt b/android/app/src/main/java/com/ts3client/android/BookmarkShortcuts.kt deleted file mode 100644 index 19144c5..0000000 --- a/android/app/src/main/java/com/ts3client/android/BookmarkShortcuts.kt +++ /dev/null @@ -1,80 +0,0 @@ -package com.ts3client.android - -import android.content.Context -import android.content.Intent -import android.content.pm.ShortcutInfo -import android.content.pm.ShortcutManager -import android.graphics.Bitmap -import android.graphics.BitmapFactory -import android.graphics.Canvas -import android.graphics.Rect -import android.graphics.drawable.Icon -import com.ts3client.config.Bookmark -import com.ts3client.net.IconRepository - -/** - * Home-screen shortcuts that connect to a bookmark in one tap. A shortcut names its bookmark by - * [Bookmark.id], so editing the bookmark carries over and removing it disables the shortcut. - */ -internal class BookmarkShortcuts(private val context: Context, private val icons: IconTheme) { - - private val manager = context.getSystemService(ShortcutManager::class.java) - - val supported: Boolean get() = manager?.isRequestPinShortcutSupported == true - - /** Asks the launcher to pin a shortcut; it confirms with the user itself. */ - fun pin(bookmark: Bookmark) { - manager?.requestPinShortcut(info(bookmark), null) - } - - /** Pinned shortcuts take on their bookmarks' current names and icons; those of removed ones stop working. */ - fun sync(bookmarks: List) { - val manager = manager ?: return - val byId = bookmarks.associateBy { shortcutId(it.id) } - val pinned = manager.pinnedShortcuts - val gone = pinned.map { it.id }.filter { it !in byId } - if (gone.isNotEmpty()) manager.disableShortcuts(gone, "Bookmark removed") - val kept = pinned.mapNotNull { byId[it.id] } - if (kept.isNotEmpty()) { - manager.enableShortcuts(kept.map { shortcutId(it.id) }) - manager.updateShortcuts(kept.map(::info)) - } - } - - private fun info(bookmark: Bookmark): ShortcutInfo = - ShortcutInfo.Builder(context, shortcutId(bookmark.id)) - .setShortLabel(bookmark.displayName()) - .setLongLabel(listOfNotNull(bookmark.displayName(), bookmark.channel.ifBlank { null }).joinToString(" · ")) - .setIcon(icon(bookmark.iconId)) - .setIntent(Intent(context, MainActivity::class.java) - .setAction(ACTION_CONNECT) - .putExtra(EXTRA_BOOKMARK, bookmark.id)) - .build() - - /** The server's own icon as last seen there, else the pack's server icon, inside the adaptive icon's safe zone. */ - private fun icon(iconId: Long): Icon { - val art = IconRepository.cached(iconId)?.let { BitmapFactory.decodeByteArray(it, 0, it.size) } - ?: icons.render(listOf("SERVER_GREEN", "BOOKMARK_MANAGER"), ART_PX, 0x202020) - val canvas = Bitmap.createBitmap(ADAPTIVE_PX, ADAPTIVE_PX, Bitmap.Config.ARGB_8888) - Canvas(canvas).apply { - drawColor(BACKGROUND) - if (art != null) { - val inset = (ADAPTIVE_PX - ART_PX) / 2 - drawBitmap(art, null, Rect(inset, inset, inset + ART_PX, inset + ART_PX), null) - } - } - return Icon.createWithAdaptiveBitmap(canvas) - } - - companion object { - const val ACTION_CONNECT = "com.ts3client.android.CONNECT_BOOKMARK" - const val EXTRA_BOOKMARK = "bookmark" - - /** 108 dp at xxxhdpi; the inner 72 dp always shows, the art sits well within. */ - private const val ADAPTIVE_PX = 432 - private const val ART_PX = 192 - private const val BACKGROUND = 0xFFE8EEF4.toInt() - - private fun shortcutId(bookmarkId: String) = "bookmark:$bookmarkId" - } -} diff --git a/android/app/src/main/java/com/ts3client/android/Chats.kt b/android/app/src/main/java/com/ts3client/android/Chats.kt deleted file mode 100644 index 9857005..0000000 --- a/android/app/src/main/java/com/ts3client/android/Chats.kt +++ /dev/null @@ -1,88 +0,0 @@ -package com.ts3client.android - -import androidx.compose.runtime.Immutable -import com.ts3client.text.HtmlText -import com.ts3client.text.TextQuery - -/** Which conversation a chat line belongs to. */ -sealed interface ChatKey { - data object Server : ChatKey - data object Channel : ChatKey - data class Private(val clientId: Int) : ChatKey -} - -/** One entry of a chat, as HTML in the form [com.ts3client.text.ChatHtml] writes. */ -@Immutable -data class ChatLine(val id: Long, val html: String) { - /** The text to find in. */ - val plain: String by lazy { HtmlText.plain(html) } -} - -@Immutable -data class Conversation( - val key: ChatKey, - val title: String, - /** The peer's unique id in a private chat, once known. */ - val uniqueId: String = "", - val lines: List = emptyList(), - val unread: Boolean = false, -) - -/** Every conversation of the session: the server's, the channel's, then the private ones. */ -@Immutable -data class Chats( - val server: Conversation = Conversation(ChatKey.Server, "Server"), - val channel: Conversation = Conversation(ChatKey.Channel, "Channel"), - val private: List = emptyList(), -) { - val all: List get() = listOf(server, channel) + private - - val anyUnread: Boolean get() = all.any { it.unread } - - operator fun get(key: ChatKey): Conversation? = when (key) { - ChatKey.Server -> server - ChatKey.Channel -> channel - is ChatKey.Private -> private.firstOrNull { it.key == key } - } - - /** Applies [change] to a conversation, opening a private one titled [title] if needed. */ - fun update(key: ChatKey, title: String = "", change: (Conversation) -> Conversation): Chats = when (key) { - ChatKey.Server -> copy(server = change(server)) - ChatKey.Channel -> copy(channel = change(channel)) - is ChatKey.Private -> { - val existing = private.indexOfFirst { it.key == key } - if (existing < 0) { - copy(private = private + change(Conversation(key, title))) - } else { - copy(private = private.toMutableList().also { it[existing] = change(it[existing]) }) - } - } - } - - fun close(key: ChatKey.Private): Chats = copy(private = private.filter { it.key != key }) - - companion object { - /** As many lines as a log history loads; older ones leave the conversation. */ - const val MAX_LINES = 1000 - } -} - -fun Conversation.append(line: ChatLine, read: Boolean): Conversation = - copy(lines = (lines + line).takeLast(Chats.MAX_LINES), unread = unread || !read) - -/** The [nth] match of the find bar's query in the line [line]. */ -data class ChatMatch(val line: Long, val nth: Int) - -/** Every match of [query] in [lines], oldest first; past [limit], only the newest. */ -fun findIn(lines: List, query: TextQuery, limit: Int): List { - if (query.isEmpty) return emptyList() - val out = ArrayList() - for (line in lines) { - val m = query.matcher(line.plain) ?: return emptyList() - var n = 0 - while (m.find()) { - if (m.end() > m.start()) out += ChatMatch(line.id, n++) - } - } - return if (out.size > limit) out.subList(out.size - limit, out.size) else out -} diff --git a/android/app/src/main/java/com/ts3client/android/ConnectionService.kt b/android/app/src/main/java/com/ts3client/android/ConnectionService.kt deleted file mode 100644 index 4c7ff4b..0000000 --- a/android/app/src/main/java/com/ts3client/android/ConnectionService.kt +++ /dev/null @@ -1,238 +0,0 @@ -package com.ts3client.android - -import android.Manifest -import android.app.Notification -import android.app.NotificationChannel -import android.app.NotificationManager -import android.app.PendingIntent -import android.content.Intent -import android.content.pm.PackageManager -import android.content.pm.ServiceInfo -import android.graphics.Color -import android.graphics.drawable.Icon -import android.net.wifi.WifiManager -import android.os.PowerManager -import androidx.lifecycle.LifecycleService -import androidx.lifecycle.lifecycleScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.delay -import com.ts3client.config.Settings -import com.ts3client.net.ClientStatus -import com.ts3client.session.SelfState -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.conflate -import kotlinx.coroutines.flow.drop -import kotlinx.coroutines.flow.collectLatest -import kotlinx.coroutines.flow.combine -import kotlinx.coroutines.flow.distinctUntilChanged -import kotlinx.coroutines.flow.flatMapLatest -import kotlinx.coroutines.flow.flowOf -import kotlinx.coroutines.launch -import kotlin.math.roundToInt - -/** - * Keeps the process in the foreground while connected, so the connection and its audio - * survive the app leaving the screen, and offers the essentials in its notification. - */ -@OptIn(ExperimentalCoroutinesApi::class) -class ConnectionService : LifecycleService() { - - private lateinit var sessions: SessionController - private lateinit var wifiLock: WifiManager.WifiLock - private lateinit var wifiBackgroundLock: WifiManager.WifiLock - private lateinit var wakeLock: PowerManager.WakeLock - private lateinit var overlay: PttOverlay - private var foregroundTypes = 0 - private var shown: ServerController? = null - - override fun onCreate() { - super.onCreate() - sessions = (application as Ts3Application).sessions - getSystemService(NotificationManager::class.java).createNotificationChannel( - NotificationChannel(CHANNEL, getString(R.string.connection_channel), NotificationManager.IMPORTANCE_LOW) - ) - // Voice goes out every 20 ms; Wi-Fi power saving and a sleeping CPU would stretch that. - // Low-latency mode only holds while we are in the foreground with the screen on, so the - // high-performance lock keeps power saving off the rest of the time. - val wifi = getSystemService(WifiManager::class.java) - wifiLock = wifi.createWifiLock(WifiManager.WIFI_MODE_FULL_LOW_LATENCY, "ts3j:voice") - .apply { setReferenceCounted(false); acquire() } - @Suppress("DEPRECATION") - wifiBackgroundLock = wifi.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "ts3j:voice-background") - .apply { setReferenceCounted(false); acquire() } - wakeLock = getSystemService(PowerManager::class.java) - .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ts3j:connection") - .apply { setReferenceCounted(false); acquire() } - - show(sessions.current.value?.state?.value ?: SessionState(), capturing = false) - lifecycleScope.launch { - // The server count shows in the notification too. - combine(shownServer(), sessions.micOwner, sessions.servers) { shown, owner, _ -> shown to (owner != null) } - .conflate() - .collect { (shown, capturing) -> - if (shown != null) { - this@ConnectionService.shown = shown.first - show(shown.second, capturing) - // Talking flips the icon often, and Android drops updates that come too fast. - delay(MIN_UPDATE_MS) - } - } - } - lifecycleScope.launch { - sessions.current.flatMapLatest { it?.state ?: flowOf(null) }.collectLatest { state -> - if (state == null) { - // A reconnect leaves the server briefly; only stop once it stays gone. - delay(STOP_DELAY_MS) - stopSelf() - } - } - } - lifecycleScope.launch { - sessions.icons.active.drop(1).collect { shown?.let { show(it.state.value, sessions.micOwner.value != null) } } - } - - overlay = PttOverlay(this, sessions.icons, sessions::setPushToTalk) - lifecycleScope.launch { - val owner = sessions.micOwner.flatMapLatest { server -> - server?.let { combine(it.state, it.tree) { state, tree -> state to tree } } ?: flowOf(null) - } - combine(owner, sessions.onScreen, sessions.pttOverlay) { held, onScreen, enabled -> - val (state, tree) = held ?: return@combine null - val wanted = enabled && !onScreen && state.connected && state.micActive && - state.inputMode == Settings.InputMode.PUSH_TO_TALK - val status = tree.client(state.selfClientId)?.status - when { - !wanted -> null - state.micMuted -> PttOverlay.Look.MUTED - status == ClientStatus.TALKING || status == ClientStatus.COMMANDER_TALKING -> PttOverlay.Look.TALKING - else -> PttOverlay.Look.IDLE - } - }.distinctUntilChanged().collect { look -> - if (look == null) overlay.hide() else overlay.show(look) - } - } - } - - /** - * The server the notification speaks for, as the desktop tray icon does: the one - * holding the microphone, or the visible one when nobody is capturing. - */ - private fun shownServer(): Flow?> = - combine(sessions.current, sessions.micOwner) { current, owner -> current to owner } - .flatMapLatest { (current, owner) -> - combine(current?.state ?: flowOf(null), owner?.state ?: flowOf(null)) { currentState, ownerState -> - when { - owner != null && ownerState?.connected == true -> owner to ownerState - current != null && currentState != null -> current to currentState - else -> null - } - } - } - - override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { - super.onStartCommand(intent, flags, startId) - val server = shown ?: sessions.current.value ?: return START_NOT_STICKY - val state = server.state.value - when (intent?.action) { - ACTION_TOGGLE_MUTE -> server.setMicMuted(!state.micMuted) - ACTION_TOGGLE_DEAFEN -> server.setDeafened(!state.deafened) - ACTION_DISCONNECT -> server.disconnect() - } - return START_NOT_STICKY - } - - /** - * The user swiped the app away: they are done with it, connection included. Leaving - * properly spares the server a ghost that would hold our identity until it times out. - */ - override fun onTaskRemoved(rootIntent: Intent?) { - super.onTaskRemoved(rootIntent) - lifecycleScope.launch(Dispatchers.IO) { - sessions.leave() - stopSelf() - } - } - - override fun onDestroy() { - overlay.hide() - wifiLock.release() - wifiBackgroundLock.release() - wakeLock.release() - super.onDestroy() - } - - /** Posts the notification, re-declaring what the service uses when that changed. */ - private fun show(state: SessionState, capturing: Boolean) { - val types = ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK or - if (capturing && hasMicPermission()) ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE else 0 - val notification = notification(state) - if (types != foregroundTypes) { - startForeground(NOTIFICATION_ID, notification, types) - foregroundTypes = types - } else { - getSystemService(NotificationManager::class.java).notify(NOTIFICATION_ID, notification) - } - } - - private fun hasMicPermission() = - checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED - - private fun notification(state: SessionState): Notification { - val open = PendingIntent.getActivity( - this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE - ) - val others = sessions.servers.value.size - 1 - return Notification.Builder(this, CHANNEL) - .setSmallIcon(statusIcon(state.self)) - .setLargeIcon(largeIcon(state.self)) - .setContentTitle(if (others > 0) "${state.title} +$others" else state.title) - .setContentText(state.status) - .setContentIntent(open) - .setOngoing(true) - .addAction(action(ACTION_TOGGLE_MUTE, if (state.micMuted) "Unmute" else "Mute")) - .addAction(action(ACTION_TOGGLE_DEAFEN, if (state.deafened) "Undeafen" else "Deafen")) - .addAction(action(ACTION_DISCONNECT, "Disconnect")) - .build() - } - - /** - * The status bar shows only the shape of an icon, which pack art loses, so it is - * drawn from the Material pack whatever pack is chosen. - */ - private fun statusIcon(self: SelfState): Icon { - val key = self.iconKey() ?: return Icon.createWithResource(this, android.R.drawable.ic_btn_speak_now) - val size = (STATUS_ICON_DP * resources.displayMetrics.density).roundToInt() - val bitmap = sessions.icons.renderMaterial(key, size, Color.WHITE) - ?: return Icon.createWithResource(this, android.R.drawable.ic_btn_speak_now) - return Icon.createWithBitmap(bitmap) - } - - /** The expanded notification has room for the chosen pack's own art, as the tree draws it. */ - private fun largeIcon(self: SelfState): Icon? { - val key = self.iconKey() ?: return null - val size = (LARGE_ICON_DP * resources.displayMetrics.density).roundToInt() - return sessions.icons.render(listOf(key), size, getColor(android.R.color.system_neutral1_500)) - ?.let(Icon::createWithBitmap) - } - - private fun action(action: String, label: String): Notification.Action { - val intent = PendingIntent.getService( - this, action.hashCode(), Intent(this, ConnectionService::class.java).setAction(action), - PendingIntent.FLAG_IMMUTABLE - ) - return Notification.Action.Builder(null, label, intent).build() - } - - private companion object { - const val CHANNEL = "connection" - const val NOTIFICATION_ID = 1 - const val STOP_DELAY_MS = 3_000L - const val MIN_UPDATE_MS = 250L - const val STATUS_ICON_DP = 24 - const val LARGE_ICON_DP = 48 - const val ACTION_TOGGLE_MUTE = "com.ts3client.android.TOGGLE_MUTE" - const val ACTION_TOGGLE_DEAFEN = "com.ts3client.android.TOGGLE_DEAFEN" - const val ACTION_DISCONNECT = "com.ts3client.android.DISCONNECT" - } -} diff --git a/android/app/src/main/java/com/ts3client/android/FileTransfers.kt b/android/app/src/main/java/com/ts3client/android/FileTransfers.kt deleted file mode 100644 index f3c0791..0000000 --- a/android/app/src/main/java/com/ts3client/android/FileTransfers.kt +++ /dev/null @@ -1,132 +0,0 @@ -package com.ts3client.android - -import android.content.Context -import android.net.Uri -import android.provider.OpenableColumns -import com.ts3client.net.TeamspeakConnection -import com.ts3client.net.filetransfer.FileTransfer -import com.ts3client.net.filetransfer.RemoteFile -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.update -import kotlinx.coroutines.withContext -import java.io.File -import java.io.IOException -import java.util.concurrent.atomic.AtomicLong - -/** One upload or download as the file browser shows it. */ -data class TransferRow( - val id: Long, - val name: String, - val upload: Boolean, - val channelId: Int, - /** The directory an upload goes into, to list again once it is there. */ - val directory: String, - val transferred: Long, - val total: Long, - val state: FileTransfer.State, - val error: String?, -) { - val done: Boolean get() = state != FileTransfer.State.PENDING && state != FileTransfer.State.ACTIVE - val progress: Float get() = if (total > 0) (transferred.toFloat() / total).coerceIn(0f, 1f) else 0f -} - -/** - * The channel file transfers of one server. Transfers go through files of our own in the cache, - * as the core reads and writes plain files: a download is copied where the user picked once - * complete, an upload is copied out of the picked document first. They outlive the browser page. - */ -class FileTransfers internal constructor(private val context: Context, private val conn: () -> TeamspeakConnection) { - - private val ids = AtomicLong() - private val handles = HashMap() - - private val _rows = MutableStateFlow(emptyList()) - val rows: StateFlow> = _rows - - /** Downloads [file] into the document at [target]. */ - fun download(channelId: Int, password: String, file: RemoteFile, target: Uri) { - val temp = File.createTempFile("download", null, context.cacheDir) - val row = add(file.name, upload = false, channelId, file.parentPath, file.size) - start(row, temp, onComplete = { - context.contentResolver.openOutputStream(target)?.use { out -> temp.inputStream().use { it.copyTo(out) } } - ?: throw IOException("Could not write the file") - }) { listener -> conn().downloadFile(channelId, password, file.fullPath, temp, listener) } - } - - /** Uploads the document at [source] into [directory] (ending in "/"), replacing a file of the same name. */ - suspend fun upload(channelId: Int, password: String, directory: String, source: Uri) { - val (name, temp) = withContext(Dispatchers.IO) { copyIn(source) } - val row = add(name, upload = true, channelId, directory, temp.length()) - start(row, temp, onComplete = {}) { listener -> - conn().uploadFile(channelId, password, directory + name, temp, true, listener) - } - } - - fun cancel(id: Long) { - synchronized(handles) { handles[id] }?.cancel() - } - - fun clearFinished() = _rows.update { rows -> rows.filterNot { it.done } } - - private fun add(name: String, upload: Boolean, channelId: Int, directory: String, total: Long): TransferRow { - val row = TransferRow(ids.incrementAndGet(), name, upload, channelId, directory, 0, total, - FileTransfer.State.PENDING, null) - _rows.update { it + row } - return row - } - - /** Runs a transfer through [temp], which goes once it is done with; [onComplete] finishes a successful one. */ - private fun start(row: TransferRow, temp: File, onComplete: () -> Unit, - begin: (FileTransfer.Listener) -> FileTransfer) { - var lastUpdate = 0L - val listener = FileTransfer.Listener { t -> - val now = System.nanoTime() - // Progress comes per buffer; the list need not redraw that often. - if (!t.isDone && now - lastUpdate < UPDATE_NANOS) return@Listener - lastUpdate = now - var error = t.errorMessage - if (t.state == FileTransfer.State.COMPLETED) { - error = runCatching(onComplete).exceptionOrNull()?.let { it.message ?: "Could not save the file" } - } - if (t.isDone) { - temp.delete() - synchronized(handles) { handles.remove(row.id) } - } - val state = if (error != null) FileTransfer.State.FAILED else t.state - update(row.id) { it.copy(transferred = t.transferredBytes, total = maxOf(t.totalBytes, 0), state = state, error = error) } - } - try { - val handle = begin(listener) - synchronized(handles) { if (!handle.isDone) handles[row.id] = handle } - } catch (e: RuntimeException) { - temp.delete() - update(row.id) { it.copy(state = FileTransfer.State.FAILED, error = e.message ?: "Not connected") } - } - } - - private fun update(id: Long, change: (TransferRow) -> TransferRow) = - _rows.update { rows -> rows.map { if (it.id == id) change(it) else it } } - - private fun copyIn(uri: Uri): Pair { - val resolver = context.contentResolver - val name = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c -> - if (c.moveToFirst()) c.getString(0) else null - }?.takeIf { it.isNotBlank() } ?: uri.lastPathSegment ?: "file" - val temp = File.createTempFile("upload", null, context.cacheDir) - try { - resolver.openInputStream(uri)?.use { input -> temp.outputStream().use { input.copyTo(it) } } - ?: throw IOException("Could not read the file") - } catch (e: IOException) { - temp.delete() - throw e - } - // A server path takes no slashes in a file name. - return name.replace('/', '_') to temp - } - - private companion object { - const val UPDATE_NANOS = 200_000_000L - } -} diff --git a/android/app/src/main/java/com/ts3client/android/IconTheme.kt b/android/app/src/main/java/com/ts3client/android/IconTheme.kt deleted file mode 100644 index 8fbd59b..0000000 --- a/android/app/src/main/java/com/ts3client/android/IconTheme.kt +++ /dev/null @@ -1,143 +0,0 @@ -package com.ts3client.android - -import android.content.Context -import android.graphics.Bitmap -import android.graphics.BitmapFactory -import android.graphics.Canvas -import android.graphics.Paint -import android.graphics.RectF -import android.net.Uri -import android.provider.OpenableColumns -import android.util.LruCache -import com.caverock.androidsvg.RenderOptions -import com.caverock.androidsvg.SVG -import com.ts3client.config.AppDirs -import com.ts3client.config.Settings -import com.ts3client.gfx.IconPack -import com.ts3client.gfx.IconPacks -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import java.io.File - -/** - * The icon packs the app draws with: the Material pack it ships, and TeamSpeak packs - * imported into its `gfx` folder, which are the very zips a TeamSpeak 3 install keeps in - * its own. Whatever the chosen pack lacks comes from the Material one. - */ -class IconTheme(private val context: Context, private val settings: Settings) { - - private val folder = File(AppDirs.profile(), "gfx") - private val material: IconPack = IconPacks.material() - @Volatile - private var lookupOrder = listOf(material) - private val cache = LruCache(256) - - private val _packs = MutableStateFlow(emptyList()) - val packs: StateFlow> = _packs - - private val _active = MutableStateFlow(material) - val active: StateFlow = _active - - init { - reload() - } - - fun select(pack: IconPack) { - settings.iconPack = pack.id() - settings.save() - reload() - } - - /** - * Copies a pack's zip into the app and switches to it. - * - * @return the pack, or `null` when the file is no icon pack - */ - fun import(uri: Uri): IconPack? { - folder.mkdirs() - val target = File(folder, displayName(uri).substringAfterLast('/').let { - if (it.endsWith(".zip", ignoreCase = true)) it else "$it.zip" - }) - val staged = File(folder, target.name + ".part") - context.contentResolver.openInputStream(uri)?.use { input -> - staged.outputStream().use { input.copyTo(it) } - } ?: return null - target.delete() - staged.renameTo(target) - val pack = IconPack.load(target) - if (pack == null) { - target.delete() - return null - } - select(pack) - return _active.value - } - - /** - * Draws the first of [keys] the packs have. - * - * @param rgb the colour for art that paints in the text colour - */ - fun render(keys: List, size: Int, rgb: Int): Bitmap? = render(lookupOrder, keys, size, rgb) - - /** Draws from the Material pack whatever pack is chosen, for chrome that must stay legible on its own colours. */ - fun renderMaterial(key: String, size: Int, rgb: Int): Bitmap? = render(listOf(material), listOf(key), size, rgb) - - private fun render(order: List, keys: List, size: Int, rgb: Int): Bitmap? { - val cacheKey = "${order.first().id()}/${keys.joinToString(",")}@$size#$rgb" - cache.get(cacheKey)?.let { return it } - for (key in keys) { - for (pack in order) { - val data = pack.icon(key, size) ?: continue - val bitmap = (if (pack.isVector(key, size)) rasterize(IconPack.withCurrentColor(data, rgb), size) - else decode(data, size)) ?: continue - cache.put(cacheKey, bitmap) - return bitmap - } - } - return null - } - - private fun reload() { - val packs = IconPacks.findAll(folder, null) - val active = IconPacks.select(packs, settings.iconPack) ?: material - lookupOrder = IconPacks.lookupOrder(active, packs, material) - cache.evictAll() - _packs.value = packs - _active.value = active - } - - private fun displayName(uri: Uri): String = - context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { - if (it.moveToFirst()) it.getString(0) else null - } ?: uri.lastPathSegment ?: "iconpack.zip" - - private fun rasterize(svg: ByteArray, size: Int): Bitmap? = try { - val document = SVG.getFromString(String(svg, Charsets.UTF_8)) - if (document.documentViewBox == null && document.documentWidth > 0 && document.documentHeight > 0) { - document.setDocumentViewBox(0f, 0f, document.documentWidth, document.documentHeight) - } - // Otherwise the art keeps the size it was authored at inside the viewport. - document.setDocumentWidth("100%") - document.setDocumentHeight("100%") - Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).also { - document.renderToCanvas(Canvas(it), RenderOptions().viewPort(0f, 0f, size.toFloat(), size.toFloat())) - } - } catch (e: Exception) { - null - } - - /** Scales a bitmap icon into the square, keeping the aspect ratio of art that is not. */ - private fun decode(data: ByteArray, size: Int): Bitmap? { - val source = BitmapFactory.decodeByteArray(data, 0, data.size) ?: return null - if (source.width == size && source.height == size) return source - val factor = minOf(size.toFloat() / source.width, size.toFloat() / source.height) - val w = source.width * factor - val h = source.height * factor - return Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).also { - val left = (size - w) / 2 - val top = (size - h) / 2 - Canvas(it).drawBitmap(source, null, RectF(left, top, left + w, top + h), Paint(Paint.FILTER_BITMAP_FLAG)) - } - } -} diff --git a/android/app/src/main/java/com/ts3client/android/IdentityManager.kt b/android/app/src/main/java/com/ts3client/android/IdentityManager.kt deleted file mode 100644 index 90e8ffe..0000000 --- a/android/app/src/main/java/com/ts3client/android/IdentityManager.kt +++ /dev/null @@ -1,170 +0,0 @@ -package com.ts3client.android - -import android.content.Context -import android.net.Uri -import com.ts3client.config.Bookmarks -import com.ts3client.config.IdentityEntry -import com.ts3client.config.IdentityStore -import com.ts3client.config.Settings -import com.ts3client.teamspeak.TeamSpeakImporter -import com.ts3client.teamspeak.TeamSpeakSettingsDb -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.cancelAndJoin -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.isActive -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext -import java.io.IOException - -/** What the identity manager shows of one identity. */ -data class IdentityInfo( - val id: String, - val name: String, - val uniqueId: String, - val securityLevel: Int, - val isDefault: Boolean, - val nickname: String, - val phoneticNickname: String, -) - -/** A search for a better key offset under way. */ -data class Improvement(val id: String, val target: Int, val reached: Int) - -/** - * The identities, as TeamSpeak's Tools → Identities manages them: create, import, export, - * rename, remove, pick the default and raise the security level. Raising the level runs - * on until it is reached or stopped, whichever page is on screen. - */ -class IdentityManager( - private val context: Context, - private val store: IdentityStore, - private val settings: Settings, - private val bookmarks: Bookmarks, - private val onBookmarksChanged: () -> Unit, -) { - private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) - - private val _all = MutableStateFlow(snapshot()) - val all: StateFlow> = _all - - private val _improving = MutableStateFlow(null) - val improving: StateFlow = _improving - private var improvement: Job? = null - - /** Picks up identities added elsewhere, such as by an import or a first connect. */ - fun refresh() { - _all.value = snapshot() - } - - private fun snapshot(): List = store.all().map { - IdentityInfo(it.id, it.name, it.uniqueId, it.securityLevel, it.id == settings.defaultIdentityId, - it.nickname, it.phoneticNickname) - } - - /** Generates an identity at TeamSpeak's default security level; the first one becomes the default. */ - suspend fun generate(name: String): IdentityInfo = added { - store.generate(name, IdentityStore.DEFAULT_SECURITY_LEVEL) - } - - /** Imports a TeamSpeak identity file, under the name it carries. */ - suspend fun importFile(uri: Uri): IdentityInfo = added { - context.contentResolver.openInputStream(uri)?.use { store.importStream(it, null) } - ?: throw IOException("Cannot open the file") - } - - /** Imports the identities of a TeamSpeak 3 `settings.db`. */ - suspend fun importFromTeamSpeak(uri: Uri): TeamSpeakImporter.Result = withContext(Dispatchers.IO) { - withLocalCopy(context, uri) { TeamSpeakImporter(store, bookmarks, settings).importIdentities(it) } - }.also { - adoptDefault(null) - refresh() - } - - private suspend fun added(create: () -> IdentityEntry): IdentityInfo { - val entry = withContext(Dispatchers.IO) { create() } - adoptDefault(entry) - refresh() - return _all.value.first { it.id == entry.id } - } - - /** Makes [entry], or else the first identity, the default while there is none. */ - private fun adoptDefault(entry: IdentityEntry?) { - if (store.byId(settings.defaultIdentityId) != null) return - val fallback = entry ?: store.all().firstOrNull() ?: return - settings.defaultIdentityId = fallback.id - settings.save() - } - - /** Writes the identity out in TeamSpeak's format, for the official client or another device. */ - suspend fun export(id: String, uri: Uri) = withContext(Dispatchers.IO) { - val entry = store.byId(id) ?: return@withContext - val out = context.contentResolver.openOutputStream(uri, "wt") ?: throw IOException("Cannot write the file") - store.exportTo(entry, out) - } - - fun rename(id: String, name: String) { - val entry = store.byId(id) ?: return - scope.launch(Dispatchers.IO) { - store.rename(entry, name) - refresh() - } - } - - fun setNicknames(id: String, nickname: String, phoneticNickname: String) { - val entry = store.byId(id) ?: return - scope.launch(Dispatchers.IO) { - store.setNicknames(entry, nickname, phoneticNickname) - refresh() - } - } - - /** The nickname of the identity a connect with [id] uses; empty when it has none. */ - fun nicknameOf(id: String): String = - (store.byId(id) ?: store.byId(settings.defaultIdentityId))?.nickname.orEmpty() - - fun setDefault(id: String) { - settings.defaultIdentityId = id - settings.save() - refresh() - } - - /** Deletes the identity; bookmarks that connected with it fall back to the default. */ - fun remove(id: String) { - val entry = store.byId(id) ?: return - scope.launch(Dispatchers.IO) { - // Else the search would write the file back once it ends. - if (_improving.value?.id == id) improvement?.cancelAndJoin() - store.remove(entry, settings, bookmarks) - onBookmarksChanged() - refresh() - } - } - - /** Searches for a key offset reaching [target], keeping the best found when stopped. */ - fun improve(id: String, target: Int) { - if (improvement?.isActive == true) return - val entry = store.byId(id) ?: return - _improving.value = Improvement(id, target, entry.securityLevel) - improvement = scope.launch { - try { - store.improveSecurity(entry, target) { reached, _ -> - _improving.value = Improvement(id, target, reached) - isActive - } - } catch (e: IOException) { - // The level reached stays in memory for this run. - } finally { - _improving.value = null - refresh() - } - } - } - - fun stopImproving() { - improvement?.cancel() - } -} diff --git a/android/app/src/main/java/com/ts3client/android/LevelMonitor.kt b/android/app/src/main/java/com/ts3client/android/LevelMonitor.kt deleted file mode 100644 index 41a5153..0000000 --- a/android/app/src/main/java/com/ts3client/android/LevelMonitor.kt +++ /dev/null @@ -1,95 +0,0 @@ -package com.ts3client.android - -import com.ts3client.audio.AudioBackend -import com.ts3client.audio.InputLevel -import com.ts3client.audio.VoiceInput -import com.ts3client.config.Settings -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow - -/** The microphone's level on [InputLevel]'s scale, and whether that would be sent. */ -data class MicLevel( - val db: Double = InputLevel.SILENCE_DB, - val transmitting: Boolean = false, - /** Whether a microphone is being listened to at all. */ - val live: Boolean = false, -) - -/** - * The level meter behind the voice-activation settings. While connected it listens to the - * connection's own microphone, so it shows exactly what gets sent; otherwise it runs a test - * microphone of its own for as long as someone watches. - */ -class LevelMonitor(private val settings: Settings, private val audio: AudioBackend) { - - private val _level = MutableStateFlow(MicLevel()) - val level: StateFlow = _level - - /** The connection's microphone, when that is the one listened to. */ - private var borrowed: VoiceInput? = null - private var test: VoiceInput? = null - - /** - * Starts or stops listening. - * - * @param source the connection's microphone while it captures, else null - * @param busy whether a connection is under way, which will bring its own microphone - */ - @Synchronized - fun update(watching: Boolean, source: VoiceInput?, busy: Boolean, mayCapture: Boolean) { - when { - !watching -> release() - source != null -> if (borrowed !== source) { - release() - source.setLevelListener(::onLevel) - borrowed = source - } - busy || !mayCapture -> release() - test == null -> startTest() - } - } - - /** The own microphone's transmit state, which the connection reports. */ - fun talking(transmitting: Boolean) { - if (borrowed != null) _level.value = _level.value.copy(transmitting = transmitting) - } - - /** Puts changed voice settings into effect on the test microphone. */ - @Synchronized - fun apply() { - test?.let { - it.apply(settings) - it.setMode(testMode()) - } - } - - private fun startTest() { - release() - val input = audio.createInput(settings) - input.setMode(testMode()) - input.setLevelListener(::onLevel) - input.setTalkListener { _level.value = _level.value.copy(transmitting = it) } - try { - input.start() - } catch (e: RuntimeException) { - return // no microphone to be had; the meter stays idle - } - test = input - } - - private fun release() { - borrowed?.setLevelListener(null) - borrowed = null - test?.stop() - test = null - _level.value = MicLevel() - } - - private fun onLevel(db: Double) { - _level.value = _level.value.copy(db = db, live = true) - } - - /** Push-to-talk would never open without the button, and the test is there to tune the gate. */ - private fun testMode() = - if (settings.inputMode == Settings.InputMode.PUSH_TO_TALK) Settings.InputMode.VOICE_ACTIVATION else settings.inputMode -} diff --git a/android/app/src/main/java/com/ts3client/android/LocalCopy.kt b/android/app/src/main/java/com/ts3client/android/LocalCopy.kt deleted file mode 100644 index ae6fd21..0000000 --- a/android/app/src/main/java/com/ts3client/android/LocalCopy.kt +++ /dev/null @@ -1,21 +0,0 @@ -package com.ts3client.android - -import android.content.Context -import android.net.Uri -import java.io.File -import java.io.IOException - -/** - * Hands [read] a temporary copy of the document at [uri], for readers that need a file they - * can seek in, which a content URI is not. - */ -internal fun withLocalCopy(context: Context, uri: Uri, read: (File) -> T): T { - val copy = File.createTempFile("import", null, context.cacheDir) - try { - val input = context.contentResolver.openInputStream(uri) ?: throw IOException("Cannot open the file") - input.use { copy.outputStream().use { out -> it.copyTo(out) } } - return read(copy) - } finally { - copy.delete() - } -} diff --git a/android/app/src/main/java/com/ts3client/android/MainActivity.kt b/android/app/src/main/java/com/ts3client/android/MainActivity.kt deleted file mode 100644 index 146f7c1..0000000 --- a/android/app/src/main/java/com/ts3client/android/MainActivity.kt +++ /dev/null @@ -1,56 +0,0 @@ -package com.ts3client.android - -import android.content.Intent -import android.os.Bundle -import androidx.activity.ComponentActivity -import androidx.activity.compose.setContent -import androidx.activity.enableEdgeToEdge -import com.ts3client.android.ui.App -import com.ts3client.android.ui.Ts3Theme -import com.ts3client.session.ServerLink - -class MainActivity : ComponentActivity() { - - private val sessions get() = (application as Ts3Application).sessions - - override fun onCreate(savedInstanceState: Bundle?) { - enableEdgeToEdge() - super.onCreate(savedInstanceState) - if (savedInstanceState == null) sessions.connectStartupBookmarks(handle(intent)) - setContent { - Ts3Theme { App(sessions) } - } - } - - override fun onNewIntent(intent: Intent) { - super.onNewIntent(intent) - handle(intent) - } - - override fun onStart() { - super.onStart() - sessions.foreground = true - } - - override fun onStop() { - sessions.foreground = false - super.onStop() - } - - /** A notification opens its conversation; a `ts3server://` link or a bookmark shortcut connects, returning where. */ - private fun handle(intent: Intent): ServerLink? = when (intent.action) { - Intent.ACTION_VIEW -> ServerLink.parse(intent.dataString)?.also { sessions.open(it) } - BookmarkShortcuts.ACTION_CONNECT -> intent.getStringExtra(BookmarkShortcuts.EXTRA_BOOKMARK) - ?.let(sessions::openBookmark) - else -> { - openRequestedChat(intent) - null - } - } - - private fun openRequestedChat(intent: Intent) { - val serverId = intent.getIntExtra(MessageNotifier.EXTRA_SERVER, -1) - val clientId = intent.getIntExtra(MessageNotifier.EXTRA_CHAT, -1) - if (serverId >= 0 && clientId >= 0) sessions.requestChat(serverId, clientId) - } -} diff --git a/android/app/src/main/java/com/ts3client/android/MessageNotifier.kt b/android/app/src/main/java/com/ts3client/android/MessageNotifier.kt deleted file mode 100644 index 0cbd795..0000000 --- a/android/app/src/main/java/com/ts3client/android/MessageNotifier.kt +++ /dev/null @@ -1,141 +0,0 @@ -package com.ts3client.android - -import android.app.Notification -import android.app.NotificationChannel -import android.app.NotificationManager -import android.app.PendingIntent -import android.app.Person -import android.app.RemoteInput -import android.content.Context -import android.content.Intent - -/** - * Tells the user about pokes and private messages while the app is out of sight. The - * notifications themselves are silent: the sound pack already plays TeamSpeak's own sound - * for either, as it does in the app. - */ -class MessageNotifier(private val context: Context) { - - private val manager = context.getSystemService(NotificationManager::class.java) - private val me = Person.Builder().setName("You").build() - - /** What each private conversation's notification shows, by [id] of server and peer. */ - private val conversations = HashMap() - - private class Conversation(val peer: Person, val messages: MutableList) - - init { - manager.createNotificationChannels(listOf( - channel(MESSAGES, R.string.messages_channel), - channel(POKES, R.string.pokes_channel), - )) - } - - private fun channel(id: String, name: Int) = - NotificationChannel(id, context.getString(name), NotificationManager.IMPORTANCE_HIGH).apply { - setSound(null, null) - enableVibration(true) - } - - fun poke(from: String, message: String) { - val notification = Notification.Builder(context, POKES) - .setSmallIcon(android.R.drawable.stat_notify_chat) - .setContentTitle("$from poked you") - .setContentText(message.ifBlank { null }) - .setCategory(Notification.CATEGORY_MESSAGE) - .setContentIntent(open(null, null)) - .setAutoCancel(true) - .build() - manager.notify(POKE_TAG, from.hashCode(), notification) - } - - fun clearPokes() { - for (active in manager.activeNotifications) { - if (active.tag == POKE_TAG) manager.cancel(POKE_TAG, active.id) - } - } - - /** A message the peer sent, which starts the conversation's notification if it had none. */ - @Synchronized - fun received(serverId: Int, clientId: Int, from: String, text: String) { - val id = id(serverId, clientId) - val conversation = conversations[id]?.takeIf { it.peer.name == from } - ?: Conversation(Person.Builder().setName(from).setKey("client:$serverId:$clientId").build(), ArrayList()) - conversations[id] = conversation - add(serverId, clientId, conversation, text, conversation.peer, alert = true) - } - - /** Our own reply, shown in a conversation already notified of; answers the reply action too. */ - @Synchronized - fun sent(serverId: Int, clientId: Int, text: String) { - val conversation = conversations[id(serverId, clientId)] ?: return - add(serverId, clientId, conversation, text, me, alert = false) - } - - private fun add(serverId: Int, clientId: Int, conversation: Conversation, text: String, sender: Person, alert: Boolean) { - conversation.messages += Notification.MessagingStyle.Message(text, System.currentTimeMillis(), sender) - if (conversation.messages.size > MAX_MESSAGES) conversation.messages.removeAt(0) - val style = Notification.MessagingStyle(me) - conversation.messages.forEach(style::addMessage) - val notification = Notification.Builder(context, MESSAGES) - .setSmallIcon(android.R.drawable.stat_notify_chat) - .setStyle(style) - .setCategory(Notification.CATEGORY_MESSAGE) - .setContentIntent(open(serverId, clientId)) - .setOnlyAlertOnce(!alert) - .setAutoCancel(true) - .addAction(replyAction(serverId, clientId)) - .build() - manager.notify(MESSAGE_TAG, id(serverId, clientId), notification) - } - - /** The conversation came on screen, or ended with the connection. */ - @Synchronized - fun clear(serverId: Int, clientId: Int) { - val id = id(serverId, clientId) - conversations.remove(id) - manager.cancel(MESSAGE_TAG, id) - } - - /** The server's conversations, as its connection ended. */ - @Synchronized - fun clearServer(serverId: Int) { - conversations.keys.filter { it ushr 16 == serverId }.forEach { clear(serverId, it and 0xFFFF) } - } - - private fun open(serverId: Int?, clientId: Int?): PendingIntent { - val intent = Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) - if (serverId != null && clientId != null) { - intent.putExtra(EXTRA_SERVER, serverId).putExtra(EXTRA_CHAT, clientId) - } - return PendingIntent.getActivity(context, if (serverId != null && clientId != null) id(serverId, clientId) else -1, - intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) - } - - private fun replyAction(serverId: Int, clientId: Int): Notification.Action { - val intent = Intent(context, ReplyReceiver::class.java) - .putExtra(EXTRA_SERVER, serverId).putExtra(EXTRA_CHAT, clientId) - // Mutable: the system fills the typed reply into it. - val pending = PendingIntent.getBroadcast(context, id(serverId, clientId), intent, - PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) - return Notification.Action.Builder(null, "Reply", pending) - .addRemoteInput(RemoteInput.Builder(KEY_REPLY).setLabel("Message").build()) - .setSemanticAction(Notification.Action.SEMANTIC_ACTION_REPLY) - .build() - } - - /** Client ids are 16 bits, and only unique on their server. */ - private fun id(serverId: Int, clientId: Int) = serverId shl 16 or clientId - - companion object { - /** The server and the client id of the private chat a notification opens or replies to. */ - const val EXTRA_SERVER = "com.ts3client.android.SERVER" - const val EXTRA_CHAT = "com.ts3client.android.CHAT" - const val KEY_REPLY = "reply" - private const val MESSAGES = "messages" - private const val POKES = "pokes" - private const val MESSAGE_TAG = "message" - private const val POKE_TAG = "poke" - private const val MAX_MESSAGES = 25 - } -} diff --git a/android/app/src/main/java/com/ts3client/android/NetworkFollower.kt b/android/app/src/main/java/com/ts3client/android/NetworkFollower.kt deleted file mode 100644 index 5d3997a..0000000 --- a/android/app/src/main/java/com/ts3client/android/NetworkFollower.kt +++ /dev/null @@ -1,220 +0,0 @@ -package com.ts3client.android - -import android.content.Context -import android.net.ConnectivityManager -import android.net.Network -import com.ts3client.session.ServerSession -import kotlinx.coroutines.CompletableDeferred -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.delay -import kotlinx.coroutines.launch -import kotlinx.coroutines.withTimeoutOrNull -import java.util.concurrent.CopyOnWriteArrayList - -/** - * Keeps the connections on the network Android routes over. - * - * A TS3 server knows its clients by address, so once the phone moves from Wi-Fi to mobile - * data (or back) an old connection is dead weight: it can only time out. This notices the - * move, says goodbye over the old network while that still works, and connects again over - * the new one, back into the channel we were in. A server that still holds our old - * connection may refuse the new one for a while as a clone, so a failed attempt is retried. - * - * The process's sockets are bound to the network a connection was made over. Otherwise the - * old connection would silently follow the new default network, and its goodbye would come - * from an address the server does not know. A socket keeps the network it was made on, so - * each connection remembers its own. - */ -class NetworkFollower(context: Context) { - private val connectivity = context.getSystemService(ConnectivityManager::class.java) - private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) - private val follows = CopyOnWriteArrayList() - - /** The system's default network; null while there is none. */ - @Volatile - private var network: Network? = null - - init { - connectivity.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() { - override fun onAvailable(available: Network) { - network = available - follows.forEach(Follow::reconsider) - } - - override fun onLost(lost: Network) { - if (network == lost) network = null - follows.forEach(Follow::reconsider) - } - }) - } - - /** Follows [session] until [Follow.forget]. */ - fun follow(session: ServerSession, onChange: () -> Unit, system: (String) -> Unit): Follow = - Follow(session, onChange, system).also(follows::add) - - /** Binds new sockets to [to], or lets them go by the default network once no connection wants one. */ - private fun bind(to: Network?) { - connectivity.bindProcessToNetwork(to ?: follows.firstNotNullOfOrNull { f -> f.bound.takeIf { f.wanted } }) - } - - inner class Follow internal constructor( - private val session: ServerSession, - private val onChange: () -> Unit, - private val system: (String) -> Unit, - ) { - /** The network the connection was made over. */ - @Volatile - internal var bound: Network? = null - - /** The user wants to be on the server: from their connect until they, or the server, end it. */ - @Volatile - internal var wanted = false - - private var settle: Job? = null - @Volatile - private var recovery: Job? = null - @Volatile - private var attempt: CompletableDeferred? = null - - /** What to show in place of the session's status while getting back on the server. */ - @Volatile - var status: String? = null - private set - - val isRecovering: Boolean get() = recovery?.isActive == true - - /** Before a connect the user asked for, which goes over the network there is now. */ - fun connecting() { - recovery?.cancel() - wanted = true - bindHere(connectivity.activeNetwork) - } - - /** The user leaves the server. */ - fun leaving() { - wanted = false - recovery?.cancel() - unbind() - } - - /** The session is thrown away. */ - fun forget() { - leaving() - follows.remove(this) - } - - fun onConnected() { - attempt?.complete(true) - } - - fun onDisconnected() { - val pending = attempt - when { - pending != null -> pending.complete(false) - isRecovering -> {} - // A socket on a network that went away fails at once, before we hear of the change. - wanted && networkGone() -> synchronized(this) { - if (!isRecovering) recovery = recover() - } - // The server let us go (a kick, a shutdown, a failed first connect): leave it at that. - else -> { - wanted = false - unbind() - } - } - } - - /** Waits for the network to settle: a handover often shows several changes in a row. */ - internal fun reconsider() { - synchronized(this) { - settle?.cancel() - settle = scope.launch { - delay(SETTLE_MS) - synchronized(this@Follow) { - if (wanted && bound != network && !isRecovering) recovery = recover() - } - } - } - } - - private fun recover() = scope.launch { - try { - val back = withTimeoutOrNull(GIVE_UP_MS) { - system(if (connectivity.activeNetwork == null) "Network lost." else "Network changed, reconnecting…") - if (session.isBusy) session.connection().disconnectBlocking("Network changed") - var retry = RETRY_MS - while (true) { - val current = awaitNetwork() - bindHere(current) - show("Reconnecting…") - val done = CompletableDeferred() - attempt = done - session.reconnect() - val connected = done.await() - attempt = null - if (connected) break - if (session.connection().connectErrorId == ERROR_BANNED) break - show("Reconnecting, retrying soon…") - delay(retry) - retry = (retry * 2).coerceAtMost(MAX_RETRY_MS) - } - } - if (session.connection().connectErrorId == ERROR_BANNED) { - wanted = false - unbind() - } else if (back == null) { - system("Could not get back on the server.") - wanted = false - unbind() - } - } finally { - attempt = null - status = null - onChange() - // The network may have moved again while we were busy. - reconsider() - } - } - - private fun networkGone(): Boolean { - val on = bound ?: return false - return connectivity.getNetworkCapabilities(on) == null || connectivity.activeNetwork != on - } - - private suspend fun awaitNetwork(): Network { - while (true) { - connectivity.activeNetwork?.let { return it } - show("Waiting for network…") - delay(POLL_MS) - } - } - - private fun show(text: String) { - status = text - onChange() - } - - private fun bindHere(to: Network?) { - bound = to - bind(to) - } - - private fun unbind() { - bound = null - bind(null) - } - } - - private companion object { - const val SETTLE_MS = 1_500L - /** The server's refusal for a banned client; asking again will not help. */ - const val ERROR_BANNED = 3329 - const val RETRY_MS = 5_000L - const val MAX_RETRY_MS = 30_000L - const val POLL_MS = 500L - const val GIVE_UP_MS = 5 * 60_000L - } -} diff --git a/android/app/src/main/java/com/ts3client/android/Picture.kt b/android/app/src/main/java/com/ts3client/android/Picture.kt deleted file mode 100644 index 0340183..0000000 --- a/android/app/src/main/java/com/ts3client/android/Picture.kt +++ /dev/null @@ -1,42 +0,0 @@ -package com.ts3client.android - -import android.graphics.ImageDecoder -import android.graphics.drawable.AnimatedImageDrawable -import android.graphics.drawable.BitmapDrawable -import androidx.compose.ui.graphics.ImageBitmap -import androidx.compose.ui.graphics.asImageBitmap -import java.nio.ByteBuffer - -/** An avatar or a picture from a description: still, or moving like an animated GIF. */ -sealed interface Picture { - val width: Int - val height: Int - - data class Still(val bitmap: ImageBitmap) : Picture { - override val width get() = bitmap.width - override val height get() = bitmap.height - } - - /** Shared by whatever shows it: one animation, drawn wherever it is on screen. */ - data class Moving(val drawable: AnimatedImageDrawable) : Picture { - override val width get() = drawable.intrinsicWidth - override val height get() = drawable.intrinsicHeight - } -} - -/** Decodes any image Android knows, no larger than [maxPx] on its longer side; null if it is none. */ -internal fun decodePicture(data: ByteArray, maxPx: Int): Picture? = try { - val drawable = ImageDecoder.decodeDrawable(ImageDecoder.createSource(ByteBuffer.wrap(data))) { decoder, info, _ -> - val largest = maxOf(info.size.width, info.size.height) - if (largest > maxPx) { - decoder.setTargetSize(info.size.width * maxPx / largest, info.size.height * maxPx / largest) - } - } - when (drawable) { - is AnimatedImageDrawable -> Picture.Moving(drawable) - is BitmapDrawable -> Picture.Still(drawable.bitmap.asImageBitmap()) - else -> null - } -} catch (e: Exception) { - null -} diff --git a/android/app/src/main/java/com/ts3client/android/PttOverlay.kt b/android/app/src/main/java/com/ts3client/android/PttOverlay.kt deleted file mode 100644 index a30849e..0000000 --- a/android/app/src/main/java/com/ts3client/android/PttOverlay.kt +++ /dev/null @@ -1,176 +0,0 @@ -package com.ts3client.android - -import android.annotation.SuppressLint -import android.content.Context -import android.graphics.Bitmap -import android.graphics.Canvas -import android.graphics.Color -import android.graphics.Paint -import android.graphics.PixelFormat -import android.provider.Settings -import android.view.Gravity -import android.view.MotionEvent -import android.view.View -import android.view.ViewConfiguration -import android.view.WindowManager - -/** - * A push-to-talk button floating over other apps. Holding it talks; a double tap whose - * second touch is held moves it instead, so moving never transmits more than the first tap. - */ -class PttOverlay( - private val context: Context, - private val icons: IconTheme, - private val onPressed: (Boolean) -> Unit, -) { - enum class Look { IDLE, TALKING, MUTED } - - private val windows = context.getSystemService(WindowManager::class.java) - private val prefs = context.getSharedPreferences("overlay", Context.MODE_PRIVATE) - private val size = (SIZE_DP * context.resources.displayMetrics.density).toInt() - private var button: Button? = null - - /** Shows the button, or updates it when it is up; nothing while the app may not draw over others. */ - fun show(look: Look) { - button?.let { - it.look = look - return - } - if (!Settings.canDrawOverlays(context)) return - val params = WindowManager.LayoutParams( - size, size, - WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, - WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, - PixelFormat.TRANSLUCENT, - ).apply { - gravity = Gravity.TOP or Gravity.START - val screen = windows.currentWindowMetrics.bounds - x = prefs.getInt(POS_X, screen.width() - size - size / 4) - y = prefs.getInt(POS_Y, screen.height() / 2) - } - val view = Button(params).also { it.look = look } - try { - windows.addView(view, params) - } catch (e: WindowManager.BadTokenException) { - // The permission went away since the check. - return - } - button = view - } - - fun hide() { - val view = button ?: return - button = null - view.release() - windows.removeView(view) - } - - @SuppressLint("ViewConstructor") - private inner class Button(private val params: WindowManager.LayoutParams) : View(context) { - - var look = Look.IDLE - set(value) { - field = value - restyle() - } - - private val paint = Paint(Paint.ANTI_ALIAS_FLAG) - private val doubleTapTimeout = ViewConfiguration.getDoubleTapTimeout().toLong() - private var pressed = false - private var dragging = false - private var lastTapUp = 0L - private var grabX = 0f - private var grabY = 0f - - init { - contentDescription = "Push to talk" - alpha = RESTING_ALPHA - } - - /** Half see-through at rest, so it hides less of the app beneath; solid while it talks. */ - private fun restyle() { - alpha = if (pressed || look == Look.TALKING) 1f else RESTING_ALPHA - invalidate() - } - - override fun onDraw(canvas: Canvas) { - val radius = width / 2f - val lit = pressed || look == Look.TALKING - paint.color = when { - look == Look.MUTED -> MUTED - lit -> TALKING - else -> IDLE - } - canvas.drawCircle(radius, radius, radius, paint) - if (lit) { - paint.color = Color.WHITE - paint.style = Paint.Style.STROKE - paint.strokeWidth = radius / 12 - canvas.drawCircle(radius, radius, radius - paint.strokeWidth, paint) - paint.style = Paint.Style.FILL - } - val iconSize = width / 2 - icon(iconSize)?.let { - val offset = (width - iconSize) / 2f - canvas.drawBitmap(it, offset, offset, null) - } - } - - private fun icon(size: Int): Bitmap? = - icons.renderMaterial(if (look == Look.MUTED) "INPUT_MUTED" else "CAPTURE", size, Color.WHITE) - - @SuppressLint("ClickableViewAccessibility") - override fun onTouchEvent(e: MotionEvent): Boolean { - when (e.actionMasked) { - MotionEvent.ACTION_DOWN -> { - dragging = e.eventTime - lastTapUp < doubleTapTimeout - if (dragging) { - grabX = e.rawX - params.x - grabY = e.rawY - params.y - } else { - press(true) - } - } - MotionEvent.ACTION_MOVE -> if (dragging) moveTo(e.rawX - grabX, e.rawY - grabY) - MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { - val tap = !dragging && e.eventTime - e.downTime < doubleTapTimeout - lastTapUp = if (tap) e.eventTime else 0L - if (dragging) { - dragging = false - prefs.edit().putInt(POS_X, params.x).putInt(POS_Y, params.y).apply() - } else { - press(false) - } - } - } - return true - } - - private fun moveTo(x: Float, y: Float) { - val screen = windows.currentWindowMetrics.bounds - params.x = x.toInt().coerceIn(0, screen.width() - width) - params.y = y.toInt().coerceIn(0, screen.height() - height) - windows.updateViewLayout(this, params) - } - - private fun press(down: Boolean) { - if (pressed == down) return - pressed = down - onPressed(down) - restyle() - } - - /** Lets go of the microphone should the button vanish under the finger. */ - fun release() = press(false) - } - - private companion object { - const val SIZE_DP = 64 - const val RESTING_ALPHA = 0.5f - const val POS_X = "x" - const val POS_Y = "y" - val IDLE = Color.rgb(0x1C, 0x6F, 0xB8) - val TALKING = Color.rgb(0x2E, 0x9B, 0xF0) - val MUTED = Color.rgb(0x42, 0x42, 0x42) - } -} diff --git a/android/app/src/main/java/com/ts3client/android/ReplyReceiver.kt b/android/app/src/main/java/com/ts3client/android/ReplyReceiver.kt deleted file mode 100644 index c84b94a..0000000 --- a/android/app/src/main/java/com/ts3client/android/ReplyReceiver.kt +++ /dev/null @@ -1,17 +0,0 @@ -package com.ts3client.android - -import android.app.RemoteInput -import android.content.BroadcastReceiver -import android.content.Context -import android.content.Intent - -/** Sends what the user typed into a private message notification. */ -class ReplyReceiver : BroadcastReceiver() { - override fun onReceive(context: Context, intent: Intent) { - val serverId = intent.getIntExtra(MessageNotifier.EXTRA_SERVER, -1) - val clientId = intent.getIntExtra(MessageNotifier.EXTRA_CHAT, -1) - val text = RemoteInput.getResultsFromIntent(intent)?.getCharSequence(MessageNotifier.KEY_REPLY)?.toString() - if (serverId < 0 || clientId < 0 || text.isNullOrBlank()) return - (context.applicationContext as Ts3Application).sessions.reply(serverId, clientId, text) - } -} diff --git a/android/app/src/main/java/com/ts3client/android/SavedPictures.kt b/android/app/src/main/java/com/ts3client/android/SavedPictures.kt deleted file mode 100644 index 0a250c8..0000000 --- a/android/app/src/main/java/com/ts3client/android/SavedPictures.kt +++ /dev/null @@ -1,39 +0,0 @@ -package com.ts3client.android - -import android.content.ContentValues -import android.content.Context -import android.graphics.BitmapFactory -import android.os.Environment -import android.provider.MediaStore -import android.webkit.MimeTypeMap -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext - -/** Puts pictures into the shared Pictures collection, in a TeamSpeak album, where galleries find them. */ -object SavedPictures { - - /** Saves [data] as [name], its extension following what the data is; false if it could not be. */ - suspend fun save(context: Context, name: String, data: ByteArray): Boolean = withContext(Dispatchers.IO) { - val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } - BitmapFactory.decodeByteArray(data, 0, data.size, bounds) - val mime = bounds.outMimeType ?: return@withContext false - val extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mime) - val values = ContentValues().apply { - put(MediaStore.Images.Media.DISPLAY_NAME, if (extension == null) name else "$name.$extension") - put(MediaStore.Images.Media.MIME_TYPE, mime) - put(MediaStore.Images.Media.RELATIVE_PATH, "${Environment.DIRECTORY_PICTURES}/TeamSpeak") - put(MediaStore.Images.Media.IS_PENDING, 1) - } - val resolver = context.contentResolver - val uri = resolver.insert(MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY), values) - ?: return@withContext false - try { - resolver.openOutputStream(uri)!!.use { it.write(data) } - resolver.update(uri, ContentValues().apply { put(MediaStore.Images.Media.IS_PENDING, 0) }, null, null) - true - } catch (e: Exception) { - resolver.delete(uri, null, null) - false - } - } -} diff --git a/android/app/src/main/java/com/ts3client/android/ServerController.kt b/android/app/src/main/java/com/ts3client/android/ServerController.kt deleted file mode 100644 index 7a84cc9..0000000 --- a/android/app/src/main/java/com/ts3client/android/ServerController.kt +++ /dev/null @@ -1,582 +0,0 @@ -package com.ts3client.android - -import android.net.Uri -import com.ts3client.config.Bookmark -import com.ts3client.contacts.ContactType -import com.ts3client.config.WhisperList -import com.ts3client.net.ChannelNode -import com.ts3client.net.ClientEntry -import com.ts3client.net.ChannelSettings -import com.ts3client.net.ConnectionStats -import com.ts3client.net.Details -import com.ts3client.net.GroupChoice -import com.ts3client.net.Whisper -import com.ts3client.net.ban.BanEntry -import com.ts3client.net.ban.BanRule -import com.ts3client.net.filetransfer.RemoteFile -import com.ts3client.net.ConnectionListener.ChatScope -import com.ts3client.session.ServerLink -import com.ts3client.session.ServerSession -import com.ts3client.text.ChatHtml -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.cancel -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.update -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext -import java.io.File -import java.util.concurrent.atomic.AtomicBoolean -import java.util.concurrent.atomic.AtomicLong -import kotlin.coroutines.resume -import kotlin.coroutines.suspendCoroutine - -/** - * One server the app is on: its [ServerSession], and the snapshots the UI shows of it. Session - * callbacks arrive on connection threads and are turned into immutable snapshots. - */ -class ServerController internal constructor( - /** Unique among the servers of this process run. */ - val id: Int, - private val app: SessionController, -) { - internal val session = ServerSession( - app.settings, app.identityStore, app.audio, app.sounds, app.contactStore, Listener() - ) - internal val conn get() = session.connection() - private val network = app.network.follow(session, ::refresh, ::system) - - /** Whether this server holds the microphone; set by [SessionController] as it moves. */ - @Volatile - internal var micOwner = false - - /** Set once connecting began, so a session that never started is not taken for one that ended. */ - @Volatile - private var started = false - - /** Set when the user left, so the end needs no telling. */ - @Volatile - internal var left = false - - private val _state = MutableStateFlow(SessionState()) - val state: StateFlow = _state - - private val _tree = MutableStateFlow(ServerTree()) - val tree: StateFlow = _tree - - private val _chats = MutableStateFlow(Chats()) - val chats: StateFlow = _chats - - /** Channels the user folded away in the tree. */ - private val _collapsed = MutableStateFlow(emptySet()) - val collapsed: StateFlow> = _collapsed - - /** The conversation on screen, whose new lines are read as they come. */ - @Volatile - var viewing: ChatKey? = null - set(value) { - field = value - if (value != null) markRead(value) - if (value is ChatKey.Private) app.notifier.clear(id, value.clientId) - } - - /** Counts the answers to info requests, for the details on screen to be read again. */ - private val _infoUpdates = MutableStateFlow(0) - val infoUpdates: StateFlow = _infoUpdates - - val images = ServerImages(conn) - - /** A private chat a notification asked to show, until the UI took it up. */ - private val _chatRequest = MutableStateFlow(null) - val chatRequest: StateFlow = _chatRequest - - private val lineIds = AtomicLong() - - /** Tree snapshots are taken one at a time, at most once per [TREE_FRAME_MS]. */ - private val treeScope = CoroutineScope(SupervisorJob() + Dispatchers.Default.limitedParallelism(1)) - private val treePending = AtomicBoolean() - private val structureChanged = AtomicBoolean(true) - private var roots: List = emptyList() - - val isConnected: Boolean get() = session.isConnected - internal val isBusy: Boolean get() = session.isBusy || network.isRecovering - internal val microphone get() = if (session.isConnected) conn.microphone else null - internal val playback get() = if (session.isConnected) conn.playback else null - - /** Not on the server and not trying to get back on it: done with. */ - internal val ended: Boolean get() = started && !isBusy - - // ---- connection ---- - - internal fun start(host: String, port: Int, nickname: String, password: String, identityId: String, - channel: String, channelPassword: String) { - network.connecting() - started = true - session.connect(host, port, nickname, password, identityId, channel, channelPassword) - refresh() - } - - internal fun open(link: ServerLink, identityId: String) { - network.connecting() - started = true - session.open(link, identityId) - refresh() - } - - /** A bookmark leading back to this server, joining [channelId]; not yet saved. */ - fun bookmark(channelId: Int): Bookmark? = session.toBookmark(conn.model.channelPath(channelId)) - - fun disconnect() { - left = true - network.leaving() - session.disconnect() - } - - /** Before the app goes away with the connection, which [SessionController.leave] then ends. */ - internal fun leaving() { - left = true - network.leaving() - } - - internal fun dispose() { - network.forget() - treeScope.cancel() - session.dispose() - } - - // ---- the local client ---- - - fun setMicMuted(muted: Boolean) = session.setMicMuted(muted) - - fun setDeafened(deafened: Boolean) = session.setDeafened(deafened) - - fun setAway(away: Boolean) = session.setAway(away, null) - - // ---- channels and clients ---- - - fun joinChannel(channelId: Int, password: String? = null) { - if (session.isConnected) conn.joinChannel(channelId, password) - } - - fun setSubscribed(channelId: Int, subscribed: Boolean) { - if (session.isConnected) conn.setChannelsSubscribed(listOf(channelId), subscribed) - } - - fun toggleCollapsed(channelId: Int) = - _collapsed.update { if (channelId in it) it - channelId else it + channelId } - - fun expand(channelIds: Collection) = _collapsed.update { it - channelIds.toSet() } - - val canMoveClients: Boolean get() = session.canMoveClients() - - fun moveClient(clientId: Int, channelId: Int) { - if (session.isConnected) conn.moveClient(clientId, channelId, null) - } - - fun poke(clientId: Int, message: String) { - if (session.isConnected) conn.poke(clientId, message) - } - - /** The client's playback volume change in dB; 0 when unchanged. */ - fun clientVolume(clientId: Int): Double = - conn.model.getClient(clientId)?.let { conn.getClientVolumeModifier(it) } ?: 0.0 - - fun setClientVolume(clientId: Int, decibels: Double) { - conn.model.getClient(clientId)?.let { conn.setClientVolumeModifier(it, decibels) } - } - - // ---- whisper ---- - - fun setWhisper(whisper: Whisper?) = session.setWhisper(whisper) - - fun whisperToChannel(channelId: Int) = conn.model.getChannel(channelId)?.let { setWhisper(Whisper.toChannel(it)) } - - fun whisperToClient(clientId: Int) = conn.model.getClient(clientId)?.let { setWhisper(Whisper.toClient(it)) } - - /** The client who whispered to us last, while on the server. */ - fun lastWhisperer(): ClientEntry? = session.lastWhisperer() - - /** A channel as a whisper list holds it: by path, so the list works on any server with that channel. */ - fun channelRef(channelId: Int): String? = conn.model.getChannel(channelId)?.let { conn.model.channelPath(it.id) } - - fun clientRef(clientId: Int): WhisperList.Client? = - conn.model.getClient(clientId)?.let { WhisperList.Client(it.uniqueId, it.nickname) } - - /** The clients on the server, for adding to a whisper list; ourselves left out. */ - fun clientRefs(): List = if (!session.isConnected) emptyList() - else conn.model.allClients().filter { it.id != conn.selfClientId && !it.uniqueId.isNullOrEmpty() } - .sortedBy { it.nickname.lowercase() }.map { WhisperList.Client(it.uniqueId, it.nickname) } - - fun channelPaths(): List = session.channelPaths() - - // ---- channel administration ---- - - val canCreateChannels: Boolean get() = session.canCreateChannels() - val canEditChannels: Boolean get() = session.canEditChannels() - val canDeleteChannels: Boolean get() = session.canDeleteChannels() - - /** The channels a channel can sort after: its siblings, or [parentId]'s children for a new one. */ - fun sortChoices(channelId: Int, parentId: Int): List = - if (channelId > 0) conn.model.siblingsOf(channelId) else conn.model.childrenOf(parentId) - - /** A channel's editable properties as the server has them. */ - suspend fun channelSettings(channelId: Int): Result = suspendCoroutine { done -> - conn.requestChannelSettings(channelId) { settings, error -> - done.resume(if (error == null) Result.success(settings) else Result.failure(IllegalStateException(error))) - } - } - - /** Each of these answers null once done, else why not. */ - suspend fun editChannel(channelId: Int, changes: Map): String? = - if (changes.isEmpty()) null - else suspendCoroutine { done -> conn.applyChannelEdit(channelId, changes, emptyMap(), emptyList()) { done.resume(it) } } - - suspend fun createChannel(parentId: Int, settings: ChannelSettings): String? = suspendCoroutine { done -> - conn.createChannel(parentId, settings.creationParameters(), emptyMap()) { _, error -> done.resume(error) } - } - - /** Deletes a channel, with its sub-channels and the clients in it moved out. */ - suspend fun deleteChannel(channelId: Int): String? = - suspendCoroutine { done -> conn.deleteChannel(channelId, true) { done.resume(it) } } - - // ---- files ---- - - val files = app.fileTransfers { conn } - - /** The files in a directory of a channel's repository; empty for an empty one. */ - suspend fun listFiles(channelId: Int, password: String, path: String): Result> = - withContext(Dispatchers.IO) { runCatching { conn.listFiles(channelId, password, path) } } - - /** Each of these answers null once done, else why not. */ - suspend fun createDirectory(channelId: Int, password: String, path: String): String? = - fileCall { conn.createDirectory(channelId, password, path) } - - suspend fun deleteFile(channelId: Int, password: String, path: String): String? = - fileCall { conn.deleteFile(channelId, password, path) } - - suspend fun renameFile(channelId: Int, password: String, from: String, to: String): String? = - fileCall { conn.renameFile(channelId, password, from, to) } - - private suspend fun fileCall(call: () -> Unit): String? = withContext(Dispatchers.IO) { - runCatching(call).exceptionOrNull()?.let { it.message ?: it.javaClass.simpleName } - } - - // ---- moderation ---- - - val canKickFromChannel: Boolean get() = session.canKickFromChannel() - val canKickFromServer: Boolean get() = session.canKickFromServer() - val canBanClients: Boolean get() = session.canBanClients() - val canViewBanList: Boolean get() = session.canViewBanList() - val canCreateBans: Boolean get() = session.isConnected && conn.model.permits("b_client_ban_create") - - /** The longest ban we may hand out in seconds; 0 or -1 for no limit. */ - val maxBanSeconds: Long get() = conn.model.maxBanSeconds() - - fun kickFromChannel(clientId: Int, reason: String) { - if (session.isConnected) conn.kickFromChannel(clientId, reason) - } - - fun kickFromServer(clientId: Int, reason: String) { - if (session.isConnected) conn.kickFromServer(clientId, reason) - } - - /** Bans a client for [seconds], or for good with 0. */ - fun ban(clientId: Int, seconds: Long, reason: String) { - if (session.isConnected) conn.banClient(clientId, seconds, reason) - } - - fun serverGroupChoices(clientId: Int): List = - conn.model.getClient(clientId)?.let(conn.model::serverGroupChoices).orEmpty() - - fun channelGroupChoices(clientId: Int): List = - conn.model.getClient(clientId)?.let(conn.model::channelGroupChoices).orEmpty() - - fun setServerGroup(clientId: Int, groupId: Int, assign: Boolean) { - val client = conn.model.getClient(clientId) ?: return - if (session.isConnected) conn.setClientServerGroup(client.databaseId, groupId, assign) - } - - /** Gives a client [groupId] in the channel they are in. */ - fun setChannelGroup(clientId: Int, groupId: Int) { - val client = conn.model.getClient(clientId) ?: return - if (session.isConnected) conn.setClientChannelGroup(client.databaseId, client.channelId, groupId) - } - - // ---- ban list ---- - - /** The server's bans, or why they could not be read. */ - /** One reading of a client's connection figures, or null when not connected. */ - suspend fun connectionStats(clientId: Int): ConnectionStats? = - if (!session.isConnected) null - else suspendCoroutine { done -> conn.requestConnectionInfo(clientId) { done.resume(it) } } - - suspend fun banList(): Result> = suspendCoroutine { done -> - conn.requestBanList { bans, error -> - done.resume(if (error == null) Result.success(bans) else Result.failure(IllegalStateException(error))) - } - } - - /** Each of these answers null once done, else why not. */ - suspend fun addBan(rule: BanRule): String? = suspendCoroutine { done -> conn.addBan(rule) { done.resume(it) } } - - suspend fun replaceBan(banId: Int, rule: BanRule): String? = - suspendCoroutine { done -> conn.replaceBan(banId, rule) { done.resume(it) } } - - suspend fun deleteBans(banIds: Collection): String? = - suspendCoroutine { done -> conn.deleteBans(banIds) { done.resume(it) } } - - fun canDeleteBans(bans: Collection): Boolean = conn.model.canDeleteBans(bans, conn.selfUniqueId) - - fun canEditBan(ban: BanEntry): Boolean = conn.model.canEditBan(ban, conn.selfUniqueId) - - fun isOwnBan(ban: BanEntry): Boolean = ban.createdBy(conn.selfUniqueId) - - /** Uploads [data] as our avatar; null once it is set, else why not. */ - suspend fun setAvatar(data: ByteArray): String? { - if (!session.isConnected) return "Not connected" - val file = withContext(Dispatchers.IO) { - File.createTempFile("avatar", null, app.cacheDir).apply { writeBytes(data) } - } - return try { - suspendCoroutine { done -> conn.setAvatar(file) { done.resume(it) } } - } finally { - file.delete() - } - } - - // ---- details ---- - - fun serverDetails(): Details? = - if (session.isConnected) Details.server(conn.model, "${conn.serverHost}:${conn.serverPort}") else null - - fun channelDetails(channelId: Int): Details? = conn.model.getChannel(channelId)?.let(Details::channel) - - fun clientDetails(clientId: Int): Details? = conn.model.getClient(clientId)?.let { - Details.client(it, conn.model, app.contactStore.find(it.uniqueId)) - } - - /** Asks the server for what the channel's details lack; they change once it answers. */ - fun requestChannelDetails(channelId: Int) { - val channel = conn.model.getChannel(channelId) ?: return - if (session.isConnected && !channel.descriptionLoaded) conn.requestChannelInfo(channelId) - } - - fun requestClientDetails(clientId: Int) { - if (session.isConnected) conn.requestClientInfo(clientId) - } - - /** Files a client on the server as a contact; a new entry takes the type's defaults. */ - fun addContact(clientId: Int, type: ContactType) { - val client = conn.model.getClient(clientId) ?: return - app.contactStore.add(client.uniqueId, client.nickname, type, app.settings.contactDefaults) - } - - internal fun contactsChanged() { - treeScope.launch { conn.applyContacts() } - scheduleTree(structure = false) - } - - // ---- chat ---- - - /** Opens the private chat with a client, loading what was said before. */ - fun openPrivateChat(clientId: Int): ChatKey.Private { - val key = ChatKey.Private(clientId) - val client = conn.model.getClient(clientId) - if (client != null) { - _chats.update { chats -> - chats.update(key, conn.displayName(client)) { it.copy(uniqueId = client.uniqueId) } - } - conn.loadPrivateChatHistory(clientId, client.uniqueId) - } - return key - } - - fun closePrivateChat(key: ChatKey.Private) = _chats.update { it.close(key) } - - fun send(key: ChatKey, text: String) = session.sendChat(scope(key), peer(key), text) - - /** Shares the file at [uri] in a chat, through myTeamSpeak; failures are told in the chat or as errors. */ - suspend fun sendFile(key: ChatKey, uri: Uri) { - app.openShared(uri) - .onSuccess { session.sendAttachment(scope(key), peer(key), app.attachments, it.data, it.size, it.name) } - .onFailure { app.error(it.message ?: "Could not read the file") } - } - - private fun scope(key: ChatKey) = when (key) { - ChatKey.Server -> ChatScope.SERVER - ChatKey.Channel -> ChatScope.CHANNEL - is ChatKey.Private -> ChatScope.PRIVATE - } - - private fun peer(key: ChatKey) = if (key is ChatKey.Private) key.clientId else 0 - - /** Where files shared on this server lie; empty before it is known. */ - private val room: String get() = conn.serverUniqueId().orEmpty() - - fun markRead(key: ChatKey) { - if (_chats.value[key]?.unread == true) _chats.update { chats -> chats.update(key) { it.copy(unread = false) } } - } - - internal fun requestChat(clientId: Int) { - _chatRequest.value = ChatKey.Private(clientId) - } - - fun chatRequestHandled() { - _chatRequest.value = null - } - - /** Answers a private message from its notification. */ - internal fun reply(clientId: Int, text: String) { - if (session.isConnected) send(ChatKey.Private(clientId), text) else app.notifier.clear(id, clientId) - } - - private fun append(key: ChatKey, title: String, html: String) { - if (html.isEmpty()) return - val line = ChatLine(lineIds.incrementAndGet(), html) - _chats.update { chats -> chats.update(key, title) { it.append(line, read = viewing == key) } } - } - - private fun setHistory(key: ChatKey, title: String, entries: List) { - val lines = entries.map { ChatHtml.logEntry(it, room) }.filter { it.isNotEmpty() } - .map { ChatLine(lineIds.incrementAndGet(), it) } - _chats.update { chats -> chats.update(key, title) { it.copy(lines = lines) } } - } - - private fun system(text: String) = append(ChatKey.Server, "", ChatHtml.system(text)) - - // ---- snapshots ---- - - private fun snapshotState(): SessionState { - val self = conn.model.getClient(conn.selfClientId) - return SessionState( - title = session.title(), - status = network.status ?: session.status(), - connected = session.isConnected, - busy = isBusy, - micActive = micOwner && app.hasMicPermission(), - micPermission = app.hasMicPermission(), - micMuted = session.isMicMuted, - deafened = session.isDeafened, - away = session.isAway, - selfClientId = if (session.isConnected) conn.selfClientId else 0, - channelId = if (session.isConnected) self?.channelId ?: 0 else 0, - inputMode = app.settings.inputMode, - hostButton = if (session.isConnected) conn.model.hostButton() else null, - self = session.selfState(), - whisper = session.whisper()?.label, - whisperNobody = session.isWhisperingToNobody, - ) - } - - internal fun refresh() { - _state.value = snapshotState() - app.serverChanged(this) - } - - /** Takes a new tree snapshot soon; [structure] when channels or clients came, went or moved. */ - internal fun scheduleTree(structure: Boolean) { - if (structure) structureChanged.set(true) - if (!treePending.compareAndSet(false, true)) return - treeScope.launch { - delay(TREE_FRAME_MS) - treePending.set(false) - if (structureChanged.getAndSet(false)) roots = conn.model.buildTree() - _tree.value = ServerTree.of(roots, conn.model, conn.contacts, app.settings.colorContacts, - app.settings.countryFlags, app.settings.clientRowColors) - val serverName = if (session.isConnected) conn.model.serverName.orEmpty() else "" - val channelName = session.currentChannel()?.name.orEmpty() - _chats.update { - it.copy( - server = it.server.copy(title = serverName.ifBlank { "Server" }), - channel = it.channel.copy(title = channelName.ifBlank { "Channel" }), - ) - } - refresh() - } - } - - private inner class Listener : ServerSession.Listener { - override fun onSessionChanged() = refresh() - override fun onSystemMessage(text: String) = system(text) - - override fun onOwnChat(scope: ChatScope, peerClientId: Int, peerName: String, text: String) { - val self = conn.model.getClient(conn.selfClientId)?.nickname ?: app.settings.nickname - val html = ChatHtml.message(conn.selfClientId, conn.selfUniqueId, "$self (you)", text, room) - append(key(scope, peerClientId), peerName, html) - if (scope == ChatScope.PRIVATE) app.notifier.sent(id, peerClientId, ChatHtml.plainMessage(text)) - } - - override fun onStatus(status: String) {} - - override fun onConnected() { - network.onConnected() - app.connected(this@ServerController) - refresh() - } - - override fun onDisconnected(reason: String?) { - network.onDisconnected() - app.notifier.clearServer(id) - _chats.update { it.copy(private = emptyList()) } - app.disconnected(this@ServerController) - scheduleTree(structure = true) - refresh() - } - - override fun onModelChanged() { - scheduleTree(structure = true) - // A server edit may have changed it. - if (session.isConnected && conn.model.hostButton() != _state.value.hostButton) refresh() - } - - override fun onServerIconChanged(iconId: Long) = - app.serverIconChanged(session.address(), session.port(), iconId) - - override fun onInfoUpdated() { - _infoUpdates.update { it + 1 } - // Avatars announce their arrival as info updates. - images.loaded() - } - - override fun onIconsUpdated() = images.loaded() - - override fun onChat(scope: ChatScope, fromClientId: Int, fromUniqueId: String?, fromName: String, message: String) { - append(key(scope, fromClientId), fromName, ChatHtml.message(fromClientId, fromUniqueId, fromName, message, room)) - if (scope == ChatScope.PRIVATE && !app.foreground) { - app.notifier.received(id, fromClientId, fromName, ChatHtml.plainMessage(message)) - } - } - - override fun onChatHistory(scope: ChatScope, htmlEntries: List) { - if (scope != ChatScope.PRIVATE) setHistory(key(scope, 0), "", htmlEntries) - } - - override fun onPrivateChatHistory(clientId: Int, nickname: String, htmlEntries: List) = - setHistory(ChatKey.Private(clientId), nickname, htmlEntries) - - override fun onTalkStateChanged(clientId: Int, talking: Boolean) { - if (clientId == conn.selfClientId && micOwner) app.talking(talking) - scheduleTree(structure = false) - } - - override fun onError(message: String) = app.error(message) - - override fun onPoke(fromName: String, message: String) = app.poked(fromName, message) - - override fun onServerLog(message: String) = append(ChatKey.Server, "", ChatHtml.serverLog(message)) - override fun onServerLogHtml(html: String) = append(ChatKey.Server, "", ChatHtml.logEntry(html, room)) - } - - private fun key(scope: ChatScope, peerClientId: Int): ChatKey = when (scope) { - ChatScope.SERVER -> ChatKey.Server - ChatScope.CHANNEL -> ChatKey.Channel - ChatScope.PRIVATE -> ChatKey.Private(peerClientId) - } - - private companion object { - const val TREE_FRAME_MS = 30L - } -} diff --git a/android/app/src/main/java/com/ts3client/android/ServerImages.kt b/android/app/src/main/java/com/ts3client/android/ServerImages.kt deleted file mode 100644 index a4a726e..0000000 --- a/android/app/src/main/java/com/ts3client/android/ServerImages.kt +++ /dev/null @@ -1,61 +0,0 @@ -package com.ts3client.android - -import android.graphics.BitmapFactory -import androidx.compose.ui.graphics.ImageBitmap -import androidx.compose.ui.graphics.asImageBitmap -import com.ts3client.net.TeamspeakConnection -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.update -import java.util.concurrent.ConcurrentHashMap - -/** - * One server's icons and its clients' avatars, decoded once. What is still - * downloading reads as null until [version] moves on. - */ -class ServerImages internal constructor(private val conn: TeamspeakConnection) { - - private val icons = ConcurrentHashMap() - private val avatars = ConcurrentHashMap() - - private val _version = MutableStateFlow(0) - val version: StateFlow = _version - - internal fun loaded() = _version.update { it + 1 } - - fun icon(id: Long): ImageBitmap? { - if (id == 0L) return null - icons[id]?.let { return it } - val bitmap = conn.icons.get(id)?.let { decode(it, ICON_PX) } ?: return null - icons[id] = bitmap - return bitmap - } - - fun avatar(uniqueId: String, flag: String): Picture? { - if (flag.isEmpty()) return null - avatars[flag]?.let { return it } - val picture = conn.avatars.get(uniqueId, flag)?.let { decodePicture(it.data(), AVATAR_PX) } ?: return null - avatars[flag] = picture - return picture - } - - /** The avatar's file as the server keeps it; null while it has none or it is still downloading. */ - fun avatarData(uniqueId: String, flag: String): ByteArray? = - if (flag.isEmpty()) null else conn.avatars.get(uniqueId, flag)?.data() - - /** Decoded no larger than needed: avatars may be far bigger than they are ever shown. */ - private fun decode(data: ByteArray, maxPx: Int): ImageBitmap? { - val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } - BitmapFactory.decodeByteArray(data, 0, data.size, bounds) - if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null - var sample = 1 - while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= maxPx) sample *= 2 - val options = BitmapFactory.Options().apply { inSampleSize = sample } - return BitmapFactory.decodeByteArray(data, 0, data.size, options)?.asImageBitmap() - } - - private companion object { - const val ICON_PX = 64 - const val AVATAR_PX = 512 - } -} diff --git a/android/app/src/main/java/com/ts3client/android/ServerTree.kt b/android/app/src/main/java/com/ts3client/android/ServerTree.kt deleted file mode 100644 index 824a030..0000000 --- a/android/app/src/main/java/com/ts3client/android/ServerTree.kt +++ /dev/null @@ -1,192 +0,0 @@ -package com.ts3client.android - -import androidx.compose.runtime.Immutable -import com.ts3client.config.ClientRowColors -import com.ts3client.contacts.ContactStore -import com.ts3client.contacts.ContactType -import com.ts3client.net.ChannelNode -import com.ts3client.net.ClientEntry -import com.ts3client.net.ClientStatus -import com.ts3client.net.ServerModel -import com.ts3client.net.Spacers -import com.ts3client.net.TreeMatch -import com.ts3client.text.TextQuery - -/** - * A copy of the channel tree taken at one moment. The model's own nodes change in place - * on connection threads, which Compose cannot observe; these never change. - */ -@Immutable -data class ServerTree( - val channels: List = emptyList(), - /** The server's own icon; 0 for none. */ - val serverIconId: Long = 0, - /** Whether client rows show their country's flag. */ - val countryFlags: Boolean = false, -) { - - fun channel(id: Int): ChannelItem? = find(channels) { it.id == id } - - fun client(id: Int): ClientItem? { - var found: ClientItem? = null - find(channels) { c -> found = c.clients.firstOrNull { it.id == id }; found != null } - return found - } - - /** The channels from the root down to the one [clientId] is in; null when they are not in the tree. */ - fun pathTo(clientId: Int): List? { - fun walk(items: List): List? { - for (c in items) { - if (c.clients.any { it.id == clientId }) return listOf(c.id) - walk(c.children)?.let { return listOf(c.id) + it } - } - return null - } - return walk(channels) - } - - /** The channels from the root down to [channelId]'s parent; null when it is not in the tree. */ - fun parentsOf(channelId: Int): List? { - fun walk(items: List, above: List): List? { - for (c in items) { - if (c.id == channelId) return above - walk(c.children, above + c.id)?.let { return it } - } - return null - } - return walk(channels, emptyList()) - } - - /** The ids of what [find] matches, in reading order. */ - fun hits(find: TreeFind): List { - val out = ArrayList() - fun walk(items: List) { - for (c in items) { - if (find.matches(c)) out += c.id - c.clients.forEach { if (find.matches(it)) out += it.id } - walk(c.children) - } - } - if (!find.query.isEmpty) walk(channels) - return out - } - - /** Only what [find] matches: a matching channel with its clients, a matching client, and the channels leading to either. */ - fun only(find: TreeFind): ServerTree { - fun keep(c: ChannelItem): ChannelItem? { - val matches = find.matches(c) - val clients = if (matches) c.clients else c.clients.filter(find::matches) - val children = c.children.mapNotNull(::keep) - return if (matches || clients.isNotEmpty() || children.isNotEmpty()) c.copy(clients = clients, children = children) else null - } - return copy(channels = channels.mapNotNull(::keep)) - } - - private fun find(items: List, test: (ChannelItem) -> Boolean): ChannelItem? { - for (c in items) { - if (test(c)) return c - find(c.children, test)?.let { return it } - } - return null - } - - companion object { - fun of(roots: List, model: ServerModel, contacts: ContactStore, colorContacts: Boolean, - countryFlags: Boolean, rowColors: ClientRowColors): ServerTree = - ServerTree( - roots.map { channel(it, model, contacts, colorContacts, rowColors) }, - model.serverIconId(), - countryFlags, - ) - - private fun channel(c: ChannelNode, model: ServerModel, contacts: ContactStore, colorContacts: Boolean, - rowColors: ClientRowColors): ChannelItem { - val clients = c.clients - val spacer = Spacers.parse(c.name) - return ChannelItem( - id = c.id, - name = c.name ?: "", - spacer = spacer, - iconId = if (spacer == null) c.iconId else 0, - locked = c.hasPassword, - full = c.maxClients >= 0 && clients.size >= c.maxClients, - subscribed = c.subscribed, - clients = clients.map { client(it, model, contacts, colorContacts, rowColors) }, - children = c.children.map { channel(it, model, contacts, colorContacts, rowColors) }, - ) - } - - private fun client(c: ClientEntry, model: ServerModel, contacts: ContactStore, colorContacts: Boolean, - rowColors: ClientRowColors): ClientItem { - val contact = contacts.find(c.uniqueId) - val away = c.away && c.awayMessage.isNotEmpty() && contact?.ignoreAwayMessage != true - val status = ClientStatus.of(c) - return ClientItem( - id = c.id, - uniqueId = c.uniqueId, - nickname = c.nickname ?: "", - name = contact?.displayName(c.nickname) ?: c.nickname ?: "", - awayMessage = if (away) c.awayMessage else "", - status = status, - background = rowColors.of(status), - self = c.self, - contactType = contact?.type, - highlight = if (colorContacts) contact?.type ?: ContactType.NEUTRAL else ContactType.NEUTRAL, - groupIconIds = (model.serverGroupsOf(c.serverGroupIds) + listOfNotNull(model.channelGroup(c.channelGroupId))) - .map { it.iconId }.filter { it != 0L }, - avatarFlag = c.avatarFlag.orEmpty(), - country = c.country.orEmpty(), - serverGroupIds = c.serverGroupIds.toList(), - channelGroupId = c.channelGroupId, - ) - } - } -} - -/** What the find bar looks for in the tree: clients, or with [channels] channels. */ -@Immutable -data class TreeFind(val query: TextQuery, val channels: Boolean) { - fun matches(c: ChannelItem) = channels && TreeMatch.channel(query, c.name) - fun matches(c: ClientItem) = !channels && TreeMatch.client(query, c.nickname, c.name) -} - -@Immutable -data class ChannelItem( - val id: Int, - val name: String, - /** Set for a spacer: a cosmetic separator rather than a channel to join. */ - val spacer: Spacers.Spacer?, - val locked: Boolean, - val full: Boolean, - val subscribed: Boolean, - /** 0 for none. */ - val iconId: Long, - val clients: List, - val children: List, -) - -@Immutable -data class ClientItem( - val id: Int, - val uniqueId: String, - val nickname: String, - /** The name shown: the contact's own name for them where there is one. */ - val name: String, - val awayMessage: String, - val status: ClientStatus, - /** The row's background colour, ARGB; 0 for none. */ - val background: Int, - val self: Boolean, - /** How the client is filed in the contacts; null when it is not one. */ - val contactType: ContactType?, - /** The contact colour the name is drawn in, NEUTRAL when contacts are not coloured. */ - val highlight: ContactType, - /** The icons of the client's server groups, then of its channel group, as TeamSpeak lines them up. */ - val groupIconIds: List, - /** The MD5 of the client's avatar; empty for none. */ - val avatarFlag: String, - /** The code of the country the server places the client in; empty when it cannot tell. */ - val country: String, - val serverGroupIds: List, - val channelGroupId: Int, -) diff --git a/android/app/src/main/java/com/ts3client/android/SessionController.kt b/android/app/src/main/java/com/ts3client/android/SessionController.kt deleted file mode 100644 index b4c13a1..0000000 --- a/android/app/src/main/java/com/ts3client/android/SessionController.kt +++ /dev/null @@ -1,657 +0,0 @@ -package com.ts3client.android - -import android.Manifest -import android.content.Context -import android.content.Intent -import android.content.pm.PackageManager -import android.net.Uri -import android.os.Handler -import android.os.Looper -import android.provider.OpenableColumns -import com.ts3client.android.audio.AndroidAudioBackend -import com.ts3client.android.audio.AudioRoute -import com.ts3client.audio.AudioDevice -import com.ts3client.config.BanReasonPresets -import com.ts3client.config.Bookmark -import com.ts3client.config.Bookmarks -import com.ts3client.config.IdentityStore -import com.ts3client.config.Settings -import com.ts3client.config.WhisperList -import com.ts3client.config.WhisperLists -import com.ts3client.contacts.Contact -import com.ts3client.contacts.ContactStore -import com.ts3client.myts.ChatAttachment -import com.ts3client.myts.ChatAttachments -import com.ts3client.myts.MyTeamSpeak -import com.ts3client.myts.MyTeamSpeakLogin -import com.ts3client.net.HostButton -import com.ts3client.net.TeamspeakConnection -import com.ts3client.session.SelfState -import com.ts3client.session.ServerLink -import com.ts3client.session.ServerSession -import com.ts3client.session.Sessions -import com.ts3client.sound.SoundNotifier -import com.ts3client.sound.SoundPack -import com.ts3client.teamspeak.SyncItem -import com.ts3client.teamspeak.TeamSpeakImporter -import com.ts3client.teamspeak.TeamSpeakSettingsDb -import com.ts3client.text.BBCode -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.flow.MutableSharedFlow -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.SharedFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.update -import kotlinx.coroutines.withContext -import java.io.File -import java.io.IOException -import java.io.InputStream -import java.util.concurrent.atomic.AtomicInteger - -/** What the app shows of a connection and the local client on it. */ -data class SessionState( - val title: String = "", - val status: String = "Not connected", - val connected: Boolean = false, - val busy: Boolean = false, - /** Whether this server holds the microphone, which only one server can at a time. */ - val micActive: Boolean = false, - val micPermission: Boolean = false, - val micMuted: Boolean = false, - val deafened: Boolean = false, - val away: Boolean = false, - val selfClientId: Int = 0, - val channelId: Int = 0, - val inputMode: Settings.InputMode = Settings.InputMode.VOICE_ACTIVATION, - val hostButton: HostButton? = null, - /** What the tree shows for the local client, and the connection notification too. */ - val self: SelfState = SelfState.DISCONNECTED, - /** Who the microphone whispers to instead of the channel; null when it talks in the channel. */ - val whisper: String? = null, - /** Whether none of the whisper's channels and clients are on the server, so nobody hears it. */ - val whisperNobody: Boolean = false, -) - -/** A file to share in chat, open for reading. */ -internal class SharedFile(val name: String, val size: Long, val data: InputStream) - -/** Something that happened once, for the UI to tell the user about. */ -sealed interface SessionEvent { - data class Poke(val from: String, val message: String) : SessionEvent - data class Error(val message: String) : SessionEvent - /** A link or shortcut brought a server on screen, in front of whatever page was open. */ - data object ServerOpened : SessionEvent -} - -/** - * The servers the app is on and what they share, outliving any activity: [ConnectionService] - * keeps the process in the foreground while any is connected. Only one server captures with - * the microphone at a time; [Sessions] hands it over. - */ -class SessionController(private val context: Context) { - - val settings: Settings = Settings.load() - val icons = IconTheme(context, settings) - private val shortcuts = BookmarkShortcuts(context, icons) - val pictures = WebPictures(context.cacheDir, settings) - internal val cacheDir: File get() = context.cacheDir - internal fun fileTransfers(conn: () -> TeamspeakConnection) = FileTransfers(context, conn) - private val bookmarkStore = Bookmarks.load() - internal val identityStore = IdentityStore.load(settings) - val identities = IdentityManager(context, identityStore, settings, bookmarkStore) { - _bookmarks.value = bookmarkStore.all().toList() - } - internal val audio = AndroidAudioBackend(context) - private val soundPlayer = SpeakingSoundPlayer(context, audio.createSoundPlayer(settings)) - internal val sounds = SoundNotifier(settings).also { it.setPlayer(soundPlayer) } - internal val notifier = MessageNotifier(context) - internal val contactStore = ContactStore.load() - /** The reasons offered when adding a ban; shared by every server. */ - val banReasons: BanReasonPresets by lazy { BanReasonPresets.load() } - internal val network = NetworkFollower(context) - - private val main = Handler(Looper.getMainLooper()) - private val nextId = AtomicInteger() - /** Touched on the main thread only, as [Sessions] wants. */ - private val sessions = Sessions { main.post(::microphoneMoved) } - - private val _servers = MutableStateFlow(emptyList()) - /** Every server the app is on or getting on, in the order they were connected. */ - val servers: StateFlow> = _servers - - private val _current = MutableStateFlow(null) - /** The server on screen; null when there is none. */ - val current: StateFlow = _current - - private val _micOwner = MutableStateFlow(null) - /** The server capturing with the microphone; null when none is. */ - val micOwner: StateFlow = _micOwner - - /** Why the last connection that ended did, for the connect form to show; null when it was left. */ - private val _lastEnd = MutableStateFlow(null) - val lastEnd: StateFlow = _lastEnd - - /** Copies of the contacts, as the store's own entries change in place. */ - private val _contacts = MutableStateFlow(contactCopies()) - val contacts: StateFlow> = _contacts - - private val _bookmarks = MutableStateFlow(bookmarkStore.all().toList()) - val bookmarks: StateFlow> = _bookmarks - - private val _events = MutableSharedFlow(extraBufferCapacity = 16) - val events: SharedFlow = _events - - private val _onScreen = MutableStateFlow(false) - val onScreen: StateFlow = _onScreen - - /** Whether the app is on screen; pokes and private messages are notified of while it is not. */ - var foreground: Boolean - get() = _onScreen.value - set(value) { - _onScreen.value = value - if (value) notifier.clearPokes() - // The process may be let go of any time once out of sight. - else contactStore.flush() - } - - private val levels = LevelMonitor(settings, audio) - val micLevel: StateFlow = levels.level - @Volatile - private var watchingLevel = false - - private val routePrefs = AudioRoutePrefs(context) - private val _route = MutableStateFlow(routePrefs.load()) - val route: StateFlow = _route - - private val _inputDevices = MutableStateFlow(audio.io().inputDevices()) - val inputDevices: StateFlow> = _inputDevices - private val _outputDevices = MutableStateFlow(audio.io().outputDevices()) - val outputDevices: StateFlow> = _outputDevices - - val unprocessedSupported: Boolean get() = audio.unprocessedSupported() - - init { - audio.setRoute(_route.value) - audio.addDeviceListener { - _inputDevices.value = audio.io().inputDevices() - _outputDevices.value = audio.io().outputDevices() - } - // Mutations report on whichever thread made them, a connection thread included. - contactStore.addListener { - _contacts.value = contactCopies() - _servers.value.forEach(ServerController::contactsChanged) - } - } - - /** The nickname a connect with [identityId] goes by: the identity's own, else the global one. */ - fun nicknameFor(identityId: String): String = identities.nicknameOf(identityId).ifBlank { settings.nickname } - val lastAddress: String get() = settings.lastAddress - - // ---- connection ---- - - /** Connects to `host[:port]`, as another server; an empty [identityId] means the default identity. */ - fun connect(address: String, nickname: String, password: String = "", identityId: String = "") { - val (host, port) = parseAddress(address) - settings.lastAddress = address - if (identities.nicknameOf(identityId).isBlank()) settings.nickname = nickname - settings.save() - start(host, port, nickname, password, identityId, "", "") - } - - fun connect(bookmark: Bookmark) { - start { it.start(bookmark.address, bookmark.port, bookmark.nickname.orEmpty(), bookmark.password, - bookmark.identityId, bookmark.channel, bookmark.channelPassword) } - } - - private fun start(host: String, port: Int, nickname: String, password: String, identityId: String, - channel: String, channelPassword: String) { - start { it.start(host, port, nickname, password, identityId, channel, channelPassword) } - } - - private fun start(connect: (ServerController) -> Unit) { - val server = ServerController(nextId.incrementAndGet(), this) - sessions.add(server.session) - _servers.update { it + server } - _current.value = server - _lastEnd.value = null - context.startForegroundService(Intent(context, ConnectionService::class.java)) - connect(server) - } - - /** - * Goes where a `ts3server://` link leads: on a server we are on already, to the channel it - * names; else connects there as another server. - */ - fun open(link: ServerLink, identityId: String = "") { - if (link.bookmarkLabel.isNotEmpty()) { - bookmarkStore.add(link.toBookmark()) - saveBookmarks() - } - val on = _servers.value.firstOrNull { it.session.isOn(link) } - if (on != null) { - _current.value = on - on.session.follow(link) - } else { - start { it.open(link, identityId) } - } - _events.tryEmit(SessionEvent.ServerOpened) - } - - /** What a home-screen shortcut does: connects to the bookmark, or goes to its channel when already on its server. */ - fun openBookmark(id: String): ServerLink? { - val bookmark = bookmarkStore.find(id) - if (bookmark == null) { - error("That bookmark no longer exists") - return null - } - return ServerLink.of(bookmark).also { open(it, bookmark.identityId) } - } - - private var startedUp = false - - /** Connects the bookmarks flagged for startup, once per process; [opened] is a server the launch already went to. */ - fun connectStartupBookmarks(opened: ServerLink?) { - if (startedUp) return - startedUp = true - for (b in bookmarkStore.startupBookmarks()) { - if (opened?.pointsAt(b.address, b.port) != true) start { it.open(ServerLink.of(b), b.identityId) } - } - } - - fun select(server: ServerController) { - if (server in _servers.value) _current.value = server - } - - /** Leaves every server before returning, for when the app goes away with the connections. */ - fun leave() { - val servers = _servers.value - servers.forEach(ServerController::leaving) - ServerSession.shutdownAll(servers.map { it.session }) - contactStore.flush() - attachments.close() - } - - fun server(id: Int): ServerController? = _servers.value.firstOrNull { it.id == id } - - /** A server's state changed; one that is done with goes from the list. */ - internal fun serverChanged(server: ServerController) { - if (server.micOwner) updateLevels() - if (server.ended) main.post { remove(server) } - } - - private fun remove(server: ServerController) { - if (server !in _servers.value || !server.ended) return - sessions.remove(server.session) - val rest = _servers.value - server - _servers.value = rest - if (_current.value == server) _current.value = rest.lastOrNull() - server.dispose() - val reason = server.state.value.status - _lastEnd.value = if (server.left) null else reason - if (!server.left && rest.isNotEmpty()) error("${server.state.value.title}: $reason") - } - - internal fun connected(server: ServerController) { - // The first connect generates an identity when there was none. - identities.refresh() - main.post { - // Without the permission yet, the UI hands the microphone over once it is granted. - if (hasMicPermission()) sessions.connected(server.session) - } - } - - internal fun disconnected(server: ServerController) { - main.post { sessions.disconnected(server.session) } - } - - internal fun error(message: String) { - _events.tryEmit(SessionEvent.Error(message)) - } - - internal fun poked(from: String, message: String) { - _events.tryEmit(SessionEvent.Poke(from, message)) - if (!foreground) notifier.poke(from, BBCode.toPlain(message)) - } - - internal fun talking(transmitting: Boolean) = levels.talking(transmitting) - - // ---- bookmarks ---- - - /** A bookmark to [address] as typed into the connect form, not yet saved. */ - fun newBookmark(address: String, nickname: String, password: String, identityId: String): Bookmark { - val (host, port) = parseAddress(address) - // Only a nickname other than the identity's is the server's own. - val own = nickname.takeIf { it != nicknameFor(identityId) }.orEmpty() - return Bookmark(host, host, port, own, password).also { it.identityId = identityId } - } - - /** Puts [edited] in place of the bookmark at [index], or adds it when [index] is -1. */ - fun saveBookmark(index: Int, edited: Bookmark) { - val all = bookmarkStore.all() - if (index !in all.indices) { - bookmarkStore.add(edited) - } else { - // The icon may have been learnt meanwhile, and belongs to the server, not to the bookmark. - edited.iconId = all[index].takeIf { it.pointsAt(edited.address, edited.port) }?.iconId ?: 0 - all[index] = edited - } - saveBookmarks() - } - - /** The channels of a server we are on at [host]:[port], to pick one to join. */ - fun channelPathsAt(host: String, port: Int): List = - _servers.value.firstOrNull { - it.isConnected && it.session.port() == port && it.session.address().equals(host.trim(), ignoreCase = true) - }?.session?.channelPaths().orEmpty() - - fun removeBookmark(bookmark: Bookmark) { - val index = bookmarkStore.all().indexOf(bookmark) - if (index < 0) return - bookmarkStore.remove(index) - saveBookmarks() - } - - /** Bookmarks leading to [address]:[port] take on the icon the server shows now. */ - internal fun serverIconChanged(address: String, port: Int, iconId: Long) { - main.post { - val all = bookmarkStore.all() - var changed = false - for (i in all.indices) { - val b = all[i] - if (!b.pointsAt(address, port) || b.iconId == iconId) continue - // A new entry, so the list the UI holds changes along with it. - all[i] = b.copy().also { it.iconId = iconId } - changed = true - } - if (changed) saveBookmarks() - } - } - - private fun saveBookmarks() { - bookmarkStore.save() - _bookmarks.value = bookmarkStore.all().toList() - shortcuts.sync(_bookmarks.value) - } - - val canPinShortcuts: Boolean get() = shortcuts.supported - - /** Asks the launcher for a home-screen shortcut connecting to [bookmark]. */ - fun pinShortcut(bookmark: Bookmark) { - // A bookmark not saved since ids came in has a new one on every load until it is. - bookmarkStore.save() - shortcuts.pin(bookmark) - } - - // ---- whisper lists ---- - - private val whisperListStore = WhisperLists.load() - private val _whisperLists = MutableStateFlow(whisperListCopies()) - val whisperLists: StateFlow> = _whisperLists - - private fun whisperListCopies() = whisperListStore.all().map { it.copy() } - - /** Puts [list] in place of the one at [index], or adds it when [index] is -1. */ - fun saveWhisperList(index: Int, list: WhisperList) { - val all = whisperListStore.all() - if (index in all.indices) all[index] = list.copy() else all.add(list.copy()) - whisperListStore.save() - _whisperLists.value = whisperListCopies() - } - - /** Adds a channel or a client to the list at [index], or to a new list named [newName] when [index] is -1. */ - fun addToWhisperList(index: Int, newName: String, add: (WhisperList) -> Unit) { - val list = whisperListStore.all().getOrNull(index)?.copy() ?: WhisperList(newName) - add(list) - saveWhisperList(index, list) - } - - fun removeWhisperList(index: Int) { - val all = whisperListStore.all() - if (index !in all.indices) return - all.removeAt(index) - whisperListStore.save() - _whisperLists.value = whisperListCopies() - } - - // ---- contacts ---- - - private fun contactCopies(): List = contactStore.all().map { it.copy() } - - /** A copy of the contact to edit and hand back to [saveContact]. */ - fun contact(uniqueId: String): Contact? = contactStore.find(uniqueId)?.copy() - - fun saveContact(contact: Contact) = contactStore.put(contact) - - fun removeContact(uniqueId: String) = contactStore.remove(uniqueId) - - /** - * Adds the contacts of a TeamSpeak 3 `settings.db`, overwriting entries for the same clients. - * - * @return how many contacts the file held and how many of them were new - */ - suspend fun importContacts(uri: Uri): Pair = withContext(Dispatchers.IO) { - val found = withLocalCopy(context, uri, TeamSpeakSettingsDb::readContacts) - found.size to if (found.isEmpty()) 0 else contactStore.merge(found) - } - - // ---- myTeamSpeak ---- - - /** The account the app stays signed in to; its reads block, so they run on [Dispatchers.IO]. */ - val myTeamSpeak: MyTeamSpeakLogin = MyTeamSpeakLogin.load() - private val importer = TeamSpeakImporter(identityStore, bookmarkStore, settings) - - private val _myTeamSpeakSignedIn = MutableStateFlow(myTeamSpeak.isSignedIn) - val myTeamSpeakSignedIn: StateFlow = _myTeamSpeakSignedIn - - /** Files shared in chat, kept in the myTeamSpeak account's cloud storage. */ - internal val attachments = ChatAttachments(myTeamSpeak).also { - pictures.addSource(ChatAttachment.SCHEME, it::fetchPicture) - } - - suspend fun signInMyTeamSpeak(email: String, password: String): MyTeamSpeak.Account = - withContext(Dispatchers.IO) { myTeamSpeak.signIn(email, password) } - .also { - _myTeamSpeakSignedIn.value = true - // Shared pictures that could not be had signed out. - pictures.retryFailed() - } - - suspend fun fetchMyTeamSpeak(): MyTeamSpeak.Account = - try { - withContext(Dispatchers.IO) { myTeamSpeak.fetch() } - } finally { - // A sign-in the server no longer takes has signed out. - _myTeamSpeakSignedIn.value = myTeamSpeak.isSignedIn - } - - suspend fun signOutMyTeamSpeak() { - myTeamSpeak.signOut() - _myTeamSpeakSignedIn.value = false - withContext(Dispatchers.IO) { attachments.close() } - } - - /** Fetches a file shared in chat whole. */ - suspend fun downloadAttachment(ref: ChatAttachment.Ref): ByteArray = - withContext(Dispatchers.IO) { attachments.download(ref, ChatAttachments.MAX_UPLOAD_BYTES) } - - /** Fetches a file shared in chat into [uri], e.g. one the user picked to save it as. */ - suspend fun saveAttachment(ref: ChatAttachment.Ref, uri: Uri) { - val data = downloadAttachment(ref) - withContext(Dispatchers.IO) { - val out = context.contentResolver.openOutputStream(uri) ?: throw IOException("Could not write the file") - out.use { it.write(data) } - } - } - - /** A file picked to share in chat, or why it cannot be. */ - internal suspend fun openShared(uri: Uri): Result = withContext(Dispatchers.IO) { - runCatching { - val resolver = context.contentResolver - val (name, size) = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), - null, null, null)?.use { c -> - if (!c.moveToFirst()) null - else c.getString(0).orEmpty() to (if (c.isNull(1)) -1L else c.getLong(1)) - } ?: ("" to -1L) - when { - size < 0 -> throw IOException("Could not read the file's size") - size > ChatAttachments.MAX_UPLOAD_BYTES -> - throw IOException("Files over ${ChatAttachments.MAX_UPLOAD_BYTES shr 20} MB cannot be shared") - } - val data = resolver.openInputStream(uri) ?: throw IOException("Could not read the file") - SharedFile(name.ifBlank { uri.lastPathSegment ?: "file" }, size, data) - } - } - - fun isImported(item: SyncItem): Boolean = importer.isPresent(item) - - /** Imports [chosen] out of the account's [all] items, with the identities the chosen bookmarks use. */ - suspend fun importMyTeamSpeak(all: List, chosen: List): TeamSpeakImporter.Result = - withContext(Dispatchers.IO) { importer.importSelected(all, chosen) } - .also { - _bookmarks.value = bookmarkStore.all().toList() - identities.refresh() - } - - // ---- sound packs ---- - - private val _soundPacks = MutableStateFlow(sounds.availablePacks()) - val soundPacks: StateFlow> = _soundPacks - - val soundPack: SoundPack? get() = sounds.pack() - - fun setCountryFlags(shown: Boolean) { - settings.countryFlags = shown - settings.save() - servers.value.forEach { it.scheduleTree(structure = false) } - } - - /** Puts new client row colours, already set in [settings], into effect. */ - fun clientRowColorsChanged() { - settings.save() - servers.value.forEach { it.scheduleTree(structure = false) } - } - - fun setDescriptionPictures(shown: Boolean) { - settings.descriptionPictures = shown - settings.save() - } - - fun setSoundPack(pack: SoundPack) { - sounds.setPack(pack) - settings.save() - } - - /** Unpacks the packs the app ships with, when this version has not yet. */ - fun installSoundPacks() { - if (!SoundPackInstaller(context).install()) return - sounds.reload() - _soundPacks.value = sounds.availablePacks() - } - - // ---- the local client ---- - - fun hasMicPermission() = - context.checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED - - /** Moves the microphone to [server]; needs RECORD_AUDIO granted. */ - fun giveMicrophoneTo(server: ServerController) { - if (server.isConnected) sessions.giveMicrophoneTo(server.session) - } - - /** Opens the microphone of the server holding it while push-to-talk is held. */ - fun setPushToTalk(pressed: Boolean) = sessions.setPushToTalk(pressed) - - /** Transmits on the server holding the microphone while held, past the voice-activation gate too. */ - fun setForceTransmit(pressed: Boolean) = sessions.setForceTransmit(pressed) - - private fun microphoneMoved() { - val owner = sessions.microphoneOwner() - for (server in _servers.value) { - server.micOwner = server.session == owner - server.refresh() - } - _micOwner.value = _servers.value.firstOrNull { it.micOwner } - updateLevels() - } - - private val overlayPrefs = context.getSharedPreferences("overlay", Context.MODE_PRIVATE) - private val _pttOverlay = MutableStateFlow(overlayPrefs.getBoolean(OVERLAY_ENABLED, false)) - /** Whether push to talk floats a button over other apps while this one is off screen. */ - val pttOverlay: StateFlow = _pttOverlay - - fun setPttOverlay(enabled: Boolean) { - overlayPrefs.edit().putBoolean(OVERLAY_ENABLED, enabled).apply() - _pttOverlay.value = enabled - } - - /** Switches between push to talk and voice activation; returns the new mode. */ - fun toggleInputMode(): Settings.InputMode { - settings.inputMode = if (settings.inputMode == Settings.InputMode.PUSH_TO_TALK) - Settings.InputMode.VOICE_ACTIVATION else Settings.InputMode.PUSH_TO_TALK - applySettings() - return settings.inputMode - } - - /** Saves the settings and puts the voice and device ones into effect at once. */ - fun applySettings() { - settings.save() - soundPlayer.setOutputDevice(settings.outputDevice) - try { - for (server in _servers.value) { - server.playback?.setMasterVolume(settings.outputVolume) - server.playback?.setOutputDevice(settings.outputDevice) - server.playback?.setReceiveBuffer(settings.receiveBuffer) - server.microphone?.apply(settings) - server.refresh() - server.scheduleTree(structure = false) - } - levels.apply() - } catch (e: RuntimeException) { - error(e.message ?: "Microphone unavailable") - } - } - - /** Microphone preset and playback usage; the open lines move over at once. */ - fun setRoute(route: AudioRoute) { - routePrefs.save(route) - _route.value = route - audio.setRoute(route) - } - - /** Listens to the microphone for the level meter while [on]. */ - fun watchLevel(on: Boolean) { - watchingLevel = on - updateLevels() - } - - private fun updateLevels() { - val owner = _micOwner.value - levels.update(watchingLevel, owner?.microphone, owner?.isBusy == true, hasMicPermission()) - } - - // ---- notifications ---- - - /** Shows a private chat a notification was tapped for. */ - fun requestChat(serverId: Int, clientId: Int) { - val server = server(serverId) ?: return - _current.value = server - server.requestChat(clientId) - } - - /** Answers a private message from its notification. */ - fun reply(serverId: Int, clientId: Int, text: String) { - server(serverId)?.reply(clientId, text) ?: notifier.clear(serverId, clientId) - } - - companion object { - const val DEFAULT_PORT = 9987 - private const val OVERLAY_ENABLED = "enabled" - - /** `host[:port]` as typed, the port defaulting to TeamSpeak's. */ - fun parseAddress(address: String): Pair { - val host = address.substringBefore(':').trim() - val port = address.substringAfter(':', "").trim().toIntOrNull() ?: DEFAULT_PORT - return host to port - } - } -} diff --git a/android/app/src/main/java/com/ts3client/android/SoundPackInstaller.kt b/android/app/src/main/java/com/ts3client/android/SoundPackInstaller.kt deleted file mode 100644 index 1895665..0000000 --- a/android/app/src/main/java/com/ts3client/android/SoundPackInstaller.kt +++ /dev/null @@ -1,53 +0,0 @@ -package com.ts3client.android - -import android.content.Context -import android.content.res.AssetManager -import com.ts3client.config.AppDirs -import java.io.File - -/** - * Unpacks the sound packs bundled in the APK into the profile's `sound` folder, where - * [com.ts3client.sound.SoundNotifier] finds packs, as they are read as plain files. - * It happens once per installed version of the app; packs of other origins in the - * folder are left alone. - */ -class SoundPackInstaller(private val context: Context) { - - private val root = File(AppDirs.profile(), ASSET_DIR) - private val marker = File(root, ".bundled") - /** Where a pack is unpacked first, outside [root] so it is never seen half written. */ - private val staging = File(AppDirs.profile(), ".sound-staging") - - /** @return whether the packs were (re)installed, so the list of them has to be read again */ - fun install(): Boolean { - val version = context.packageManager.getPackageInfo(context.packageName, 0).lastUpdateTime.toString() - if (marker.isFile && marker.readText() == version) return false - val assets = context.assets - for (pack in assets.list(ASSET_DIR).orEmpty()) { - staging.deleteRecursively() - copy(assets, "$ASSET_DIR/$pack", staging) - val target = File(root, pack) - target.deleteRecursively() - root.mkdirs() - check(staging.renameTo(target)) { "Cannot install sound pack $pack" } - } - root.mkdirs() - marker.writeText(version) - return true - } - - private fun copy(assets: AssetManager, path: String, to: File) { - val children = assets.list(path).orEmpty() - if (children.isEmpty()) { - to.parentFile?.mkdirs() - assets.open(path).use { input -> to.outputStream().use { input.copyTo(it) } } - return - } - to.mkdirs() - for (child in children) copy(assets, "$path/$child", File(to, child)) - } - - private companion object { - const val ASSET_DIR = "sound" - } -} diff --git a/android/app/src/main/java/com/ts3client/android/SpeakingSoundPlayer.kt b/android/app/src/main/java/com/ts3client/android/SpeakingSoundPlayer.kt deleted file mode 100644 index 734358c..0000000 --- a/android/app/src/main/java/com/ts3client/android/SpeakingSoundPlayer.kt +++ /dev/null @@ -1,31 +0,0 @@ -package com.ts3client.android - -import android.content.Context -import android.os.Bundle -import android.speech.tts.TextToSpeech -import com.ts3client.sound.SoundPlayer - -/** - * Adds the phone's text-to-speech to a wave player, for packs that speak their - * notifications. Sentences asked for before the engine is up are dropped: they - * would come out late, past what they announce. - */ -class SpeakingSoundPlayer(context: Context, private val waves: SoundPlayer) : SoundPlayer by waves { - - @Volatile - private var ready = false - private val tts = TextToSpeech(context.applicationContext) { status -> ready = status == TextToSpeech.SUCCESS } - - override fun canSpeak() = true - - override fun say(text: String, volume: Double) { - if (!ready) return - val params = Bundle().apply { putFloat(TextToSpeech.Engine.KEY_PARAM_VOLUME, volume.toFloat()) } - tts.speak(text, TextToSpeech.QUEUE_ADD, params, null) - } - - override fun shutdown() { - tts.shutdown() - waves.shutdown() - } -} diff --git a/android/app/src/main/java/com/ts3client/android/Ts3Application.kt b/android/app/src/main/java/com/ts3client/android/Ts3Application.kt deleted file mode 100644 index a3f2ab3..0000000 --- a/android/app/src/main/java/com/ts3client/android/Ts3Application.kt +++ /dev/null @@ -1,18 +0,0 @@ -package com.ts3client.android - -import android.app.Application -import com.ts3client.config.AppDirs - -class Ts3Application : Application() { - - lateinit var sessions: SessionController - private set - - override fun onCreate() { - super.onCreate() - // Before any store loads: there is no home directory to find them in. - AppDirs.init(filesDir, filesDir.toPath().resolve("chats")) - sessions = SessionController(this) - Thread(sessions::installSoundPacks, "sound-packs").start() - } -} diff --git a/android/app/src/main/java/com/ts3client/android/WebPictures.kt b/android/app/src/main/java/com/ts3client/android/WebPictures.kt deleted file mode 100644 index f122248..0000000 --- a/android/app/src/main/java/com/ts3client/android/WebPictures.kt +++ /dev/null @@ -1,64 +0,0 @@ -package com.ts3client.android - -import android.util.LruCache -import com.ts3client.config.Settings -import com.ts3client.net.PictureDownloads -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.update -import kotlinx.coroutines.withContext -import java.io.File -import java.util.concurrent.ConcurrentHashMap - -/** The pictures descriptions show, fetched by core's downloads and decoded while there is room. */ -class WebPictures(cacheDir: File, private val settings: Settings) { - - sealed interface State { - data object Loading : State - data object Broken : State - data class Shown(val picture: Picture) : State - } - - private val downloads = PictureDownloads(File(cacheDir, "pictures"), false) - private val decoded = LruCache(CACHED) - private val undecodable = ConcurrentHashMap.newKeySet() - - private val _version = MutableStateFlow(0) - /** Moves on whenever a download has come or failed. */ - val version: StateFlow = _version - - init { - downloads.addListener { _version.update { it + 1 } } - } - - /** Fetches pictures whose addresses start with [scheme] from [source] rather than the web. */ - fun addSource(scheme: String, source: PictureDownloads.Source) = downloads.addSource(scheme, source) - - /** Asks again for the pictures that could not be had. */ - fun retryFailed() = downloads.retryFailed() - - /** Whether pictures are shown at all, rather than links to them. */ - val enabled: Boolean get() = settings.descriptionPictures - - suspend fun state(url: String): State { - decoded.get(url)?.let { return State.Shown(it) } - if (url in undecodable) return State.Broken - val file = downloads.get(url) ?: return if (downloads.failed(url)) State.Broken else State.Loading - val picture = withContext(Dispatchers.IO) { decodePicture(file.readBytes(), MAX_PX) } - if (picture == null) { - undecodable += url - return State.Broken - } - decoded.put(url, picture) - return State.Shown(picture) - } - - /** The picture's file as downloaded; null while it is not there. */ - suspend fun data(url: String): ByteArray? = withContext(Dispatchers.IO) { downloads.get(url)?.readBytes() } - - private companion object { - const val CACHED = 32 - const val MAX_PX = 1024 - } -} diff --git a/android/app/src/main/java/com/ts3client/android/ui/App.kt b/android/app/src/main/java/com/ts3client/android/ui/App.kt deleted file mode 100644 index c70f2ad..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/App.kt +++ /dev/null @@ -1,115 +0,0 @@ -package com.ts3client.android.ui - -import android.Manifest -import android.content.pm.PackageManager -import androidx.activity.compose.rememberLauncherForActivityResult -import androidx.activity.result.contract.ActivityResultContracts -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.SnackbarHostState -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.CompositionLocalProvider -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.saveable.rememberSaveableStateHolder -import androidx.compose.runtime.setValue -import androidx.compose.ui.platform.LocalContext -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import com.ts3client.android.SessionController -import com.ts3client.android.SessionEvent - -@Composable -fun App(vm: SessionController) { - val current by vm.current.collectAsStateWithLifecycle() - // Each server keeps its own screen state (chat open, conversation) while another is shown. - val serverStates = rememberSaveableStateHolder() - var connectOpen by rememberSaveable { mutableStateOf(false) } - val snackbar = remember { SnackbarHostState() } - var settingsOpen by rememberSaveable { mutableStateOf(false) } - var contactsOpen by rememberSaveable { mutableStateOf(false) } - var editingContact by rememberSaveable { mutableStateOf(null) } - // Set when a contact's page was opened from a client, so leaving it goes back there. - var contactDirect by rememberSaveable { mutableStateOf(false) } - var editingBookmark by rememberSaveable(stateSaver = BookmarkEditSaver) { mutableStateOf(null) } - var poke by remember { mutableStateOf(null) } - - LaunchedEffect(vm) { - vm.events.collect { event -> - when (event) { - is SessionEvent.Poke -> poke = event - is SessionEvent.Error -> snackbar.showSnackbar(event.message) - SessionEvent.ServerOpened -> { - connectOpen = false - settingsOpen = false - contactsOpen = false - editingBookmark = null - } - } - } - } - - val context = LocalContext.current - val permissions = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { granted -> - if (granted[Manifest.permission.RECORD_AUDIO] == true) vm.current.value?.let(vm::giveMicrophoneTo) - } - fun missing(vararg names: String) = - names.filter { context.checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED } - - // The connection runs without either permission, just silent or without its notification. - val connectAsking: (() -> Unit) -> Unit = { connect -> - connect() - connectOpen = false - val ask = missing(Manifest.permission.RECORD_AUDIO, Manifest.permission.POST_NOTIFICATIONS) - if (ask.isNotEmpty()) permissions.launch(ask.toTypedArray()) - } - val enableMicrophone: () -> Unit = { - if (missing(Manifest.permission.RECORD_AUDIO).isEmpty()) vm.current.value?.let(vm::giveMicrophoneTo) - else permissions.launch(arrayOf(Manifest.permission.RECORD_AUDIO)) - } - - val openContacts: (String?) -> Unit = { uniqueId -> - contactsOpen = true - editingContact = uniqueId - contactDirect = uniqueId != null - } - - CompositionLocalProvider(LocalIconTheme provides vm.icons, LocalWebPictures provides vm.pictures) { - val server = current - val bookmark = editingBookmark - when { - bookmark != null -> BookmarkScreen(vm, bookmark, onDone = { editingBookmark = null }) - contactsOpen -> ContactsScreen(vm, editingContact, onEdit = { uniqueId -> - if (uniqueId == null && contactDirect) contactsOpen = false - contactDirect = false - editingContact = uniqueId - }, onBack = { contactsOpen = false }) - settingsOpen -> SettingsScreen(vm, onContacts = { openContacts(null) }, onBack = { settingsOpen = false }) - server != null && !connectOpen -> { - serverStates.SaveableStateProvider(server.id) { - CompositionLocalProvider(LocalServerImages provides server.images) { - PictureViewerHost(server) { - ServerScreen(vm, server, snackbar, { settingsOpen = true }, openContacts, enableMicrophone, - onConnectOther = { connectOpen = true }, onEditBookmark = { editingBookmark = it }) - } - } - } - } - else -> ConnectScreen(vm, snackbar, { settingsOpen = true }, connectAsking, - onEditBookmark = { editingBookmark = it }, - onBack = if (current != null) ({ connectOpen = false }) else null) - } - } - - poke?.let { p -> - AlertDialog( - onDismissRequest = { poke = null }, - title = { Text("${p.from} poked you") }, - text = if (p.message.isNotBlank()) ({ Text(p.message) }) else null, - confirmButton = { TextButton(onClick = { poke = null }) { Text("OK") } }, - ) - } -} diff --git a/android/app/src/main/java/com/ts3client/android/ui/Attachments.kt b/android/app/src/main/java/com/ts3client/android/ui/Attachments.kt deleted file mode 100644 index 48616a1..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/Attachments.kt +++ /dev/null @@ -1,102 +0,0 @@ -package com.ts3client.android.ui - -import android.app.Activity -import android.content.Context -import android.content.Intent -import android.net.Uri -import android.webkit.MimeTypeMap -import androidx.activity.compose.rememberLauncherForActivityResult -import androidx.activity.result.contract.ActivityResultContract -import androidx.activity.result.contract.ActivityResultContracts -import androidx.compose.material3.SnackbarHostState -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.rememberUpdatedState -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import com.ts3client.android.ChatKey -import com.ts3client.android.ServerController -import com.ts3client.android.SessionController -import com.ts3client.myts.ChatAttachment -import com.ts3client.myts.MyTsException -import kotlinx.coroutines.launch -import java.io.IOException - -/** What the chat does with shared files: [open] one it links to, [share] one into a conversation. */ -class AttachmentActions(val open: (String) -> Unit, val share: () -> Unit) - -/** - * Shared files for [server]'s chat: a picture opens full size, anything else is saved where - * the user picks; sharing picks a file to send into the conversation [shown] gives. - */ -@Composable -fun rememberAttachmentActions( - vm: SessionController, - server: ServerController, - snackbar: SnackbarHostState, - shown: ChatKey, -): AttachmentActions { - val scope = rememberCoroutineScope() - val signedIn by vm.myTeamSpeakSignedIn.collectAsStateWithLifecycle() - val key by rememberUpdatedState(shown) - val viewer = LocalPictureViewer.current - val tell = { message: String -> scope.launch { snackbar.showSnackbar(message) }; Unit } - - var saving by rememberSaveable { mutableStateOf(null) } - val saver = rememberLauncherForActivityResult(SaveAs) { uri -> - val ref = ChatAttachment.Ref.parse(saving) - saving = null - if (uri == null || ref == null) return@rememberLauncherForActivityResult - scope.launch { - val error = try { - vm.saveAttachment(ref, uri) - null - } catch (e: MyTsException) { - e.message - } catch (e: IOException) { - e.message - } - snackbar.showSnackbar(if (error == null) "Saved ${ref.fileName}." else "Could not save ${ref.fileName}: $error") - } - } - val picker = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri -> - if (uri != null) scope.launch { server.sendFile(key, uri) } - } - - return AttachmentActions( - open = open@{ href -> - val ref = ChatAttachment.Ref.parse(href) ?: return@open - when { - !signedIn -> tell(SIGN_IN) - ref.isImage() && viewer != null -> viewer(ViewedPicture(ref.fileName.substringBeforeLast('.')) { - vm.pictures.data(href) ?: runCatching { vm.downloadAttachment(ref) }.getOrNull() - }) - else -> { - saving = href - saver.launch(ref.fileName) - } - } - }, - share = { if (signedIn) picker.launch("*/*") else tell(SIGN_IN) }, - ) -} - -private const val SIGN_IN = "Sign in to myTeamSpeak to share files" - -/** Asks where to save a file of the given name, typed by its extension. */ -internal object SaveAs : ActivityResultContract() { - override fun createIntent(context: Context, input: String): Intent { - val extension = input.substringAfterLast('.', "").lowercase() - val type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) ?: "application/octet-stream" - return Intent(Intent.ACTION_CREATE_DOCUMENT) - .addCategory(Intent.CATEGORY_OPENABLE) - .setType(type) - .putExtra(Intent.EXTRA_TITLE, input) - } - - override fun parseResult(resultCode: Int, intent: Intent?): Uri? = - intent?.data.takeIf { resultCode == Activity.RESULT_OK } -} diff --git a/android/app/src/main/java/com/ts3client/android/ui/BanListScreen.kt b/android/app/src/main/java/com/ts3client/android/ui/BanListScreen.kt deleted file mode 100644 index 7e3763b..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/BanListScreen.kt +++ /dev/null @@ -1,313 +0,0 @@ -package com.ts3client.android.ui - -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.layout.navigationBarsPadding -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.ArrowDropDown -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.DropdownMenu -import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.FilterChip -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.ModalBottomSheet -import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.SnackbarHostState -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import com.ts3client.android.ServerController -import com.ts3client.config.BanReasonPresets -import com.ts3client.net.ban.BanEntry -import com.ts3client.net.ban.BanPattern -import com.ts3client.net.ban.BanRule -import kotlinx.coroutines.launch -import java.time.Instant -import java.time.ZoneId -import java.time.format.DateTimeFormatter -import java.time.format.FormatStyle -import java.util.Locale - -/** What the ban list shows instead of itself: a ban's editor, a new or an existing ban's. */ -private sealed interface BanEdit { - data object New : BanEdit - data class Existing(val ban: BanEntry) : BanEdit -} - -/** The server's ban list, as TeamSpeak's Ban List window: searchable, own bans apart, add, edit and remove. */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun BanListScreen(server: ServerController, presets: BanReasonPresets, onBack: () -> Unit) { - val scope = rememberCoroutineScope() - val snackbar = remember { SnackbarHostState() } - var bans by remember { mutableStateOf?>(null) } - var status by remember { mutableStateOf("Loading…") } - /** Bumped to read the list again. */ - var generation by remember { mutableIntStateOf(0) } - var query by rememberSaveable { mutableStateOf("") } - var onlyOwn by rememberSaveable { mutableStateOf(false) } - var shown by remember { mutableStateOf(null) } - var edit by remember { mutableStateOf(null) } - - LaunchedEffect(generation) { - status = "Loading…" - server.banList() - .onSuccess { - bans = it - status = if (it.size == 1) "1 ban" else "${it.size} bans" - } - .onFailure { - bans = emptyList() - status = "Failed to request ban list: ${it.message}" - } - } - - /** Reports a failed change, or re-reads the list to show what the server now holds. */ - val change = { action: suspend () -> String?, failure: String -> - scope.launch { - val error = action() - if (error != null) snackbar.showSnackbar("$failure: $error") - generation++ - } - Unit - } - - edit?.let { e -> - val existing = (e as? BanEdit.Existing)?.ban - BanEditor(existing, presets, server.maxBanSeconds, onBack = { edit = null }) { rule -> - edit = null - if (existing == null) change({ server.addBan(rule) }, "Error adding ban") - else change({ server.replaceBan(existing.id, rule) }, "Error editing ban") - } - return - } - - SubScreen( - "Ban list", onBack, - actions = { - if (server.canCreateBans) IconButton(onClick = { edit = BanEdit.New }) { PackIcon("ADD", "Add") } - IconButton(onClick = { generation++ }) { PackIcon("REFRESH", "Reload") } - }, - snackbar = snackbar, - ) { padding -> - val needle = query.trim().lowercase(Locale.ROOT) - val filtered = remember(bans, needle, onlyOwn) { - bans.orEmpty().filter { ban -> - (!onlyOwn || server.isOwnBan(ban)) && (needle.isEmpty() || searchText(ban).contains(needle)) - } - } - Column(Modifier.padding(padding).imePadding().fillMaxSize()) { - Row(Modifier.padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp)) { - OutlinedTextField(query, { query = it }, Modifier.weight(1f), placeholder = { Text("Search") }, - singleLine = true, leadingIcon = { PackIcon("SEARCH", null) }) - FilterChip(onlyOwn, { onlyOwn = !onlyOwn }, label = { Text("Own") }) - } - Text(status, Modifier.padding(horizontal = 16.dp, vertical = 8.dp), - style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - LazyColumn(Modifier.weight(1f)) { - items(filtered, key = { it.id }) { ban -> - ListItem( - headlineContent = { Text(ban.targets(), maxLines = 2, overflow = TextOverflow.Ellipsis) }, - supportingContent = { - Column { - if (ban.reason.isNotEmpty()) Text(ban.reason, maxLines = 1, overflow = TextOverflow.Ellipsis) - Text("${ban.invokerName} · ${expiry(ban)}", style = MaterialTheme.typography.bodySmall) - } - }, - modifier = Modifier.clickable { shown = ban }, - ) - HorizontalDivider() - } - } - } - } - - shown?.let { ban -> - BanSheet( - ban, - onDismiss = { shown = null }, - onEdit = if (server.canEditBan(ban)) ({ shown = null; edit = BanEdit.Existing(ban) }) else null, - onDelete = if (server.canDeleteBans(listOf(ban))) ({ - shown = null - change({ server.deleteBans(listOf(ban.id)) }, "Error deleting ban") - }) else null, - ) - } -} - -private fun searchText(ban: BanEntry): String = - listOf(ban.targets(), ban.reason, ban.invokerName, date(ban.createdEpochSeconds), expiry(ban)) - .joinToString("\n").lowercase(Locale.ROOT) - -private val DATE: DateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) - -private fun date(epochSeconds: Long): String = - if (epochSeconds <= 0) "" else DATE.format(Instant.ofEpochSecond(epochSeconds).atZone(ZoneId.systemDefault())) - -private fun expiry(ban: BanEntry): String = if (ban.isPermanent) "Never expires" else "Expires ${date(ban.expiresEpochSeconds())}" - -/** Everything about one ban, and what may be done with it. */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -private fun BanSheet(ban: BanEntry, onDismiss: () -> Unit, onEdit: (() -> Unit)?, onDelete: (() -> Unit)?) { - var confirmDelete by remember { mutableStateOf(false) } - ModalBottomSheet(onDismissRequest = onDismiss) { - Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) { - Column(Modifier.padding(horizontal = 24.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { - Fact("Name", ban.name) - Fact("IP", ban.ip) - Fact("Unique ID", ban.uid) - Fact("Last nickname", ban.lastNickname) - Fact("myTeamSpeak ID", ban.mytsid) - Fact("Reason", ban.reason) - Fact("Creator", ban.invokerName) - Fact("Created", date(ban.createdEpochSeconds)) - Fact("Expires", if (ban.isPermanent) "Never" else date(ban.expiresEpochSeconds())) - Fact("Enforced", ban.enforcements.toString()) - } - onEdit?.let { Action("EDIT", "Edit", onClick = it) } - onDelete?.let { Action("DELETE", "Delete") { confirmDelete = true } } - } - } - if (confirmDelete && onDelete != null) { - AlertDialog( - onDismissRequest = { confirmDelete = false }, - title = { Text("Delete ban?") }, - text = { Text(ban.targets()) }, - confirmButton = { TextButton(onClick = { confirmDelete = false; onDelete() }) { Text("Delete") } }, - dismissButton = { TextButton(onClick = { confirmDelete = false }) { Text("Cancel") } }, - ) - } -} - -@Composable -private fun Fact(label: String, value: String) { - if (value.isEmpty()) return - Column { - Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) - Text(value, style = MaterialTheme.typography.bodyMedium) - } -} - -/** Adds a ban, or rewrites [existing]: what it matches, why, and for how long. */ -@Composable -private fun BanEditor( - existing: BanEntry?, - presets: BanReasonPresets, - maxSeconds: Long, - onBack: () -> Unit, - onSave: (BanRule) -> Unit, -) { - val decoded = remember { BanPattern.decode(existing?.ip, existing?.name) } - var ip by remember { mutableStateOf(decoded.ip) } - var name by remember { mutableStateOf(decoded.name) } - var pattern by remember { mutableStateOf(if (existing == null) BanPattern.WILDCARD_IPV4 else decoded.pattern) } - var uid by remember { mutableStateOf(existing?.uid.orEmpty()) } - var mytsid by remember { mutableStateOf(existing?.mytsid.orEmpty()) } - var reason by remember { mutableStateOf(existing?.reason.orEmpty()) } - val duration = remember { BanDurationState(existing?.durationSeconds ?: DEFAULT_BAN_SECONDS) } - - val rule = BanRule(pattern.ipToRegex(ip), pattern.nameToRegex(name), uid, mytsid, duration.seconds, reason) - val ipValid = BanPattern.isValidRegex(rule.ipRegex) - val nameValid = BanPattern.isValidRegex(rule.nameRegex) - val valid = rule.hasTarget() && ipValid && nameValid && duration.valid - - SubScreen( - if (existing == null) "Add ban" else "Edit ban", onBack, - actions = { TextButton(onClick = { onSave(rule) }, enabled = valid) { Text("Save") } }, - ) { padding -> - Column( - Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - OutlinedTextField(ip, { ip = it }, Modifier.fillMaxWidth(), label = { Text("IP") }, singleLine = true, - isError = !ipValid) - OutlinedTextField(name, { name = it }, Modifier.fillMaxWidth(), label = { Text("Name") }, singleLine = true, - isError = !nameValid) - PatternField(pattern) { pattern = it } - OutlinedTextField(uid, { uid = it }, Modifier.fillMaxWidth(), label = { Text("Unique ID") }, singleLine = true) - OutlinedTextField(mytsid, { mytsid = it }, Modifier.fillMaxWidth(), label = { Text("myTeamSpeak ID") }, - singleLine = true) - ReasonField(reason, { reason = it }, presets) - BanDurationField(duration, maxSeconds) - } - } -} - -/** How the IP and name are written: wildcards, fixed strings or regular expressions. */ -@Composable -private fun PatternField(pattern: BanPattern, onSelect: (BanPattern) -> Unit) { - var open by remember { mutableStateOf(false) } - Row(verticalAlignment = Alignment.CenterVertically) { - Text("Interpret as", Modifier.weight(1f)) - Box { - OutlinedButton(onClick = { open = true }) { Text(pattern.label()) } - DropdownMenu(open, { open = false }) { - for (p in BanPattern.entries) DropdownMenuItem({ Text(p.label()) }, onClick = { open = false; onSelect(p) }) - } - } - } -} - -/** The reason, with the saved presets to pick from and the reason typed to save as one. */ -@Composable -private fun ReasonField(reason: String, onChange: (String) -> Unit, presets: BanReasonPresets) { - var open by remember { mutableStateOf(false) } - var saved by remember { mutableStateOf(presets.all().toList()) } - Box { - Row(verticalAlignment = Alignment.Top) { - LimitedField(reason, onChange, "Reason", BanRule.REASON_LIMIT, Modifier.weight(1f)) - IconButton(onClick = { open = true }, Modifier.padding(top = 8.dp)) { Icon(Icons.Filled.ArrowDropDown, "Presets") } - } - DropdownMenu(open, { open = false }, Modifier.align(Alignment.TopEnd)) { - for (preset in saved) { - DropdownMenuItem({ Text(preset, maxLines = 1, overflow = TextOverflow.Ellipsis) }, - onClick = { open = false; onChange(preset.take(BanRule.REASON_LIMIT)) }, - trailingIcon = { - IconButton(onClick = { - presets.remove(preset) - presets.save() - saved = presets.all().toList() - }) { PackIcon("DELETE", "Remove preset") } - }) - } - if (saved.isNotEmpty()) HorizontalDivider() - DropdownMenuItem({ Text("Save as preset") }, enabled = reason.isNotBlank(), onClick = { - open = false - presets.add(reason) - presets.save() - saved = presets.all().toList() - }) - } - } -} diff --git a/android/app/src/main/java/com/ts3client/android/ui/BookmarkScreen.kt b/android/app/src/main/java/com/ts3client/android/ui/BookmarkScreen.kt deleted file mode 100644 index f49ad56..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/BookmarkScreen.kt +++ /dev/null @@ -1,152 +0,0 @@ -package com.ts3client.android.ui - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.ExposedDropdownMenuAnchorType -import androidx.compose.material3.ExposedDropdownMenuBox -import androidx.compose.material3.ExposedDropdownMenuDefaults -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Switch -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.listSaver -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.input.KeyboardType -import androidx.compose.ui.text.input.PasswordVisualTransformation -import androidx.compose.ui.unit.dp -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import com.ts3client.android.SessionController -import com.ts3client.config.Bookmark - -/** A bookmark on the edit page: [index] among the saved ones, -1 for a new one. */ -class BookmarkEdit(val index: Int, val bookmark: Bookmark) - -val BookmarkEditSaver = listSaver( - save = { edit -> - val b = edit?.bookmark ?: return@listSaver emptyList() - listOf(edit.index, b.label.orEmpty(), b.address.orEmpty(), b.port, b.nickname.orEmpty(), b.password, - b.identityId, b.channel, b.channelPassword, b.connectOnStartup, b.iconId, b.id) - }, - restore = { saved -> - if (saved.isEmpty()) null - else BookmarkEdit(saved[0] as Int, Bookmark(saved[1] as String, saved[2] as String, saved[3] as Int, - saved[4] as String, saved[5] as String).apply { - identityId = saved[6] as String - channel = saved[7] as String - channelPassword = saved[8] as String - connectOnStartup = saved[9] as Boolean - iconId = saved[10] as Long - id = saved[11] as String - }) - }, -) - -/** Every setting of one bookmark, saved only on Save. */ -@Composable -fun BookmarkScreen(vm: SessionController, edit: BookmarkEdit, onDone: () -> Unit) { - val b = edit.bookmark - val identities by vm.identities.all.collectAsStateWithLifecycle() - var label by rememberSaveable { mutableStateOf(b.label.orEmpty()) } - var address by rememberSaveable { - mutableStateOf(if (b.port == SessionController.DEFAULT_PORT) b.address.orEmpty() else "${b.address}:${b.port}") - } - var nickname by rememberSaveable { mutableStateOf(b.nickname.orEmpty()) } - var password by rememberSaveable { mutableStateOf(b.password.orEmpty()) } - var identityId by rememberSaveable { mutableStateOf(b.identityId.orEmpty()) } - var channel by rememberSaveable { mutableStateOf(b.channel.orEmpty()) } - var channelPassword by rememberSaveable { mutableStateOf(b.channelPassword.orEmpty()) } - var connectOnStartup by rememberSaveable { mutableStateOf(b.connectOnStartup) } - - val save = { - val (host, port) = SessionController.parseAddress(address) - vm.saveBookmark(edit.index, b.copy().also { - it.label = label.trim().ifEmpty { host } - it.address = host - it.port = port - it.nickname = nickname.trim() - it.password = password - it.identityId = identityId - it.channel = channel.trim() - it.channelPassword = channelPassword - it.connectOnStartup = connectOnStartup - }) - onDone() - } - - SubScreen(if (edit.index < 0) "New bookmark" else "Edit bookmark", onBack = onDone, actions = { - TextButton(onClick = save, enabled = address.isNotBlank()) { Text("Save") } - }) { padding -> - Column( - Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(16.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - OutlinedTextField(label, { label = it }, Modifier.fillMaxWidth(), label = { Text("Name") }, singleLine = true) - OutlinedTextField(address, { address = it }, Modifier.fillMaxWidth(), label = { Text("Server address") }, - singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri)) - OutlinedTextField(password, { password = it }, Modifier.fillMaxWidth(), - label = { Text("Server password") }, singleLine = true, - visualTransformation = PasswordVisualTransformation(), - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)) - IdentityField(identities, identityId) { identityId = it } - OutlinedTextField(nickname, { nickname = it }, Modifier.fillMaxWidth(), label = { Text("Nickname") }, - placeholder = { Text(vm.nicknameFor(identityId)) }, singleLine = true) - val paths = remember(address) { - SessionController.parseAddress(address).let { (host, port) -> vm.channelPathsAt(host, port) } - } - ChannelField(channel, paths) { channel = it } - OutlinedTextField(channelPassword, { channelPassword = it }, Modifier.fillMaxWidth(), - label = { Text("Channel password") }, singleLine = true, - visualTransformation = PasswordVisualTransformation(), - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)) - Row(Modifier.fillMaxWidth().clickable { connectOnStartup = !connectOnStartup }, - verticalAlignment = Alignment.CenterVertically) { - Text("Connect on startup", Modifier.weight(1f)) - Switch(connectOnStartup, { connectOnStartup = it }) - } - } - } -} - -/** The channel to join, typed or picked among [paths] of the server when we are on it. */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -private fun ChannelField(channel: String, paths: List, onChange: (String) -> Unit) { - var open by remember { mutableStateOf(false) } - // A channel already picked lists them all, for picking another. - val matches = if (channel in paths) paths else paths.filter { it.contains(channel.trim(), ignoreCase = true) } - val expanded = open && matches.isNotEmpty() - ExposedDropdownMenuBox(expanded, { open = it }) { - OutlinedTextField( - channel, { onChange(it); open = true }, singleLine = true, - label = { Text("Channel") }, - placeholder = { Text("Default") }, - trailingIcon = if (paths.isEmpty()) null else ({ ExposedDropdownMenuDefaults.TrailingIcon(expanded) }), - modifier = Modifier.fillMaxWidth().menuAnchor(ExposedDropdownMenuAnchorType.PrimaryEditable), - ) - ExposedDropdownMenu(expanded, { open = false }) { - for (path in matches) { - DropdownMenuItem({ Text(path) }, onClick = { - open = false - onChange(path) - }) - } - } - } -} diff --git a/android/app/src/main/java/com/ts3client/android/ui/ChannelEditScreen.kt b/android/app/src/main/java/com/ts3client/android/ui/ChannelEditScreen.kt deleted file mode 100644 index 8e182de..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/ChannelEditScreen.kt +++ /dev/null @@ -1,211 +0,0 @@ -package com.ts3client.android.ui - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.SnackbarHostState -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.input.KeyboardType -import androidx.compose.ui.text.input.PasswordVisualTransformation -import androidx.compose.ui.unit.dp -import com.ts3client.android.ServerController -import com.ts3client.net.ChannelCodec -import com.ts3client.net.ChannelSettings -import kotlinx.coroutines.launch -import kotlin.math.roundToInt - -/** The channel being edited ([channelId] > 0), or one to create below [parentId] (0: the top level). */ -data class ChannelEdit(val channelId: Int, val parentId: Int = 0) - -/** - * TeamSpeak's channel editor on one page: name, password, topic and description, then the - * channel's type, sorting, audio and limits. Only what changed is sent, as the server refuses - * an edit carrying one property we may not change. - */ -@Composable -fun ChannelEditScreen(server: ServerController, edit: ChannelEdit, onDone: () -> Unit) { - val creating = edit.channelId <= 0 - val snackbar = remember { SnackbarHostState() } - val scope = rememberCoroutineScope() - /** The channel as the server described it, which changes are measured against. */ - var original by remember { mutableStateOf(null) } - var edited by remember { mutableStateOf(null) } - var passwordText by remember { mutableStateOf("") } - var saving by remember { mutableStateOf(false) } - - LaunchedEffect(edit) { - if (creating) { - // Made from a channel's sheet, a channel is usually a throwaway one, as in TeamSpeak; - // the server puts a new channel after its siblings. - val fresh = ChannelSettings().apply { - type = ChannelSettings.Type.TEMPORARY - parentId = edit.parentId - order = server.sortChoices(0, edit.parentId).lastOrNull()?.id ?: 0 - } - original = fresh - edited = fresh.copy() - } else { - server.channelSettings(edit.channelId) - .onSuccess { original = it; edited = it.copy() } - .onFailure { snackbar.showSnackbar("Could not read the channel: ${it.message}"); onDone() } - } - } - - val change = { f: ChannelSettings.() -> Unit -> edited = edited?.copy()?.apply(f) } - val save = save@{ - val e = edited ?: return@save - val o = original ?: return@save - if (e.name.isBlank()) { - scope.launch { snackbar.showSnackbar("The channel needs a name.") } - return@save - } - saving = true - scope.launch { - val trimmed = e.copy().apply { name = name.trim() } - val error = if (creating) server.createChannel(edit.parentId, trimmed) - else server.editChannel(edit.channelId, trimmed.changesFrom(o)) - saving = false - if (error == null) onDone() - else snackbar.showSnackbar((if (creating) "Could not create the channel: " else "Could not save the channel: ") + error) - } - } - - val title = when { - !creating -> "Edit channel" - edit.parentId > 0 -> "New sub-channel" - else -> "New channel" - } - SubScreen(title, onBack = onDone, snackbar = snackbar, actions = { - TextButton(onClick = save, enabled = edited != null && !saving) { Text(if (creating) "Create" else "Save") } - }) { padding -> - val e = edited - if (e == null) { - Box(Modifier.padding(padding).fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() } - return@SubScreen - } - Column(Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) { - Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { - OutlinedTextField(e.name, { change { name = it } }, Modifier.fillMaxWidth(), label = { Text("Name") }, - singleLine = true) - OutlinedTextField(passwordText, { - passwordText = it - change { password = it } - }, Modifier.fillMaxWidth(), label = { Text("Password") }, singleLine = true, - placeholder = if (e.hasPassword && e.password == null) ({ Text("Unchanged") }) else null, - visualTransformation = PasswordVisualTransformation(), - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)) - if (e.hasPassword && e.password == null) { - TextButton(onClick = { change { password = "" } }) { Text("Remove password") } - } - OutlinedTextField(e.topic, { change { topic = it } }, Modifier.fillMaxWidth(), label = { Text("Topic") }, - singleLine = true) - OutlinedTextField(e.description, { change { description = it } }, Modifier.fillMaxWidth(), - label = { Text("Description") }, minLines = 3, maxLines = 10) - } - - Section("Channel type") - Segments(listOf( - ChannelSettings.Type.TEMPORARY to "Temporary", - ChannelSettings.Type.SEMI_PERMANENT to "Semi-permanent", - ChannelSettings.Type.PERMANENT to "Permanent", - ), e.type) { change { type = it } } - // The default channel cannot stop being one; another has to take over. - if (original?.defaultChannel != true) { - Toggle("Default channel", e.defaultChannel) { change { defaultChannel = it } } - } - val siblings = remember(edit) { - server.sortChoices(edit.channelId, edit.parentId).filter { it.id != edit.channelId } - } - Picker("Sort after", listOf(0 to "(first)") + siblings.map { it.id to it.name }, - e.order.takeIf { o -> o == 0 || siblings.any { it.id == o } } ?: 0) { change { order = it } } - NumberField("Needed talk power", e.neededTalkPower, 0..9999) { change { neededTalkPower = it } } - - Section("Audio") - val preset = ChannelCodec.Preset.of(e.codec, e.codecQuality) - var custom by remember { mutableStateOf(preset == null) } - val presets: List> = - ChannelCodec.Preset.entries.map { it to it.label } + (null to "Custom") - Segments(presets, if (custom) null else preset) { picked -> - custom = picked == null - if (picked != null) change { codec = picked.codec; codecQuality = picked.quality } - } - if (custom) { - Picker("Codec", ChannelCodec.NAMES.indices.map { it to ChannelCodec.NAMES[it] }, - ChannelCodec.clampCodec(e.codec)) { change { codec = it } } - Level("Quality", e.codecQuality.toFloat(), 0f..ChannelCodec.MAX_QUALITY.toFloat(), - { it.roundToInt().toString() }, steps = ChannelCodec.MAX_QUALITY - 1) { - change { codecQuality = it.roundToInt() } - } - } - Hint("Bandwidth: ${ChannelCodec.bandwidthText(e.codec, e.codecQuality)} per talking client") - - Section("Advanced") - Column(Modifier.padding(horizontal = 16.dp)) { - OutlinedTextField(e.phoneticName, { change { phoneticName = it } }, Modifier.fillMaxWidth(), - label = { Text("Phonetic name") }, singleLine = true) - } - if (e.type == ChannelSettings.Type.TEMPORARY) { - NumberField("Delete delay (seconds)", e.deleteDelay, 0..ChannelSettings.MAX_DELETE_DELAY) { - change { deleteDelay = it } - } - } - Toggle("Voice encrypted", e.encrypted) { change { encrypted = it } } - Text("Max users", Modifier.padding(start = 16.dp, top = 8.dp), style = MaterialTheme.typography.bodyLarge) - Segments(listOf(true to "Unlimited", false to "Limited"), e.maxClientsUnlimited) { - change { maxClientsUnlimited = it } - } - if (!e.maxClientsUnlimited) NumberField("Users", e.maxClients, 0..65535) { change { maxClients = it } } - Text("Family max users", Modifier.padding(start = 16.dp, top = 8.dp), style = MaterialTheme.typography.bodyLarge) - val family = when { - e.familyInherited -> FamilyLimit.INHERITED - e.familyUnlimited -> FamilyLimit.UNLIMITED - else -> FamilyLimit.LIMITED - } - Segments(FamilyLimit.entries.map { it to it.label }, family) { - change { - familyInherited = it == FamilyLimit.INHERITED - familyUnlimited = it == FamilyLimit.UNLIMITED - } - } - if (family == FamilyLimit.LIMITED) { - NumberField("Users", e.maxFamilyClients, 0..65535) { change { maxFamilyClients = it } } - } - } - } -} - -private enum class FamilyLimit(val label: String) { INHERITED("Inherited"), UNLIMITED("Unlimited"), LIMITED("Limited") } - -/** A whole number within [range]; what does not parse leaves the value alone. */ -@Composable -private fun NumberField(label: String, value: Int, range: IntRange, onChange: (Int) -> Unit) { - var text by remember(value) { mutableStateOf(value.toString()) } - Row(Modifier.padding(horizontal = 16.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) { - OutlinedTextField(text, { - text = it.filter(Char::isDigit).take(7) - text.toIntOrNull()?.let { n -> onChange(n.coerceIn(range)) } - }, Modifier.fillMaxWidth(), label = { Text(label) }, singleLine = true, - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)) - } -} diff --git a/android/app/src/main/java/com/ts3client/android/ui/ChannelTree.kt b/android/app/src/main/java/com/ts3client/android/ui/ChannelTree.kt deleted file mode 100644 index 8e82fc4..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/ChannelTree.kt +++ /dev/null @@ -1,349 +0,0 @@ -package com.ts3client.android.ui - -import androidx.compose.animation.animateColorAsState -import androidx.compose.animation.AnimatedVisibility -import androidx.compose.animation.fadeIn -import androidx.compose.animation.fadeOut -import androidx.compose.animation.slideInVertically -import androidx.compose.animation.slideOutVertically -import androidx.compose.foundation.layout.BoxScope -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.material3.Surface -import androidx.compose.runtime.derivedStateOf -import androidx.compose.animation.core.tween -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.combinedClickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.RowScope -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.fillMaxHeight -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.PaddingValues -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.lazy.LazyListState -import androidx.compose.foundation.lazy.rememberLazyListState -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.KeyboardArrowDown -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.ProvideTextStyle -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.runtime.snapshotFlow -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.rotate -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import com.ts3client.android.ChannelItem -import com.ts3client.android.ClientItem -import com.ts3client.android.ServerTree -import com.ts3client.contacts.ContactType -import com.ts3client.gfx.IconKeys -import com.ts3client.net.ClientStatus -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.first - -/** A channel's or a client's row. */ -data class TreeRef(val channel: Boolean, val id: Int) - -/** One line of the tree as the list shows it. */ -private sealed interface TreeRow { - val ref: TreeRef - val key: String get() = (if (ref.channel) "c" else "u") + ref.id - - data class Channel(val channel: ChannelItem, val depth: Int, val expanded: Boolean, val current: Boolean) : TreeRow { - override val ref get() = TreeRef(true, channel.id) - val expandable get() = channel.clients.isNotEmpty() || channel.children.isNotEmpty() - } - - data class Client(val client: ClientItem, val depth: Int) : TreeRow { - override val ref get() = TreeRef(false, client.id) - } -} - -/** The tree's channels and clients in reading order, leaving out what sits in folded channels. */ -private fun flatten(tree: ServerTree, collapsed: Set, currentChannel: Int): List { - val rows = ArrayList() - fun add(channel: ChannelItem, depth: Int) { - val expanded = channel.id !in collapsed - rows += TreeRow.Channel(channel, depth, expanded, channel.id == currentChannel) - if (!expanded) return - channel.clients.forEach { rows += TreeRow.Client(it, depth + 1) } - channel.children.forEach { add(it, depth + 1) } - } - tree.channels.forEach { add(it, 0) } - return rows -} - -private fun ChannelItem.holdsSelf(): Boolean = clients.any { it.self } || children.any { it.holdsSelf() } - -/** Where the list shows our own client: its row, or the folded channel hiding it; -1 when it shows nowhere. */ -private fun selfAnchor(rows: List): Int = rows.indexOfFirst { row -> - when (row) { - is TreeRow.Client -> row.client.self - is TreeRow.Channel -> !row.expanded && row.channel.holdsSelf() - } -} - -/** Which way our own row lies off screen. */ -private enum class Offscreen { ABOVE, BELOW } - -/** Floats over the tree's edge on the side our own row went off. */ -@Composable -private fun BoxScope.ScrollToSelf(where: Offscreen?, onClick: () -> Unit) { - AnimatedVisibility(where == Offscreen.ABOVE, Modifier.align(Alignment.TopCenter).padding(top = 8.dp), - enter = slideInVertically { -it * 2 } + fadeIn(), exit = slideOutVertically { -it * 2 } + fadeOut()) { - ScrollToSelfChip(up = true, onClick) - } - AnimatedVisibility(where == Offscreen.BELOW, Modifier.align(Alignment.BottomCenter).padding(bottom = 8.dp), - enter = slideInVertically { it * 2 } + fadeIn(), exit = slideOutVertically { it * 2 } + fadeOut()) { - ScrollToSelfChip(up = false, onClick) - } -} - -@Composable -private fun ScrollToSelfChip(up: Boolean, onClick: () -> Unit) { - Surface(onClick = onClick, shape = CircleShape, color = MaterialTheme.colorScheme.secondaryContainer, - shadowElevation = 4.dp) { - Row(Modifier.padding(start = 10.dp, end = 14.dp, top = 6.dp, bottom = 6.dp), - verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { - Icon(Icons.Filled.KeyboardArrowDown, null, Modifier.size(18.dp).rotate(if (up) 180f else 0f)) - Text("Me", style = MaterialTheme.typography.labelLarge) - } - } -} - -@Composable -fun ChannelTree( - serverName: String, - tree: ServerTree, - collapsed: Set, - currentChannel: Int, - onToggle: (ChannelItem) -> Unit, - onChannel: (ChannelItem) -> Unit, - onChannelDoubleTap: (ChannelItem) -> Unit, - onClient: (ClientItem) -> Unit, - onServer: () -> Unit, - modifier: Modifier = Modifier, - /** A row to scroll to and flash, once the channels above it are expanded. */ - reveal: TreeRef? = null, - onRevealed: () -> Unit = {}, - /** The rows the find bar matched, and the one it is on, which a reveal does not flash. */ - found: Set = emptySet(), - foundCurrent: TreeRef? = null, - listState: LazyListState = rememberLazyListState(), - /** Brings our own client into view; its row may sit in folded channels. */ - onShowSelf: () -> Unit = {}, -) { - val rows = remember(tree, collapsed, currentChannel) { flatten(tree, collapsed, currentChannel) } - var flashing by remember { mutableStateOf(null) } - LaunchedEffect(reveal, rows) { - val ref = reveal ?: return@LaunchedEffect - val index = rows.indexOfFirst { it.ref == ref } - if (index < 0) return@LaunchedEffect - // Index 0 is the server's row. The row ends up in the middle of the list. - val middle = snapshotFlow { listState.layoutInfo.viewportSize.height }.first { it > 0 } / 2 - listState.animateScrollToItem(index + 1, -middle) - if (ref != foundCurrent) flashing = ref - onRevealed() - } - LaunchedEffect(flashing) { - if (flashing != null) { - delay(1500) - flashing = null - } - } - val anchor = remember(rows) { selfAnchor(rows) } - val offscreen by remember(anchor) { - derivedStateOf { - if (anchor < 0) return@derivedStateOf null - val info = listState.layoutInfo - val index = anchor + 1 // past the server's row - val item = info.visibleItemsInfo.firstOrNull { it.index == index } - when { - item != null && item.offset >= info.viewportStartOffset && - item.offset + item.size <= info.viewportEndOffset -> null - item != null -> if (item.offset < info.viewportStartOffset) Offscreen.ABOVE else Offscreen.BELOW - info.visibleItemsInfo.isEmpty() -> null - index < info.visibleItemsInfo.first().index -> Offscreen.ABOVE - else -> Offscreen.BELOW - } - } - } - Box(modifier.fillMaxSize()) { - LazyColumn(Modifier.fillMaxSize(), state = listState, contentPadding = PaddingValues(vertical = 4.dp)) { - item(key = "server") { - RowLayout(depth = 0, onClick = onServer) { - PackIcon("SERVER_GREEN", null, size = ICON) - Text(serverName, Modifier.weight(1f), fontWeight = FontWeight.Bold, maxLines = 1, - overflow = TextOverflow.Ellipsis) - ServerIcon(tree.serverIconId, size = ICON) - } - } - items(rows, key = { it.key }) { row -> - val background = rowBackground( - when (row.ref) { - flashing -> FLASH - foundCurrent -> findCurrentColor() - in found -> findMatchColor() - else -> Color.Transparent - }, - ) - when (row) { - is TreeRow.Channel -> ChannelRow(row, background, onToggle, onChannel, onChannelDoubleTap) - is TreeRow.Client -> ClientRow(row, tree.countryFlags, background, onClient) - } - } - } - ScrollToSelf(offscreen, onShowSelf) - } -} - -private val ICON = 16.dp -private val INDENT = 14.dp -private val ROW = 26.dp -/** Amber, see-through so the row's text keeps its own colour and contrast. */ -private val FLASH = Color(0x80FFB300) - -/** Fades in fast and out slowly, so a flash is seen. */ -@Composable -private fun rowBackground(target: Color): Color { - val color by animateColorAsState(target, tween(if (target == FLASH) 150 else 600), label = "row") - return color -} - -@Composable -private fun RowLayout( - depth: Int, - onClick: (() -> Unit)?, - background: Color = Color.Transparent, - /** The colour under [background], which a flash or find match goes over. */ - tint: Color = Color.Transparent, - onDoubleClick: (() -> Unit)? = null, - content: @Composable RowScope.() -> Unit, -) { - Row( - Modifier - .fillMaxWidth() - .background(tint) - .background(background) - .height(ROW) - .then(if (onClick != null) Modifier.combinedClickable(onDoubleClick = onDoubleClick, onClick = onClick) else Modifier) - .padding(start = 4.dp + INDENT * depth, end = 8.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(4.dp), - ) { - ProvideTextStyle(MaterialTheme.typography.bodyMedium, content = { content() }) - } -} - -@Composable -private fun ChannelRow( - row: TreeRow.Channel, - background: Color, - onToggle: (ChannelItem) -> Unit, - onChannel: (ChannelItem) -> Unit, - onDoubleTap: (ChannelItem) -> Unit, -) { - val channel = row.channel - val spacer = channel.spacer - RowLayout(row.depth, onClick = { onChannel(channel) }, background = background, - onDoubleClick = if (spacer == null) ({ onDoubleTap(channel) }) else null) { - Box( - Modifier.fillMaxHeight().width(ICON + 4.dp) - .then(if (row.expandable) Modifier.clickable { onToggle(channel) } else Modifier), - contentAlignment = Alignment.Center, - ) { - if (row.expandable) { - Icon(Icons.Filled.KeyboardArrowDown, if (row.expanded) "Collapse" else "Expand", - Modifier.size(ICON + 2.dp).rotate(if (row.expanded) 0f else -90f)) - } - } - if (spacer != null) { - SpacerLabel(spacer.align(), spacer.caption().orEmpty(), Modifier.weight(1f)) - } else { - PackIcon(IconKeys.channel(channel.locked, channel.full, channel.subscribed).asList(), null, size = ICON) - Text( - channel.name, - Modifier.weight(1f), - color = if (row.current) MaterialTheme.colorScheme.primary else Color.Unspecified, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - ServerIcon(channel.iconId, size = ICON) - } - } -} - -/** A spacer's caption, placed as its tag asks; a repeated one of dashes or the like becomes a rule. */ -@Composable -private fun SpacerLabel(align: Char, caption: String, modifier: Modifier) { - if (align == '*') { - if (caption.isNotEmpty() && caption.all { it in "-_=.~" }) { - HorizontalDivider(modifier) - } else { - Text(caption.repeat(200 / caption.length.coerceAtLeast(1)), modifier, maxLines = 1, overflow = TextOverflow.Clip) - } - return - } - val textAlign = when (align) { - 'c' -> TextAlign.Center - 'r' -> TextAlign.End - else -> TextAlign.Start - } - Text(caption, modifier, textAlign = textAlign, maxLines = 1, overflow = TextOverflow.Ellipsis, - color = MaterialTheme.colorScheme.onSurfaceVariant) -} - -@Composable -private fun ClientRow(row: TreeRow.Client, countryFlags: Boolean, background: Color, onClient: (ClientItem) -> Unit) { - val client = row.client - RowLayout(row.depth, onClick = { onClient(client) }, background = background, tint = Color(client.background)) { - Spacer(Modifier.width(ICON + 4.dp)) - StatusIcon(client.status) - Row(Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(4.dp)) { - Text( - client.name, - fontWeight = if (client.self) FontWeight.Bold else FontWeight.Normal, - color = when (client.highlight) { - ContactType.FRIEND -> StatusColors.friend - ContactType.BLOCKED -> StatusColors.blocked - else -> Color.Unspecified - }, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - if (client.awayMessage.isNotEmpty()) { - Text("[${client.awayMessage}]", Modifier.weight(1f, fill = false), - color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) - } - } - for (id in client.groupIconIds) ServerIcon(id, size = ICON) - // The country's flag comes last, at the row's edge. - if (countryFlags) CountryFlag(client.country) - } -} - -@Composable -fun StatusIcon(status: ClientStatus, modifier: Modifier = Modifier) { - PackIcon(IconKeys.client(status), status.name, modifier, size = ICON) -} diff --git a/android/app/src/main/java/com/ts3client/android/ui/ChatPane.kt b/android/app/src/main/java/com/ts3client/android/ui/ChatPane.kt deleted file mode 100644 index dc2778a..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/ChatPane.kt +++ /dev/null @@ -1,185 +0,0 @@ -package com.ts3client.android.ui - -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.PaddingValues -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.LazyRow -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.lazy.rememberLazyListState -import androidx.compose.foundation.text.KeyboardActions -import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.Send -import androidx.compose.material.icons.filled.AttachFile -import androidx.compose.material.icons.filled.Close -import androidx.compose.material3.Badge -import androidx.compose.material3.FilterChip -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.key -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberUpdatedState -import androidx.compose.runtime.snapshotFlow -import androidx.compose.runtime.mutableStateMapOf -import androidx.compose.runtime.saveable.Saver -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.snapshots.SnapshotStateMap -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.input.key.Key -import androidx.compose.ui.input.key.KeyEventType -import androidx.compose.ui.input.key.isShiftPressed -import androidx.compose.ui.input.key.key -import androidx.compose.ui.input.key.onPreviewKeyEvent -import androidx.compose.ui.input.key.type -import androidx.compose.ui.text.input.ImeAction -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import com.ts3client.android.ChatKey -import com.ts3client.android.ChatLine -import com.ts3client.android.ChatMatch -import com.ts3client.android.Chats -import com.ts3client.android.Conversation -import com.ts3client.text.TextQuery -import kotlinx.coroutines.flow.first - -@Composable -fun ChatPane( - chats: Chats, - selected: Conversation, - canSend: Boolean, - onSelect: (ChatKey) -> Unit, - onClose: (ChatKey.Private) -> Unit, - onSend: (String) -> Unit, - /** Picks a file to share in [selected]. */ - onAttach: () -> Unit, - onLink: (String) -> Unit, - modifier: Modifier = Modifier, - /** The lines to show, when not all of [selected]'s. */ - lines: List = selected.lines, - find: TextQuery = TextQuery.EMPTY, - /** The match the find bar is on. */ - current: ChatMatch? = null, - /** A line to scroll to. */ - reveal: Long? = null, - onRevealed: () -> Unit = {}, -) { - Column(modifier) { - LazyRow( - contentPadding = PaddingValues(horizontal = 8.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - items(chats.all, key = { it.key.toString() }) { conversation -> - ConversationChip(conversation, conversation.key == selected.key, onSelect, onClose) - } - } - // Each conversation opens at its newest line. - key(selected.key) { Lines(lines, onLink, Modifier.weight(1f), find, current, reveal, onRevealed) } - // One unsent message per conversation, kept while another one is on screen. - val drafts = rememberSaveable(saver = DraftsSaver) { mutableStateMapOf() } - val draftKey = selected.key.toString() - val draft = drafts[draftKey].orEmpty() - val send = { - if (draft.isNotBlank()) { - onSend(draft.trim()) - drafts.remove(draftKey) - } - } - Row(Modifier.padding(8.dp), verticalAlignment = Alignment.CenterVertically) { - IconButton(onClick = onAttach, enabled = canSend) { - Icon(Icons.Filled.AttachFile, "Share file") - } - OutlinedTextField( - draft, { drafts[draftKey] = it }, - Modifier.weight(1f).onPreviewKeyEvent { e -> - // A hardware keyboard's Enter sends, as on the desktop; Shift+Enter starts a new line. - val enter = e.key == Key.Enter && !e.isShiftPressed - if (enter && e.type == KeyEventType.KeyDown) send() - enter - }, - placeholder = { Text("Message ${selected.title}", maxLines = 1, overflow = TextOverflow.Ellipsis) }, - enabled = canSend, - maxLines = 4, - keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send), - keyboardActions = KeyboardActions(onSend = { send() }), - ) - IconButton(onClick = send, enabled = canSend && draft.isNotBlank()) { - Icon(Icons.AutoMirrored.Filled.Send, "Send") - } - } - } -} - -private val DraftsSaver = Saver, HashMap>( - save = { HashMap(it) }, - restore = { mutableStateMapOf().apply { putAll(it) } }, -) - -@Composable -private fun ConversationChip( - conversation: Conversation, - selected: Boolean, - onSelect: (ChatKey) -> Unit, - onClose: (ChatKey.Private) -> Unit, -) { - val key = conversation.key - FilterChip( - selected = selected, - onClick = { onSelect(key) }, - label = { Text(conversation.title, maxLines = 1, overflow = TextOverflow.Ellipsis) }, - leadingIcon = if (conversation.unread) ({ Badge() }) else null, - trailingIcon = if (key is ChatKey.Private) ({ - Icon(Icons.Filled.Close, "Close", Modifier.size(18.dp).clickable { onClose(key) }) - }) else null, - ) -} - -/** The conversation's lines, following new ones while the newest is in view. */ -@Composable -private fun Lines( - lines: List, - onLink: (String) -> Unit, - modifier: Modifier, - find: TextQuery, - current: ChatMatch?, - reveal: Long?, - onRevealed: () -> Unit, -) { - val listState = rememberLazyListState(initialFirstVisibleItemIndex = (lines.size - 1).coerceAtLeast(0)) - val link by rememberUpdatedState(onLink) - LaunchedEffect(lines.lastOrNull()?.id) { - val info = listState.layoutInfo - val atEnd = info.visibleItemsInfo.lastOrNull()?.index?.let { it >= info.totalItemsCount - 2 } ?: true - if (atEnd && lines.isNotEmpty()) listState.scrollToItem(lines.size - 1) - } - LaunchedEffect(reveal, lines) { - val id = reveal ?: return@LaunchedEffect - val index = lines.indexOfFirst { it.id == id } - if (index < 0) return@LaunchedEffect - val info = listState.layoutInfo - if (info.visibleItemsInfo.none { it.index == index && it.offset >= 0 && it.offset + it.size <= info.viewportEndOffset }) { - // The line's top ends up in the middle of the list. - val middle = snapshotFlow { listState.layoutInfo.viewportSize.height }.first { it > 0 } / 2 - listState.animateScrollToItem(index, -middle) - } - onRevealed() - } - LazyColumn(modifier.fillMaxWidth(), state = listState, contentPadding = PaddingValues(horizontal = 12.dp, vertical = 4.dp)) { - items(lines, key = { it.id }) { line -> - RichText(line.html, { link(it) }, Modifier.padding(vertical = 2.dp), MaterialTheme.typography.bodyMedium, - find, if (current?.line == line.id) current.nth else -1) - } - } -} diff --git a/android/app/src/main/java/com/ts3client/android/ui/ChatText.kt b/android/app/src/main/java/com/ts3client/android/ui/ChatText.kt deleted file mode 100644 index 4f557a9..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/ChatText.kt +++ /dev/null @@ -1,318 +0,0 @@ -package com.ts3client.android.ui - -import androidx.compose.foundation.Image -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.aspectRatio -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.widthIn -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.LocalTextStyle -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.produceState -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberUpdatedState -import androidx.compose.runtime.staticCompositionLocalOf -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.text.AnnotatedString -import androidx.compose.ui.text.LinkAnnotation -import androidx.compose.ui.text.SpanStyle -import androidx.compose.ui.text.TextLinkStyles -import androidx.compose.ui.text.TextStyle -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.fromHtml -import androidx.compose.ui.unit.dp -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import com.ts3client.android.WebPictures -import com.ts3client.myts.ChatAttachment -import com.ts3client.text.BBCode -import com.ts3client.text.ChatHtml -import com.ts3client.text.TextQuery - -/** - * HTML as [BBCode][com.ts3client.text.BBCode] and [ChatHtml] write it, with its rules as dividers - * and its pictures fetched from the web: Android's HTML parser shows neither, so the text is - * split at them. - */ -@Composable -fun RichText( - html: String, - onLink: (String) -> Unit, - modifier: Modifier = Modifier, - style: TextStyle = LocalTextStyle.current, - /** Matches to highlight: [current] is the index of the one the find bar is on, if it is here. */ - find: TextQuery = TextQuery.EMPTY, - current: Int = -1, -) { - val link by rememberUpdatedState(onLink) - val color = linkColor() - val parsed = remember(html, color) { split(html) { chatText(it, color) { href -> link(href) } } } - val match = findMatchColor() - val currentMatch = findCurrentColor() - val pieces = remember(parsed, find, current, match, currentMatch) { - if (find.isEmpty) parsed else highlight(parsed, find, current, match, currentMatch) - } - Column(modifier) { - for (piece in pieces) { - when (piece) { - Piece.Rule -> HorizontalDivider(Modifier.padding(vertical = 6.dp)) - is Piece.Image -> WebPicture(piece, style) { link(it) } - // As wide as there is room, for aligned paragraphs to have somewhere to go. - is Piece.Text -> if (piece.text.isNotEmpty()) Text(piece.text, Modifier.fillMaxWidth(), style = style) - } - } - } -} - -/** [pieces] with [find]'s matches behind [match], and the [current]th of them, counting across pieces, behind [currentMatch]. */ -private fun highlight(pieces: List, find: TextQuery, current: Int, match: Color, currentMatch: Color): List { - var n = 0 - return pieces.map { piece -> - if (piece !is Piece.Text) return@map piece - val m = find.matcher(piece.text.text) ?: return@map piece - val text = AnnotatedString.Builder(piece.text) - while (m.find()) { - if (m.end() == m.start()) continue - text.addStyle(SpanStyle(background = if (n == current) currentMatch else match), m.start(), m.end()) - n++ - } - Piece.Text(text.toAnnotatedString()) - } -} - -/** The web pictures descriptions show. */ -val LocalWebPictures = staticCompositionLocalOf { null } - -private sealed interface Piece { - data class Text(val text: AnnotatedString) : Piece - data object Rule : Piece - /** @param href where the picture links to, if it sits in a link */ - data class Image(val url: String, val href: String?, val align: Alignment.Horizontal) : Piece -} - -/** - * [html] cut at its rules and pictures. Each piece of text is closed where it is cut and the - * next reopens what it was in, so an aligned block or a link carries on past a picture. - */ -private fun split(html: String, text: (String) -> AnnotatedString): List { - val pieces = ArrayList() - val divs = ArrayList() - var anchor: String? = null - var href: String? = null - val current = StringBuilder() - fun cut() { - if (anchor != null) current.append("") - repeat(divs.size) { current.append("") } - pieces += Piece.Text(text(current.toString())) - current.setLength(0) - divs.forEach { current.append(it) } - anchor?.let { current.append(it) } - } - var last = 0 - for (m in CUT_TAG.findAll(html)) { - current.append(html, last, m.range.first) - last = m.range.last + 1 - val tag = m.value - when { - tag.startsWith(" { - cut() - pieces += Piece.Rule - } - tag.startsWith(" { - cut() - pieces += Piece.Image(unescape(m.groupValues[1]), href?.let(::unescape), alignment(divs)) - } - tag.startsWith(" { - divs += tag - current.append(tag) - } - tag.equals("", ignoreCase = true) -> { - divs.removeLastOrNull() - current.append(tag) - } - tag.startsWith(" { - anchor = tag - href = m.groupValues[2] - current.append(tag) - } - else -> { - anchor = null - href = null - current.append(tag) - } - } - } - current.append(html, last, html.length) - pieces += Piece.Text(text(current.toString())) - return pieces -} - -/** Where the innermost aligned block puts what is in it. */ -private fun alignment(divs: List): Alignment.Horizontal { - val align = divs.asReversed().firstNotNullOfOrNull { ALIGN.find(it)?.groupValues?.get(1) } - return when (align) { - "center" -> Alignment.CenterHorizontally - "right" -> Alignment.End - else -> Alignment.Start - } -} - -private fun unescape(s: String) = - s.replace("<", "<").replace(">", ">").replace(""", "\"").replace("&", "&") - -/** - * A picture at its own size, a pixel to a dp as TeamSpeak shows it, narrowed to fit. With - * pictures turned off, or when one cannot be had, its address as a link behind a picture icon. - */ -@Composable -private fun WebPicture(image: Piece.Image, style: TextStyle, onLink: (String) -> Unit) { - val pictures = LocalWebPictures.current - Column(Modifier.fillMaxWidth().padding(vertical = 2.dp), horizontalAlignment = image.align) { - if (pictures == null || !pictures.enabled) { - PictureLink("ICONVIEWER", image, style, onLink) - return@Column - } - val version by pictures.version.collectAsStateWithLifecycle() - val state by produceState(WebPictures.State.Loading, image.url, version) { - value = pictures.state(image.url) - } - when (val shown = state) { - WebPictures.State.Loading -> PackIcon("LOADING_IMAGE", "Loading picture", size = 16.dp) - WebPictures.State.Broken -> PictureLink("BROKEN_IMAGE", image, style, onLink) - is WebPictures.State.Shown -> { - val picture = shown.picture - val viewer = LocalPictureViewer.current - Image( - rememberPicturePainter(picture), - null, - Modifier - .widthIn(max = picture.width.dp) - .aspectRatio(picture.width.toFloat() / picture.height.coerceAtLeast(1)) - .then(if (viewer != null) Modifier.clickable { - viewer(viewedPicture(image, onLink) { pictures.data(image.url) }) - } else if (image.href != null) Modifier.clickable { onLink(image.href) } else Modifier), - ) - } - } - } -} - -/** [image] to open full size; a file shared in chat has no address to copy or link to follow but itself. */ -private fun viewedPicture(image: Piece.Image, onLink: (String) -> Unit, read: suspend () -> ByteArray?): ViewedPicture { - val attachment = ChatAttachment.Ref.parse(image.url) - if (attachment != null) return ViewedPicture(attachment.fileName.substringBeforeLast('.'), read = read) - val openLink = image.href?.let { href -> { onLink(href) } } - return ViewedPicture(pictureName(image.url), image.url, openLink, read = read) -} - -/** The picture's address as a link behind [iconKey], then the link it sat in, if any, so neither is lost. */ -@Composable -private fun PictureLink(iconKey: String, image: Piece.Image, style: TextStyle, onLink: (String) -> Unit) { - val color = linkColor() - val text = remember(image, color) { - val links = listOfNotNull(image.url, image.href?.takeIf { it != image.url }) - chatText(links.joinToString(" ") { "${BBCode.escape(linkText(it))}" }, color, onLink) - } - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { - PackIcon(iconKey, "Picture", size = 16.dp) - Text(text, style = style) - } -} - -/** A shared file goes by its name, anything else by its address. */ -private fun linkText(url: String): String = ChatAttachment.Ref.parse(url)?.fileName ?: BBCode.shortAddress(url) - -/** - * HTML without rules as styled text. Android's parser knows no stylesheets, tables, - * numbered lists, font sizes or `align`, so the classes [ChatHtml] marks lines with become - * inline colours, table rows lines of their cells, numbered items numbered lines, sizes - * ``/``, and alignment the style it does know. - */ -fun chatText(html: String, linkColor: Color, onLink: (String) -> Unit): AnnotatedString { - val styled = sizes(numbered(CLASS.replace(html) { m -> - CLASS_COLORS[m.groupValues[1]]?.let { "style=\"color:$it\"" } ?: "" - })) - .replace(ALIGN) { m -> "style=\"text-align:${ALIGNS.getValue(m.groupValues[1])}\"" } - .replace(CELL_END, " ") - .replace(ROW_END, "
") - val text = AnnotatedString.fromHtml( - styled, - TextLinkStyles(SpanStyle(color = linkColor, fontWeight = FontWeight.SemiBold)), - ) { link -> (link as? LinkAnnotation.Url)?.let { onLink(it.url) } } - // Block elements leave line breaks around the text. - val start = text.text.indexOfFirst { !it.isWhitespace() }.coerceAtLeast(0) - val end = text.text.indexOfLast { !it.isWhitespace() } + 1 - return if (end <= start) AnnotatedString("") else text.subSequence(start, end) -} - -/** Numbers the items of each `
    `, innermost first. */ -private fun numbered(html: String): String { - var out = html - while (true) { - val list = INNER_OL.find(out) ?: return out - val letters = list.groupValues[1].isNotEmpty() - var n = 0 - val items = LI.replace(list.groupValues[2]) { m -> - if (m.value.startsWith("" + (if (letters) ('a' + (n - 1) % 26).toString() else n.toString()) + ". " - } - } - out = out.replaceRange(list.range, "
    $items
    ") - } -} - -/** - * Turns each font-size span into ``s or `` (or a plain span), closing it alike. - * Sizes are TeamSpeak's, around its 11 px text. - */ -private fun sizes(html: String): String { - val closes = ArrayDeque() - return SPAN.replace(html) { m -> - if (m.value.startsWith(" listOf("span") - px >= BIGGER_PX -> listOf("big", "big") - px >= BIG_PX -> listOf("big") - px <= SMALL_PX -> listOf("small") - else -> listOf("span") - } - closes.addLast(tags.reversed().joinToString("") { "" }) - if (px == null) m.value else tags.joinToString("") { "<$it>" } - } - } -} - -private const val BIGGER_PX = 18 -private const val BIG_PX = 13 -private const val SMALL_PX = 9 - -private val INNER_OL = Regex("((?:(?!]).)*?)
", RegexOption.DOT_MATCHES_ALL) -private val LI = Regex("") -private val SPAN = Regex("|]*>|") -private val ALIGNS = mapOf("left" to "start", "justify" to "start", "center" to "center", "right" to "end") - -/** Where the text is cut, and what it has to carry across: aligned blocks and links. */ -private val CUT_TAG = Regex( - "||]*>||]*href=\"([^\"]*)\"[^>]*>|", - RegexOption.IGNORE_CASE, -) -private val CLASS = Regex("class=\"([a-z]+)\"") -private val ALIGN = Regex("align=\"(left|center|right|justify)\"") -private val CELL_END = Regex("") -private val ROW_END = Regex("") - -private val CLASS_COLORS = mapOf( - ChatHtml.MUTED_CLASS to "#8c8c8c", - ChatHtml.EVENT_CLASS to "#7a8fa6", -) diff --git a/android/app/src/main/java/com/ts3client/android/ui/ConnectScreen.kt b/android/app/src/main/java/com/ts3client/android/ui/ConnectScreen.kt deleted file mode 100644 index 39ae3ec..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/ConnectScreen.kt +++ /dev/null @@ -1,231 +0,0 @@ -package com.ts3client.android.ui - -import android.graphics.BitmapFactory -import androidx.activity.compose.BackHandler -import androidx.compose.foundation.Image -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.PaddingValues -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.itemsIndexed -import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.foundation.layout.Box -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.ArrowBack -import androidx.compose.material.icons.filled.MoreVert -import androidx.compose.material3.Button -import androidx.compose.material3.DropdownMenu -import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.ExposedDropdownMenuBox -import androidx.compose.material3.ExposedDropdownMenuDefaults -import androidx.compose.material3.ExposedDropdownMenuAnchorType -import androidx.compose.material3.Icon -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.IconButton -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.SnackbarHostState -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.asImageBitmap -import androidx.compose.ui.text.SpanStyle -import androidx.compose.ui.text.buildAnnotatedString -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.withStyle -import androidx.compose.ui.text.input.KeyboardType -import androidx.compose.ui.text.input.PasswordVisualTransformation -import androidx.compose.ui.unit.dp -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import com.ts3client.android.IdentityInfo -import com.ts3client.android.SessionController -import com.ts3client.config.Bookmark -import com.ts3client.net.IconRepository - -/** Where to connect to: an address typed in, or a bookmark. */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun ConnectScreen( - vm: SessionController, - snackbar: SnackbarHostState, - onSettings: () -> Unit, - onConnect: (() -> Unit) -> Unit, - onEditBookmark: (BookmarkEdit) -> Unit, - /** Back to the servers already connected; null when there are none. */ - onBack: (() -> Unit)?, -) { - val lastEnd by vm.lastEnd.collectAsStateWithLifecycle() - val bookmarks by vm.bookmarks.collectAsStateWithLifecycle() - val identities by vm.identities.all.collectAsStateWithLifecycle() - var address by rememberSaveable { mutableStateOf(vm.lastAddress) } - var identityId by rememberSaveable { mutableStateOf("") } - var nickname by rememberSaveable { mutableStateOf(vm.nicknameFor("")) } - var password by rememberSaveable { mutableStateOf("") } - - if (onBack != null) BackHandler(onBack = onBack) - - Scaffold( - topBar = { - TopAppBar( - title = { Text("TeamSpeak") }, - navigationIcon = { - if (onBack != null) IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } - }, - actions = { - IconButton(onClick = onSettings) { PackIcon("SETTINGS", "Settings") } - }, - ) - }, - snackbarHost = { SnackbarHost(snackbar) }, - ) { padding -> - LazyColumn( - Modifier.padding(padding).imePadding(), - contentPadding = PaddingValues(16.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - item { - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - OutlinedTextField(address, { address = it }, Modifier.fillMaxWidth(), label = { Text("Server address") }, - singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri)) - OutlinedTextField(nickname, { nickname = it }, Modifier.fillMaxWidth(), label = { Text("Nickname") }, - singleLine = true) - OutlinedTextField(password, { password = it }, Modifier.fillMaxWidth(), - label = { Text("Server password") }, singleLine = true, - visualTransformation = PasswordVisualTransformation(), - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)) - IdentityField(identities, identityId) { - identityId = it - nickname = vm.nicknameFor(it) - } - lastEnd?.let { - Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodyMedium) - } - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Button( - onClick = { onConnect { vm.connect(address.trim(), nickname.trim(), password, identityId) } }, - enabled = address.isNotBlank() && nickname.isNotBlank(), - ) { Text("Connect") } - TextButton(onClick = { - onEditBookmark(BookmarkEdit(-1, vm.newBookmark(address.trim(), nickname.trim(), password, identityId))) - }, enabled = address.isNotBlank()) { Text("Add bookmark") } - } - } - } - if (bookmarks.isNotEmpty()) { - item { - Text("Bookmarks", Modifier.padding(top = 16.dp), style = MaterialTheme.typography.titleSmall, - color = MaterialTheme.colorScheme.primary) - } - } - itemsIndexed(bookmarks) { index, bookmark -> - BookmarkRow(bookmark, identities, { onConnect { vm.connect(bookmark) } }, - onEdit = { onEditBookmark(BookmarkEdit(index, bookmark)) }, - onPin = if (vm.canPinShortcuts) ({ vm.pinShortcut(bookmark) }) else null, - onRemove = { vm.removeBookmark(bookmark) }) - } - } - } -} - -/** The identities to connect with, the default one first as an empty id. */ -private fun identityChoices(identities: List): List> { - val default = identities.firstOrNull { it.isDefault }?.name - return listOf("" to (default?.let { "Default ($it)" } ?: "Default")) + identities.map { it.id to it.name } -} - -/** An id no longer among the identities connects with the default, and shows as such. */ -private fun shownId(identities: List, id: String) = id.takeIf { i -> identities.any { it.id == i } } ?: "" - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -internal fun IdentityField(identities: List, selected: String, onSelect: (String) -> Unit) { - val choices = identityChoices(identities) - val shown = shownId(identities, selected) - var open by remember { mutableStateOf(false) } - ExposedDropdownMenuBox(open, { open = it }) { - OutlinedTextField( - choices.first { it.first == shown }.second, {}, readOnly = true, singleLine = true, - label = { Text("Identity") }, - trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(open) }, - modifier = Modifier.fillMaxWidth().menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable), - ) - ExposedDropdownMenu(open, { open = false }) { - for ((id, name) in choices) { - DropdownMenuItem({ Text(name) }, onClick = { - open = false - onSelect(id) - }) - } - } - } -} - -/** The server's icon as last seen there, else the pack's bookmark icon. */ -@Composable -private fun BookmarkIcon(iconId: Long) { - val cached = remember(iconId) { - IconRepository.cached(iconId)?.let { BitmapFactory.decodeByteArray(it, 0, it.size)?.asImageBitmap() } - } - if (cached != null) Image(cached, null, Modifier.size(24.dp)) - else PackIcon("BOOKMARK_MANAGER", null) -} - -private val AUTOCONNECT = Color(0xFF3A9D4A) - -@Composable -private fun BookmarkRow( - bookmark: Bookmark, - identities: List, - onConnect: () -> Unit, - onEdit: () -> Unit, - /** Null when the launcher takes no shortcuts. */ - onPin: (() -> Unit)?, - onRemove: () -> Unit, -) { - val identity = identities.firstOrNull { it.id == bookmark.identityId } - var menu by remember { mutableStateOf(false) } - ListItem( - headlineContent = { - Text(buildAnnotatedString { - if (bookmark.connectOnStartup) { - withStyle(SpanStyle(color = AUTOCONNECT, fontWeight = FontWeight.Bold)) { append("AC") } - append(' ') - } - append(bookmark.displayName()) - }) - }, - supportingContent = { - Text(listOfNotNull("${bookmark.address}:${bookmark.port}", bookmark.channel.ifBlank { null }, identity?.name) - .joinToString(" · ")) - }, - leadingContent = { BookmarkIcon(bookmark.iconId) }, - trailingContent = { - Box { - IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "Bookmark options") } - DropdownMenu(menu, { menu = false }) { - DropdownMenuItem({ Text("Edit") }, onClick = { menu = false; onEdit() }) - onPin?.let { DropdownMenuItem({ Text("Add to home screen") }, onClick = { menu = false; it() }) } - DropdownMenuItem({ Text("Remove") }, onClick = { menu = false; onRemove() }) - } - } - }, - modifier = Modifier.clickable(onClick = onConnect), - ) -} diff --git a/android/app/src/main/java/com/ts3client/android/ui/ConnectionInfoScreen.kt b/android/app/src/main/java/com/ts3client/android/ui/ConnectionInfoScreen.kt deleted file mode 100644 index 078787e..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/ConnectionInfoScreen.kt +++ /dev/null @@ -1,150 +0,0 @@ -package com.ts3client.android.ui - -import android.content.ClipData -import android.content.ClipboardManager -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.RowScope -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.PrimaryScrollableTabRow -import androidx.compose.material3.Tab -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.text.font.FontStyle -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import com.ts3client.android.ClientItem -import com.ts3client.android.ServerController -import com.ts3client.net.ConnectionStats -import com.ts3client.net.ConnectionStatsFormat -import kotlinx.coroutines.delay - -private const val REFRESH_MS = 1000L - -private val TABS = ConnectionStatsFormat.TRAFFIC_TABS.map { it.title() } + - listOf(ConnectionStatsFormat.QUOTA_TAB, ConnectionStatsFormat.VOICE_TAB) - -/** - * A client's connection figures, read again every second while shown, laid out as TeamSpeak's - * Connection Info window: name, times, ping and address beside the avatar, then a tab per - * traffic category with Total / In / Out columns, Quota, and what our playback made of their voice. - */ -@Composable -fun ConnectionInfoScreen(server: ServerController, clientId: Int, client: ClientItem?, onBack: () -> Unit) { - var stats by remember { mutableStateOf(null) } - LaunchedEffect(clientId) { - while (true) { - stats = server.connectionStats(clientId) ?: break - delay(REFRESH_MS) - } - } - var tab by rememberSaveable { mutableIntStateOf(0) } - val s = stats - SubScreen("Connection info", onBack) { padding -> - Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) { - Row(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) { - Summary(s, client?.nickname ?: "", Modifier.weight(1f)) - if (client != null && client.avatarFlag.isNotEmpty()) { - Avatar(client.uniqueId, client.avatarFlag, Modifier.padding(start = 12.dp), size = 72.dp) - } - } - PrimaryScrollableTabRow(selectedTabIndex = tab, edgePadding = 8.dp) { - TABS.forEachIndexed { i, title -> Tab(tab == i, onClick = { tab = i }, text = { Text(title) }) } - } - val traffic = ConnectionStatsFormat.TRAFFIC_TABS - Column(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) { - when { - tab < traffic.size -> TrafficTable(ConnectionStatsFormat.trafficRows(s, traffic[tab].kind())) - tab == traffic.size -> Figures(ConnectionStatsFormat.quotaGroups(s)) - else -> Figures(listOf(ConnectionStatsFormat.voiceRows(s?.voiceReceived))) - } - } - } - } -} - -@Composable -private fun Summary(s: ConnectionStats?, nickname: String, modifier: Modifier) { - val context = LocalContext.current - val address = ConnectionStatsFormat.copyableAddress(s) - val rows = ConnectionStatsFormat.summaryRows(s, nickname) - Column(modifier) { - rows.forEachIndexed { i, row -> - Row(Modifier.heightIn(min = 32.dp), verticalAlignment = Alignment.CenterVertically) { - Text(row.label, Modifier.weight(1f), color = MaterialTheme.colorScheme.onSurfaceVariant) - Text(row.value, textAlign = TextAlign.End) - if (i == rows.lastIndex) { - IconButton( - onClick = { - // The system confirms the copy itself. - context.getSystemService(ClipboardManager::class.java) - .setPrimaryClip(ClipData.newPlainText("Client address", address)) - }, - enabled = address != null, - modifier = Modifier.size(32.dp), - ) { PackIcon("COPY", "Copy client address", size = 18.dp) } - } - } - } - } -} - -/** Labelled figures in groups set apart by a rule. */ -@Composable -private fun Figures(groups: List>) { - groups.forEachIndexed { g, rows -> - if (g > 0) HorizontalDivider(Modifier.padding(vertical = 8.dp)) - for (row in rows) { - Row(Modifier.padding(vertical = 4.dp)) { - Text(row.label, Modifier.weight(1f), color = MaterialTheme.colorScheme.onSurfaceVariant) - Text(row.value, textAlign = TextAlign.End) - } - } - } -} - -@Composable -private fun TrafficTable(rows: List) { - Row(Modifier.padding(vertical = 4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp)) { - LabelCell("") - ConnectionStatsFormat.COLUMNS.forEachIndexed { i, column -> ValueCell(column, i == 0, FontStyle.Italic) } - } - for (row in rows) { - Row(Modifier.padding(vertical = 4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp), - verticalAlignment = Alignment.CenterVertically) { - LabelCell(row.label) - ValueCell(row.total, narrow = true) - ValueCell(row.`in`) - ValueCell(row.out) - } - } -} - -@Composable -private fun RowScope.LabelCell(text: String) = - Text(text, Modifier.weight(1.5f), color = MaterialTheme.colorScheme.onSurfaceVariant, - style = MaterialTheme.typography.bodySmall) - -/** The Total column only ever holds the loss percentage. */ -@Composable -private fun RowScope.ValueCell(text: String, narrow: Boolean = false, fontStyle: FontStyle? = null) = - Text(text, Modifier.weight(if (narrow) 0.7f else 1f), style = MaterialTheme.typography.bodySmall, fontStyle = fontStyle, - textAlign = TextAlign.End) diff --git a/android/app/src/main/java/com/ts3client/android/ui/ContactsScreen.kt b/android/app/src/main/java/com/ts3client/android/ui/ContactsScreen.kt deleted file mode 100644 index 702dc98..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/ContactsScreen.kt +++ /dev/null @@ -1,271 +0,0 @@ -package com.ts3client.android.ui - -import android.content.ClipData -import android.content.ClipboardManager -import androidx.activity.compose.rememberLauncherForActivityResult -import androidx.activity.result.contract.ActivityResultContracts -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.MoreVert -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.DropdownMenu -import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.ListItem -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.PrimaryTabRow -import androidx.compose.material3.Tab -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.unit.dp -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import com.ts3client.android.SessionController -import com.ts3client.contacts.Contact -import com.ts3client.contacts.ContactDefaults -import com.ts3client.contacts.ContactType -import com.ts3client.contacts.NicknameDisplay -import kotlinx.coroutines.launch -import java.time.format.DateTimeFormatter -import kotlin.math.roundToInt - -private val SEEN = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm") - -private val DISPLAYS = listOf( - NicknameDisplay.ONLY_NICKNAME to "Nickname", - NicknameDisplay.ONLY_CUSTOM to "Custom name", - NicknameDisplay.BOTH to "Both", -) - -private val GROUPS = listOf( - ContactType.FRIEND to "Friends", - ContactType.BLOCKED to "Blocked", - ContactType.NEUTRAL to "Neutral", -) - -/** - * The contact list, grouped as TeamSpeak's Contacts window groups it, with each - * contact's own page and the defaults new contacts start out with. - * - * @param editing the unique id of the contact whose page is open, if any - */ -@Composable -fun ContactsScreen(vm: SessionController, editing: String?, onEdit: (String?) -> Unit, onBack: () -> Unit) { - var defaults by rememberSaveable { mutableStateOf(false) } - when { - editing != null -> return ContactScreen(vm, editing, onBack = { onEdit(null) }) - defaults -> return ContactDefaultsScreen(vm, onBack = { defaults = false }) - } - - val contacts by vm.contacts.collectAsStateWithLifecycle() - val scope = rememberCoroutineScope() - var menu by remember { mutableStateOf(false) } - var imported by remember { mutableStateOf(null) } - val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> - if (uri != null) scope.launch { - imported = runCatching { vm.importContacts(uri) }.fold( - { (found, added) -> - if (found == 0) "That file holds no contacts." - else "Imported $found contacts, $added of them new." - }, - { "That file is not a TeamSpeak 3 settings.db." }, - ) - } - } - - SubScreen("Contacts", onBack, actions = { - Box { - IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "More") } - DropdownMenu(menu, { menu = false }) { - DropdownMenuItem({ Text("Defaults for new contacts") }, onClick = { menu = false; defaults = true }) - DropdownMenuItem({ Text("Import from TeamSpeak 3") }, onClick = { - menu = false - importer.launch(arrayOf("*/*")) - }) - } - } - }) { padding -> - LazyColumn(Modifier.padding(padding)) { - imported?.let { item { Hint(it) } } - if (contacts.isEmpty()) { - item { - Hint("No contacts yet. Tap a client on a server to add them as a friend or block them, " + - "or import the contacts of TeamSpeak 3 from its settings.db.") - } - } - for ((type, title) in GROUPS) { - val group = contacts.filter { it.type == type }.sortedBy { label(it).lowercase() } - if (group.isEmpty()) continue - item(key = type) { Section(title) } - items(group, key = { it.uniqueId }) { contact -> - ListItem( - headlineContent = { Text(label(contact), color = typeColor(contact.type)) }, - supportingContent = { Text(lastSeen(contact)) }, - modifier = Modifier.clickable { onEdit(contact.uniqueId) }, - ) - } - } - } - } -} - -/** One contact's settings; each is stored as it is changed, the names once the page is left. */ -@Composable -private fun ContactScreen(vm: SessionController, uniqueId: String, onBack: () -> Unit) { - val contacts by vm.contacts.collectAsStateWithLifecycle() - val contact = contacts.firstOrNull { it.uniqueId == uniqueId } - if (contact == null) { - LaunchedEffect(Unit) { onBack() } - return - } - // Starts from the stored entry, which may have been seen again since this page opened. - fun edit(change: Contact.() -> Unit) { - vm.contact(uniqueId)?.let { vm.saveContact(it.apply(change)) } - } - var customName by rememberSaveable(uniqueId) { mutableStateOf(contact.nickname) } - var phoneticName by rememberSaveable(uniqueId) { mutableStateOf(contact.phoneticNickname) } - var removing by remember { mutableStateOf(false) } - val leave = { - if (customName.trim() != contact.nickname || phoneticName.trim() != contact.phoneticNickname) { - edit { - nickname = customName.trim() - phoneticNickname = phoneticName.trim() - } - } - onBack() - } - - SubScreen(label(contact), leave, actions = { - IconButton(onClick = { removing = true }) { PackIcon(if (contact.type == ContactType.BLOCKED) "REMOVE_FOE" else "REMOVE_FRIEND", "Remove from contacts") } - }) { padding -> - Column(Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(vertical = 8.dp)) { - OutlinedTextField(customName, { customName = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp), - label = { Text("Custom nickname") }, singleLine = true) - OutlinedTextField(phoneticName, { phoneticName = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), - label = { Text("Phonetic nickname") }, singleLine = true) - - Section("Contact") - Segments(GROUPS.map { (type, _) -> type to type.label() }, contact.type) { edit { type = it } } - - Section("Show as") - Segments(DISPLAYS, contact.nicknameDisplay) { edit { nicknameDisplay = it } } - - Section("Ignore") - Toggle("Mute", contact.automute) { edit { automute = it } } - Toggle("Ignore server and channel chat", contact.ignorePublicMessages) { edit { ignorePublicMessages = it } } - Toggle("Ignore private chat", contact.ignorePrivateMessages) { edit { ignorePrivateMessages = it } } - Toggle("Ignore pokes", contact.ignorePokes) { edit { ignorePokes = it } } - Toggle("Hide avatar", contact.ignoreAvatar) { edit { ignoreAvatar = it } } - Toggle("Hide away message", contact.ignoreAwayMessage) { edit { ignoreAwayMessage = it } } - Toggle("Deny whisper", !contact.whisperAllowed) { edit { whisperAllowed = !it } } - - Section("Playback") - val volume = if (contact.hasVolumeModifier) contact.volumeModifier.toFloat() else 0f - Level("Volume", volume, -30f..20f, ::formatVolume) { db -> - val rounded = db.roundToInt().toDouble() - edit { - hasVolumeModifier = rounded != 0.0 - volumeModifier = rounded - } - } - - Section("Details") - val context = LocalContext.current - LinkRow("Unique ID", contact.uniqueId) { - // The system confirms the copy itself. - context.getSystemService(ClipboardManager::class.java) - .setPrimaryClip(ClipData.newPlainText("Unique ID", contact.uniqueId)) - } - ListItem(headlineContent = { Text(lastSeen(contact)) }) - } - } - - if (removing) { - AlertDialog( - onDismissRequest = { removing = false }, - title = { Text("Remove ${label(contact)}?") }, - text = { Text("Their settings here are forgotten; they show as anyone else again.") }, - confirmButton = { - TextButton(onClick = { - removing = false - vm.removeContact(uniqueId) - onBack() - }) { Text("Remove") } - }, - dismissButton = { TextButton(onClick = { removing = false }) { Text("Cancel") } }, - ) - } -} - -/** What a client starts out with when added as a friend, blocked or neutral. */ -@Composable -private fun ContactDefaultsScreen(vm: SessionController, onBack: () -> Unit) { - val defaults = vm.settings.contactDefaults - var tab by rememberSaveable { mutableStateOf(ContactType.FRIEND) } - var entry by remember(tab) { mutableStateOf(ContactDefaults.Entry().apply { copyFrom(defaults.of(tab)) }) } - fun edit(change: ContactDefaults.Entry.() -> Unit) { - val changed = ContactDefaults.Entry().apply { copyFrom(entry); change() } - defaults.of(tab).copyFrom(changed) - vm.settings.save() - entry = changed - } - - SubScreen("Defaults for new contacts", onBack) { padding -> - Column(Modifier.padding(padding)) { - PrimaryTabRow(selectedTabIndex = GROUPS.indexOfFirst { it.first == tab }) { - for ((type, title) in GROUPS) Tab(tab == type, onClick = { tab = type }, text = { Text(title) }) - } - Column(Modifier.verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { - Section("Show as") - Segments(DISPLAYS, entry.nicknameDisplay) { edit { nicknameDisplay = it } } - Section("Ignore") - Toggle("Mute", entry.automute) { edit { automute = it } } - Toggle("Ignore server and channel chat", entry.ignorePublicMessages) { edit { ignorePublicMessages = it } } - Toggle("Ignore private chat", entry.ignorePrivateMessages) { edit { ignorePrivateMessages = it } } - Toggle("Ignore pokes", entry.ignorePokes) { edit { ignorePokes = it } } - Toggle("Hide avatar", entry.ignoreAvatar) { edit { ignoreAvatar = it } } - Toggle("Hide away message", entry.ignoreAwayMessage) { edit { ignoreAwayMessage = it } } - Toggle("Deny whisper", entry.ignoreWhisper) { edit { ignoreWhisper = it } } - } - } - } -} - -private fun label(contact: Contact) = contact.nickname.ifBlank { contact.uniqueId } - -private fun lastSeen(contact: Contact): String { - val seen = contact.lastSeen ?: return "Never seen" - val where = contact.lastSeenServerName.ifBlank { contact.lastSeenServerAddress } - return "Last seen ${SEEN.format(seen)}" + if (where.isNotBlank()) " on $where" else "" -} - -private fun formatVolume(db: Float): String { - val rounded = db.roundToInt() - return if (rounded == 0) "Unchanged" else "${if (rounded > 0) "+" else ""}$rounded dB" -} - -private fun typeColor(type: ContactType): Color = when (type) { - ContactType.FRIEND -> StatusColors.friend - ContactType.BLOCKED -> StatusColors.blocked - ContactType.NEUTRAL -> Color.Unspecified -} diff --git a/android/app/src/main/java/com/ts3client/android/ui/DetailsSection.kt b/android/app/src/main/java/com/ts3client/android/ui/DetailsSection.kt deleted file mode 100644 index aa8e1c1..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/DetailsSection.kt +++ /dev/null @@ -1,137 +0,0 @@ -package com.ts3client.android.ui - -import androidx.compose.animation.animateContentSize -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.ExperimentalLayoutApi -import androidx.compose.foundation.layout.FlowRow -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberUpdatedState -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clipToBounds -import androidx.compose.ui.graphics.Brush -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.layout.Layout -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.Constraints -import androidx.compose.ui.unit.Dp -import androidx.compose.ui.unit.dp -import com.ts3client.net.Details -import com.ts3client.text.BBCode - -/** - * The facts of the server, a channel or a client, then its description, for the top of its sheet. - * The minor facts wait behind "more…". - */ -@Composable -fun DetailsSection(details: Details, onLink: (String) -> Unit, modifier: Modifier = Modifier) { - var all by rememberSaveable(details.title()) { mutableStateOf(false) } - val shown = if (all) details.fields() else details.fields().filterNot { it.minor() } - val more = !all && shown.size < details.fields().size - Column(modifier.padding(horizontal = 24.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { - if (shown.isNotEmpty() || more) { - Column(Modifier.animateContentSize(), verticalArrangement = Arrangement.spacedBy(2.dp)) { - for (field in shown) Fact(field) - if (more) { - Text("more…", Modifier.clickable { all = true }.padding(vertical = 2.dp), - style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary) - } - } - } - when { - details.description().isNotBlank() -> Description(details.description(), onLink) - details.pending() -> Text("Loading description…", style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant) - } - } -} - -@OptIn(ExperimentalLayoutApi::class) -@Composable -private fun Fact(field: Details.Field) { - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Text(field.label(), Modifier.width(96.dp), style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) - if (field.groups().isEmpty()) { - Text(field.value(), style = MaterialTheme.typography.bodySmall) - } else { - // Each group with its icon, as TeamSpeak's info frame lists them. - FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - // A nameless group shows only its icon, and takes no comma. - val lastNamed = field.groups().indexOfLast { it.name.isNotBlank() } - field.groups().forEachIndexed { i, group -> - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { - ServerIcon(group.iconId, size = 14.dp) - if (group.name.isNotBlank()) { - Text(group.name.trim() + if (i < lastNamed) "," else "", style = MaterialTheme.typography.bodySmall) - } - } - } - } - } - } -} - -/** The description in a box that opens up, when there is more of it than fits folded. */ -@Composable -private fun Description(bbcode: String, onLink: (String) -> Unit) { - val html = remember(bbcode) { BBCode.toHtml(bbcode, true) } - var expanded by rememberSaveable(bbcode) { mutableStateOf(false) } - var overflows by remember(bbcode) { mutableStateOf(false) } - val expandable = overflows || expanded - val background = MaterialTheme.colorScheme.surfaceContainerHigh - Surface( - Modifier.fillMaxWidth().then(if (expandable) Modifier.clickable { expanded = !expanded } else Modifier), - shape = RoundedCornerShape(12.dp), - color = background, - ) { - Column(Modifier.animateContentSize().padding(12.dp)) { - Box { - Folded(FOLDED_HEIGHT, expanded, onOverflow = { overflows = it }) { - RichText(html, onLink, style = MaterialTheme.typography.bodyMedium) - } - if (overflows && !expanded) { - Box(Modifier.align(Alignment.BottomCenter).fillMaxWidth().height(24.dp) - .background(Brush.verticalGradient(listOf(Color.Transparent, background)))) - } - } - if (expandable) { - Text(if (expanded) "Less" else "More", Modifier.padding(top = 4.dp), - style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary) - } - } - } -} - -/** Its content cut to [height] unless [open], telling whether there is more of it than that. */ -@Composable -private fun Folded(height: Dp, open: Boolean, onOverflow: (Boolean) -> Unit, content: @Composable () -> Unit) { - val report by rememberUpdatedState(onOverflow) - Layout(content, Modifier.clipToBounds()) { measurables, constraints -> - val placeable = measurables.first().measure(constraints.copy(maxHeight = Constraints.Infinity)) - val limit = height.roundToPx() - report(placeable.height > limit) - val shown = if (open) placeable.height else minOf(placeable.height, limit) - layout(placeable.width, shown) { placeable.place(0, 0) } - } -} - -private val FOLDED_HEIGHT = 128.dp diff --git a/android/app/src/main/java/com/ts3client/android/ui/FilesScreen.kt b/android/app/src/main/java/com/ts3client/android/ui/FilesScreen.kt deleted file mode 100644 index 47009ac..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/FilesScreen.kt +++ /dev/null @@ -1,239 +0,0 @@ -package com.ts3client.android.ui - -import android.text.format.DateUtils -import android.text.format.Formatter -import androidx.activity.compose.rememberLauncherForActivityResult -import androidx.activity.result.contract.ActivityResultContracts -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Close -import androidx.compose.material.icons.filled.MoreVert -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.DropdownMenu -import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.LinearProgressIndicator -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.SnackbarHostState -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import com.ts3client.android.ServerController -import com.ts3client.android.TransferRow -import com.ts3client.net.filetransfer.FileTransfer -import com.ts3client.net.filetransfer.RemoteFile -import kotlinx.coroutines.launch - -/** A channel's file repository: folders to walk, files to download, upload, rename and delete. */ -@Composable -fun FilesScreen(server: ServerController, channelId: Int, channelName: String, password: String, onBack: () -> Unit) { - val scope = rememberCoroutineScope() - val snackbar = remember { SnackbarHostState() } - var path by rememberSaveable { mutableStateOf("/") } - var files by remember { mutableStateOf?>(null) } - var failure by remember { mutableStateOf(null) } - var reloads by remember { mutableIntStateOf(0) } - val transfers by server.files.rows.collectAsStateWithLifecycle() - var downloading by remember { mutableStateOf(null) } - var creatingFolder by remember { mutableStateOf(false) } - var renaming by remember { mutableStateOf(null) } - var deleting by remember { mutableStateOf(null) } - - LaunchedEffect(path, reloads) { - failure = null - server.listFiles(channelId, password, path) - .onSuccess { list -> files = list.sortedWith(compareBy({ !it.isDirectory }, { it.name.lowercase() })) } - .onFailure { files = emptyList(); failure = it.message ?: "Could not list the files" } - } - // An upload into the folder on screen shows up once it is there. - val uploadedHere = transfers.count { it.upload && it.channelId == channelId && it.directory == path && it.state == FileTransfer.State.COMPLETED } - LaunchedEffect(uploadedHere) { if (uploadedHere > 0) reloads++ } - - val tell = { message: String -> scope.launch { snackbar.showSnackbar(message) }; Unit } - val act = { call: suspend () -> String? -> - scope.launch { - val error = call() - if (error != null) snackbar.showSnackbar(error) else reloads++ - } - Unit - } - - val saver = rememberLauncherForActivityResult(SaveAs) { uri -> - val file = downloading - downloading = null - if (uri != null && file != null) server.files.download(channelId, password, file, uri) - } - val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> - if (uri != null) scope.launch { - runCatching { server.files.upload(channelId, password, path, uri) } - .onFailure { tell("Could not read the file: ${it.message}") } - } - } - - SubScreen(channelName, onBack = { if (path == "/") onBack() else path = parentOf(path) }, snackbar = snackbar, actions = { - IconButton(onClick = { creatingFolder = true }) { PackIcon("ADD_FOLDER", "New folder") } - IconButton(onClick = { picker.launch(arrayOf("*/*")) }) { PackIcon("UPLOAD", "Upload") } - IconButton(onClick = { reloads++ }) { PackIcon(listOf("FILE_REFRESH", "REFRESH"), "Refresh") } - }) { padding -> - Column(Modifier.padding(padding).fillMaxSize()) { - Row(Modifier.fillMaxWidth().padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically) { - IconButton(onClick = { path = parentOf(path) }, enabled = path != "/") { PackIcon("FILE_UP", "Up") } - Text(path, Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis, - style = MaterialTheme.typography.bodyMedium) - } - HorizontalDivider() - Box(Modifier.weight(1f).fillMaxWidth()) { - val list = files - when { - list == null -> CircularProgressIndicator(Modifier.align(Alignment.Center)) - list.isEmpty() -> Text(failure ?: "No files", Modifier.align(Alignment.Center).padding(24.dp), - color = if (failure != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant) - else -> LazyColumn { - items(list, key = { it.fullPath }) { file -> - FileRow(file, - onOpen = { - if (file.isDirectory) path = file.fullPath + "/" - else { downloading = file; saver.launch(file.name) } - }, - onRename = { renaming = file }, - onDelete = { deleting = file }) - } - } - } - } - if (transfers.isNotEmpty()) Transfers(transfers, server.files::cancel, server.files::clearFinished) - } - } - - if (creatingFolder) { - TextPrompt("New folder", "Name", "Create", onDismiss = { creatingFolder = false }, onConfirm = { name -> - creatingFolder = false - if (name.isNotBlank()) act { server.createDirectory(channelId, password, path + name.trim()) } - }) - } - renaming?.let { file -> - TextPrompt("Rename", "Name", "Rename", initial = file.name, onDismiss = { renaming = null }, onConfirm = { name -> - renaming = null - if (name.isNotBlank() && name != file.name) { - act { server.renameFile(channelId, password, file.fullPath, file.parentPath + name.trim()) } - } - }) - } - deleting?.let { file -> - AlertDialog( - onDismissRequest = { deleting = null }, - title = { Text("Delete ${file.name}?") }, - text = if (file.isDirectory) ({ Text("Everything in the folder goes with it.") }) else null, - confirmButton = { - TextButton(onClick = { - deleting = null - act { server.deleteFile(channelId, password, file.fullPath) } - }) { Text("Delete") } - }, - dismissButton = { TextButton(onClick = { deleting = null }) { Text("Cancel") } }, - ) - } -} - -private fun parentOf(path: String): String { - val trimmed = path.removeSuffix("/") - val slash = trimmed.lastIndexOf('/') - return if (slash <= 0) "/" else trimmed.substring(0, slash + 1) -} - -@Composable -private fun FileRow(file: RemoteFile, onOpen: () -> Unit, onRename: () -> Unit, onDelete: () -> Unit) { - val context = LocalContext.current - var menu by remember { mutableStateOf(false) } - val modified = if (file.lastModifiedEpochSec > 0) { - DateUtils.formatDateTime(context, file.lastModifiedEpochSec * 1000, - DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_ABBREV_MONTH) - } else null - ListItem( - headlineContent = { Text(file.name, maxLines = 1, overflow = TextOverflow.Ellipsis) }, - supportingContent = { - Text(listOfNotNull(if (file.isDirectory) null else Formatter.formatShortFileSize(context, file.size), modified) - .joinToString(" · ")) - }, - leadingContent = { PackIcon(if (file.isDirectory) listOf("FOLDER") else listOf("FILE", "FILETRANSFER"), null) }, - trailingContent = { - Box { - IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "File options") } - DropdownMenu(menu, { menu = false }) { - if (!file.isDirectory) DropdownMenuItem({ Text("Download") }, onClick = { menu = false; onOpen() }) - DropdownMenuItem({ Text("Rename") }, onClick = { menu = false; onRename() }) - DropdownMenuItem({ Text("Delete") }, onClick = { menu = false; onDelete() }) - } - } - }, - modifier = Modifier.clickable(onClick = onOpen), - ) -} - -/** The transfers under way and done, newest last. */ -@Composable -private fun Transfers(rows: List, onCancel: (Long) -> Unit, onClear: () -> Unit) { - val context = LocalContext.current - Surface(tonalElevation = 3.dp) { - Column(Modifier.fillMaxWidth().heightIn(max = 220.dp)) { - Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) { - Text("Transfers", Modifier.weight(1f), style = MaterialTheme.typography.titleSmall) - if (rows.any { it.done }) TextButton(onClick = onClear) { Text("Clear finished") } - } - LazyColumn { - items(rows, key = { it.id }) { row -> - Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 4.dp, bottom = 4.dp), - verticalAlignment = Alignment.CenterVertically) { - PackIcon(if (row.upload) "UPLOAD" else "DOWNLOAD", null) - Column(Modifier.weight(1f).padding(horizontal = 12.dp)) { - Text(row.name, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium) - when (row.state) { - FileTransfer.State.PENDING, FileTransfer.State.ACTIVE -> - LinearProgressIndicator({ row.progress }, Modifier.fillMaxWidth().padding(vertical = 4.dp)) - else -> Text(status(row, context), style = MaterialTheme.typography.bodySmall, - color = if (row.state == FileTransfer.State.FAILED) MaterialTheme.colorScheme.error - else MaterialTheme.colorScheme.onSurfaceVariant) - } - } - if (!row.done) IconButton(onClick = { onCancel(row.id) }) { Icon(Icons.Default.Close, "Cancel") } - } - } - } - } - } -} - -private fun status(row: TransferRow, context: android.content.Context): String = when (row.state) { - FileTransfer.State.COMPLETED -> (if (row.upload) "Uploaded" else "Downloaded") + " · " + - Formatter.formatShortFileSize(context, row.total) - FileTransfer.State.CANCELLED -> "Cancelled" - else -> row.error ?: "Failed" -} diff --git a/android/app/src/main/java/com/ts3client/android/ui/FindBar.kt b/android/app/src/main/java/com/ts3client/android/ui/FindBar.kt deleted file mode 100644 index a645159..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/FindBar.kt +++ /dev/null @@ -1,190 +0,0 @@ -package com.ts3client.android.ui - -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.text.KeyboardActions -import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.ArrowBack -import androidx.compose.material.icons.filled.Close -import androidx.compose.material.icons.filled.KeyboardArrowDown -import androidx.compose.material.icons.filled.KeyboardArrowUp -import androidx.compose.material.icons.filled.MoreVert -import androidx.compose.material3.Checkbox -import androidx.compose.material3.DropdownMenu -import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.material3.TextField -import androidx.compose.material3.TextFieldDefaults -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.Stable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.listSaver -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.focus.FocusRequester -import androidx.compose.ui.focus.focusRequester -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.input.key.Key -import androidx.compose.ui.input.key.KeyEventType -import androidx.compose.ui.input.key.isShiftPressed -import androidx.compose.ui.input.key.key -import androidx.compose.ui.input.key.onPreviewKeyEvent -import androidx.compose.ui.input.key.type -import androidx.compose.ui.text.TextRange -import androidx.compose.ui.text.input.ImeAction -import androidx.compose.ui.text.input.TextFieldValue -import androidx.compose.ui.unit.dp -import com.ts3client.gfx.IconKeys -import com.ts3client.net.ClientStatus -import com.ts3client.text.TextQuery - -/** What the find bar holds: the text, how to match it, and whether it is [open]. */ -@Stable -class FindState(text: String = "", flags: Int = 0) { - var open by mutableStateOf(false) - var input by mutableStateOf(TextFieldValue(text)) - var matchCase by mutableStateOf(flags and 1 != 0) - var wholeWord by mutableStateOf(flags and 2 != 0) - var regex by mutableStateOf(flags and 4 != 0) - /** Counts the times it was asked to show, for the field to take the focus each time. */ - var shown by mutableStateOf(0) - private set - /** Show only what matches. */ - var filter by mutableStateOf(flags and 8 != 0) - /** In the tree, find channels rather than clients. */ - var channels by mutableStateOf(flags and 16 != 0) - - /** What is typed, as it is to be matched; empty while the bar is closed. */ - val query: TextQuery - get() = if (open) TextQuery(input.text, matchCase, wholeWord, regex) else TextQuery.EMPTY - - /** [query], but nothing when it is not a valid regular expression. */ - val usable: TextQuery - get() = query.let { if (it.isInvalid) TextQuery.EMPTY else it } - - /** Opens the bar with what it holds selected, to be typed over. */ - fun show() { - input = input.copy(selection = TextRange(0, input.text.length)) - open = true - shown++ - } - - companion object { - val Saver = listSaver( - save = { - val flags = (if (it.matchCase) 1 else 0) or (if (it.wholeWord) 2 else 0) or (if (it.regex) 4 else 0) or - (if (it.filter) 8 else 0) or (if (it.channels) 16 else 0) - listOf(it.input.text, flags, it.open) - }, - restore = { FindState(it[0] as String, it[1] as Int).apply { open = it[2] as Boolean } }, - ) - } -} - -/** - * The find bar, in the place of the top bar: the field, where the view is among the matches, - * previous/next, and the options. Enter goes to the next match, Shift+Enter to the previous. - * - * @param inTree whether it finds in the tree, which offers finding channels instead of clients - * @param position the 1-based match the view is on, or 0 for none - * @param more whether there are more matches than [total] - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun FindBar(state: FindState, inTree: Boolean, position: Int, total: Int, more: Boolean, onStep: (Int) -> Unit) { - val focus = remember { FocusRequester() } - LaunchedEffect(state.shown) { focus.requestFocus() } - val query = state.query - TopAppBar( - expandedHeight = 48.dp, - navigationIcon = { IconButton(onClick = { state.open = false }) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Close") } }, - title = { - TextField( - state.input, { state.input = it }, - Modifier.focusRequester(focus).onPreviewKeyEvent { e -> - when { - e.key == Key.Enter -> { - if (e.type == KeyEventType.KeyDown) onStep(if (e.isShiftPressed) -1 else 1) - true - } - e.key == Key.Escape && e.type == KeyEventType.KeyDown -> { - state.open = false - true - } - else -> false - } - }, - placeholder = { - Text(if (!inTree) "Find" else if (state.channels) "Find channels" else "Find clients", maxLines = 1) - }, - leadingIcon = if (inTree) ({ - IconButton(onClick = { state.channels = !state.channels }) { - if (state.channels) PackIcon(IconKeys.channel(false, false, true).asList(), "Finding channels", size = 18.dp) - else PackIcon(IconKeys.client(ClientStatus.IDLE), "Finding clients", size = 18.dp) - } - }) else null, - trailingIcon = if (state.input.text.isNotEmpty()) ({ - IconButton(onClick = { state.input = TextFieldValue() }) { Icon(Icons.Filled.Close, "Clear", Modifier.size(18.dp)) } - }) else null, - isError = query.isInvalid, - singleLine = true, - textStyle = MaterialTheme.typography.bodyLarge, - keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), - keyboardActions = KeyboardActions(onSearch = { onStep(1) }), - colors = TextFieldDefaults.colors( - focusedContainerColor = Color.Transparent, - unfocusedContainerColor = Color.Transparent, - errorContainerColor = Color.Transparent, - focusedIndicatorColor = Color.Transparent, - unfocusedIndicatorColor = Color.Transparent, - ), - ) - }, - actions = { - Row(verticalAlignment = Alignment.CenterVertically) { - if (!query.isEmpty) { - Text( - if (query.isInvalid) "!" else "${if (position > 0) "$position/" else ""}$total${if (more) "+" else ""}", - Modifier.padding(horizontal = 4.dp), - color = if (query.isInvalid || total == 0) MaterialTheme.colorScheme.error - else MaterialTheme.colorScheme.onSurfaceVariant, - style = MaterialTheme.typography.labelMedium, - ) - } - val navigable = total > 1 || (total == 1 && position == 0) - IconButton(onClick = { onStep(-1) }, enabled = navigable) { Icon(Icons.Filled.KeyboardArrowUp, "Previous") } - IconButton(onClick = { onStep(1) }, enabled = navigable) { Icon(Icons.Filled.KeyboardArrowDown, "Next") } - FindOptions(state) - } - }, - ) -} - -@Composable -private fun FindOptions(state: FindState) { - var open by remember { mutableStateOf(false) } - IconButton(onClick = { open = true }) { Icon(Icons.Filled.MoreVert, "Options") } - DropdownMenu(open, onDismissRequest = { open = false }) { - @Composable - fun option(label: String, checked: Boolean, set: (Boolean) -> Unit) = DropdownMenuItem( - text = { Text(label) }, - onClick = { set(!checked) }, - leadingIcon = { Checkbox(checked, set) }, - ) - option("Only matches", state.filter) { state.filter = it } - option("Match case", state.matchCase) { state.matchCase = it } - option("Whole words", state.wholeWord) { state.wholeWord = it } - option("Regular expression", state.regex) { state.regex = it } - } -} diff --git a/android/app/src/main/java/com/ts3client/android/ui/HostButton.kt b/android/app/src/main/java/com/ts3client/android/ui/HostButton.kt deleted file mode 100644 index 970ff2d..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/HostButton.kt +++ /dev/null @@ -1,64 +0,0 @@ -package com.ts3client.android.ui - -import androidx.compose.foundation.Image -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.aspectRatio -import androidx.compose.foundation.layout.fillMaxHeight -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.widthIn -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.produceState -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.unit.dp -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import com.ts3client.android.Picture -import com.ts3client.android.WebPictures -import com.ts3client.net.HostButton - -/** - * The server's host button in the top bar: its own picture fitted to the bar's icons, or - * the pack's host button icon while there is none (yet). - */ -@Composable -fun HostButtonAction(button: HostButton, onOpen: (String) -> Unit) { - val label = button.tooltip.ifEmpty { button.url }.ifEmpty { null } - val picture = hostPicture(button.gfxUrl) - Box( - Modifier - .fillMaxHeight() - .clickable(enabled = button.url.isNotEmpty()) { onOpen(button.url) } - .padding(horizontal = 12.dp), - contentAlignment = Alignment.Center, - ) { - if (picture == null) { - PackIcon("HOSTER_BUTTON", label) - } else { - Image( - rememberPicturePainter(picture), - label, - Modifier - .widthIn(max = 24.dp * MAX_ASPECT) - .height(24.dp) - .aspectRatio(picture.width.toFloat() / picture.height.coerceAtLeast(1)), - ) - } - } -} - -@Composable -private fun hostPicture(url: String): Picture? { - val pictures = LocalWebPictures.current - if (pictures == null || url.isEmpty()) return null - val version by pictures.version.collectAsStateWithLifecycle() - val state by produceState(WebPictures.State.Loading, url, version) { - value = pictures.state(url) - } - return (state as? WebPictures.State.Shown)?.picture -} - -/** Keeps a banner-shaped picture from crowding out the server's name. */ -private const val MAX_ASPECT = 6 diff --git a/android/app/src/main/java/com/ts3client/android/ui/IdentitiesScreen.kt b/android/app/src/main/java/com/ts3client/android/ui/IdentitiesScreen.kt deleted file mode 100644 index 600d093..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/IdentitiesScreen.kt +++ /dev/null @@ -1,282 +0,0 @@ -package com.ts3client.android.ui - -import android.content.ClipData -import android.content.ClipboardManager -import androidx.activity.compose.rememberLauncherForActivityResult -import androidx.activity.result.contract.ActivityResultContracts -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.foundation.verticalScroll -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.MoreVert -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.DropdownMenu -import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.LinearProgressIndicator -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.text.input.KeyboardType -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import com.ts3client.android.IdentityInfo -import com.ts3client.android.IdentityManager -import kotlinx.coroutines.launch - -/** Beyond this a search takes years; TeamSpeak's own dialog stops there too. */ -private const val MAX_SECURITY_LEVEL = 40 - -/** - * The identities a server knows this client by, as TeamSpeak's Tools → Identities - * manages them, with each identity's own page. - */ -@Composable -fun IdentitiesScreen(manager: IdentityManager, onBack: () -> Unit) { - var editing by rememberSaveable { mutableStateOf(null) } - editing?.let { id -> return IdentityScreen(manager, id, onBack = { editing = null }) } - - val identities by manager.all.collectAsStateWithLifecycle() - val scope = rememberCoroutineScope() - var menu by remember { mutableStateOf(false) } - var creating by remember { mutableStateOf(false) } - var busy by remember { mutableStateOf(false) } - var message by remember { mutableStateOf(null) } - - fun work(failure: String, block: suspend () -> String?) { - busy = true - scope.launch { - message = try { - block() - } catch (e: Exception) { - "$failure: ${e.message ?: e}" - } - busy = false - } - } - - val fileImporter = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> - if (uri != null) work("That file is not a TeamSpeak identity") { - editing = manager.importFile(uri).id - null - } - } - val dbImporter = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> - if (uri != null) work("That file is not a TeamSpeak 3 settings.db") { - val r = manager.importFromTeamSpeak(uri) - if (r.identities() == 0) "That file holds no identities." - else "Imported ${r.identitiesAdded()} of ${r.identities()} identities." - } - } - - SubScreen("Identities", onBack, actions = { - IconButton(onClick = { creating = true }, enabled = !busy) { PackIcon("IDENTITY_ADD", "New identity") } - Box { - IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "More") } - DropdownMenu(menu, { menu = false }) { - DropdownMenuItem({ Text("Import identity file") }, onClick = { - menu = false - fileImporter.launch(arrayOf("*/*")) - }) - DropdownMenuItem({ Text("Import from TeamSpeak 3") }, onClick = { - menu = false - dbImporter.launch(arrayOf("*/*")) - }) - } - } - }) { padding -> - LazyColumn(Modifier.padding(padding)) { - if (busy) item { LinearProgressIndicator(Modifier.fillMaxWidth().padding(horizontal = 16.dp)) } - message?.let { item { Hint(it) } } - if (identities.isEmpty()) { - item { - Hint("No identities. One is created on the first connect.") - } - } - items(identities, key = { it.id }) { identity -> - ListItem( - headlineContent = { Text(identity.name, maxLines = 1, overflow = TextOverflow.Ellipsis) }, - supportingContent = { - Text("Security level ${identity.securityLevel}", maxLines = 1) - }, - trailingContent = if (identity.isDefault) ({ PackIcon("IDENTITY_DEFAULT", "Default") }) else null, - modifier = Modifier.clickable { editing = identity.id }, - ) - } - } - } - - if (creating) { - NewIdentityDialog(onDismiss = { creating = false }) { name -> - creating = false - work("Could not create the identity") { - editing = manager.generate(name).id - null - } - } - } -} - -/** One identity: its name, whether it is the default, its security level and unique ID. */ -@Composable -private fun IdentityScreen(manager: IdentityManager, id: String, onBack: () -> Unit) { - val identities by manager.all.collectAsStateWithLifecycle() - val improving by manager.improving.collectAsStateWithLifecycle() - val identity = identities.firstOrNull { it.id == id } - if (identity == null) { - LaunchedEffect(Unit) { onBack() } - return - } - val scope = rememberCoroutineScope() - var name by rememberSaveable(id) { mutableStateOf(identity.name) } - var nickname by rememberSaveable(id) { mutableStateOf(identity.nickname) } - var phonetic by rememberSaveable(id) { mutableStateOf(identity.phoneticNickname) } - var removing by remember { mutableStateOf(false) } - var raising by remember { mutableStateOf(false) } - var message by remember { mutableStateOf(null) } - val leave = { - val trimmed = name.trim() - if (trimmed.isNotEmpty() && trimmed != identity.name) manager.rename(id, trimmed) - if (nickname.trim() != identity.nickname || phonetic.trim() != identity.phoneticNickname) { - manager.setNicknames(id, nickname.trim(), phonetic.trim()) - } - onBack() - } - val exporter = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/octet-stream")) { uri -> - if (uri != null) scope.launch { - message = runCatching { manager.export(id, uri) }.fold( - { "Exported." }, - { "Could not export: ${it.message ?: it}" }, - ) - } - } - val mine = improving?.takeIf { it.id == id } - - SubScreen(identity.name, leave, actions = { - IconButton(onClick = { exporter.launch(fileName(name.ifBlank { identity.name })) }) { - PackIcon("IDENTITY_EXPORT", "Export") - } - IconButton(onClick = { removing = true }) { PackIcon("DELETE", "Remove") } - }) { padding -> - Column(Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(vertical = 8.dp)) { - OutlinedTextField(name, { name = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp), - label = { Text("Name") }, singleLine = true, isError = name.isBlank()) - OutlinedTextField(nickname, { nickname = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(top = 8.dp), - label = { Text("Nickname") }, placeholder = { Text("Global nickname") }, singleLine = true) - OutlinedTextField(phonetic, { phonetic = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), - label = { Text("Phonetic nickname") }, singleLine = true) - message?.let { Hint(it) } - - Section("Use") - if (identity.isDefault) { - Hint("Default identity") - } else { - LinkRow("Make default", null, "IDENTITY_DEFAULT") { - manager.setDefault(id) - } - } - - Section("Security level") - if (mine != null) { - ListItem( - headlineContent = { Text("Improving to ${mine.target}: reached ${mine.reached}") }, - supportingContent = { LinearProgressIndicator(Modifier.fillMaxWidth().padding(top = 8.dp)) }, - trailingContent = { TextButton(onClick = manager::stopImproving) { Text("Stop") } }, - ) - } else { - LinkRow("Level ${identity.securityLevel}", - if (improving != null) "Another identity is being improved" else "Improve", - "SECURITY") { if (improving == null) raising = true } - } - - Section("Details") - val context = LocalContext.current - LinkRow("Unique ID", identity.uniqueId) { - // The system confirms the copy itself. - context.getSystemService(ClipboardManager::class.java) - .setPrimaryClip(ClipData.newPlainText("Unique ID", identity.uniqueId)) - } - } - } - - if (raising) { - LevelDialog(identity, onDismiss = { raising = false }) { target -> - raising = false - manager.improve(id, target) - } - } - if (removing) { - AlertDialog( - onDismissRequest = { removing = false }, - title = { Text("Remove ${identity.name}?") }, - text = { - Text("Server groups and permissions tied to it are lost. Export it first to keep it.") - }, - confirmButton = { - TextButton(onClick = { - removing = false - manager.remove(id) - }) { Text("Remove") } - }, - dismissButton = { TextButton(onClick = { removing = false }) { Text("Cancel") } }, - ) - } -} - -@Composable -private fun NewIdentityDialog(onDismiss: () -> Unit, onConfirm: (String) -> Unit) { - var name by remember { mutableStateOf("") } - AlertDialog( - onDismissRequest = onDismiss, - title = { Text("New identity") }, - text = { - OutlinedTextField(name, { name = it }, Modifier.fillMaxWidth(), label = { Text("Name") }, singleLine = true) - }, - confirmButton = { TextButton(onClick = { onConfirm(name.trim()) }, enabled = name.isNotBlank()) { Text("Create") } }, - dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, - ) -} - -@Composable -private fun LevelDialog(identity: IdentityInfo, onDismiss: () -> Unit, onConfirm: (Int) -> Unit) { - var text by remember { mutableStateOf((identity.securityLevel + 1).toString()) } - val level = text.trim().toIntOrNull()?.takeIf { it in identity.securityLevel + 1..MAX_SECURITY_LEVEL } - AlertDialog( - onDismissRequest = onDismiss, - title = { Text("Improve security level") }, - text = { - Column { - Text("Current level: ${identity.securityLevel}", style = MaterialTheme.typography.bodyMedium) - OutlinedTextField(text, { text = it }, Modifier.fillMaxWidth().padding(top = 8.dp), - label = { Text("Target level") }, singleLine = true, isError = level == null, - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)) - } - }, - confirmButton = { TextButton(onClick = { level?.let(onConfirm) }, enabled = level != null) { Text("Start") } }, - dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, - ) -} - -private fun fileName(name: String) = name.replace(Regex("[^\\w.-]+"), "_") + ".ini" diff --git a/android/app/src/main/java/com/ts3client/android/ui/Moderation.kt b/android/app/src/main/java/com/ts3client/android/ui/Moderation.kt deleted file mode 100644 index a9bc625..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/Moderation.kt +++ /dev/null @@ -1,225 +0,0 @@ -package com.ts3client.android.ui - -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.Checkbox -import androidx.compose.material3.DropdownMenu -import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.RadioButton -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.alpha -import androidx.compose.ui.text.input.KeyboardType -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import com.ts3client.android.ClientItem -import com.ts3client.android.ServerController -import com.ts3client.net.GroupChoice -import com.ts3client.net.TeamspeakConnection -import com.ts3client.net.ban.BanRule -import com.ts3client.net.ban.BanUnit - -/** Asks to confirm a kick, with an optional reason. */ -@Composable -fun KickPrompt(title: String, onDismiss: () -> Unit, onKick: (String) -> Unit) { - var reason by remember { mutableStateOf("") } - AlertDialog( - onDismissRequest = onDismiss, - title = { Text(title) }, - text = { LimitedField(reason, { reason = it }, "Reason", TeamspeakConnection.KICK_REASON_LIMIT) }, - confirmButton = { TextButton(onClick = { onKick(reason.trim()) }) { Text("Kick") } }, - dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, - ) -} - -/** Asks for a ban's reason and length. */ -@Composable -fun BanPrompt(name: String, maxSeconds: Long, onDismiss: () -> Unit, onBan: (seconds: Long, reason: String) -> Unit) { - var reason by remember { mutableStateOf("") } - val duration = remember { BanDurationState(DEFAULT_BAN_SECONDS) } - AlertDialog( - onDismissRequest = onDismiss, - title = { Text("Ban $name") }, - text = { - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - LimitedField(reason, { reason = it }, "Reason", BanRule.REASON_LIMIT) - BanDurationField(duration, maxSeconds) - } - }, - confirmButton = { - TextButton(onClick = { onBan(duration.seconds, reason.trim()) }, enabled = duration.valid) { Text("Ban") } - }, - dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, - ) -} - -/** Thirty minutes, as the official client starts its ban dialog. */ -internal const val DEFAULT_BAN_SECONDS = 30 * 60L - -/** A one-line field that takes no more than [limit] characters, counting them as they come. */ -@Composable -internal fun LimitedField(value: String, onChange: (String) -> Unit, label: String, limit: Int, modifier: Modifier = Modifier) { - OutlinedTextField( - value, { onChange(it.take(limit)) }, - modifier.fillMaxWidth(), - label = { Text(label) }, - singleLine = true, - supportingText = { Text("${value.length}/$limit", Modifier.fillMaxWidth(), textAlign = TextAlign.End) }, - ) -} - -/** A ban's length as typed: an amount of a [BanUnit]. */ -internal class BanDurationState(seconds: Long) { - var unit by mutableStateOf(BanUnit.largestFor(seconds)) - var amount by mutableStateOf(BanUnit.largestFor(seconds).amountOf(seconds).takeIf { it > 0 }?.toString() ?: "30") - - val valid: Boolean get() = unit == BanUnit.PERMANENT || (amount.toLongOrNull() ?: 0) > 0 - - /** The length in seconds; 0 for permanent. */ - val seconds: Long get() = unit.toSeconds(amount.toLongOrNull() ?: 0) - - fun set(seconds: Long) { - unit = BanUnit.largestFor(seconds) - if (unit != BanUnit.PERMANENT) amount = unit.amountOf(seconds).toString() - } -} - -/** The amount, its unit, and a jump to the longest ban the server lets us hand out. */ -@Composable -internal fun BanDurationField(state: BanDurationState, maxSeconds: Long, modifier: Modifier = Modifier) { - var units by remember { mutableStateOf(false) } - Row(modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { - OutlinedTextField( - if (state.unit == BanUnit.PERMANENT) "" else state.amount, - { text -> state.amount = text.filter(Char::isDigit).take(9) }, - Modifier.width(120.dp), - enabled = state.unit != BanUnit.PERMANENT, - label = { Text("Duration") }, - singleLine = true, - isError = !state.valid, - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), - ) - Box(Modifier.weight(1f)) { - OutlinedButton(onClick = { units = true }, Modifier.fillMaxWidth()) { Text(state.unit.label()) } - DropdownMenu(units, { units = false }) { - for (unit in BanUnit.entries) { - DropdownMenuItem({ Text(unit.label()) }, onClick = { units = false; state.unit = unit }) - } - } - } - if (maxSeconds != 0L) TextButton(onClick = { state.set(maxSeconds) }) { Text("Max") } - } -} - -/** - * A client's groups to tick: several server groups, or with [single] the one channel group. - * Groups we have no power over show greyed out; a change shows once the server made it. - */ -@Composable -fun GroupsDialog( - title: String, - choices: List, - single: Boolean, - onDismiss: () -> Unit, - onChange: (groupId: Int, assign: Boolean) -> Unit, -) { - AlertDialog( - onDismissRequest = onDismiss, - title = { Text(title) }, - text = { - LazyColumn { - items(choices, key = { it.group().id }) { choice -> - val group = choice.group() - // A client always has one channel group: picking another is the only change. - val changeable = choice.allowed() && !(single && choice.assigned()) - val toggle = { if (changeable) onChange(group.id, !choice.assigned()) } - Row( - Modifier.fillMaxWidth() - .clickable(enabled = changeable, onClick = toggle) - .alpha(if (choice.allowed()) 1f else 0.38f) - .padding(vertical = 2.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - if (single) { - RadioButton(choice.assigned(), onClick = toggle, enabled = choice.allowed()) - } else { - Checkbox(choice.assigned(), onCheckedChange = { toggle() }, enabled = choice.allowed()) - } - Box(Modifier.width(24.dp), contentAlignment = Alignment.Center) { - if (group.iconId != 0L) ServerIcon(group.iconId) - } - Text(group.name, Modifier.padding(start = 8.dp)) - } - } - } - }, - confirmButton = { TextButton(onClick = onDismiss) { Text("Close") } }, - ) -} - -/** The kicks, the ban and the groups of [client], as far as we may use them; [onDone] once one went out. */ -@Composable -fun ClientModeration(server: ServerController, client: ClientItem, onDone: () -> Unit) { - var kick by remember { mutableStateOf(null) } - var banning by remember { mutableStateOf(false) } - var groups by remember { mutableStateOf(null) } - val serverGroups = remember(client) { server.serverGroupChoices(client.id) } - val channelGroups = remember(client) { server.channelGroupChoices(client.id) } - - if (!client.self) { - if (server.canKickFromChannel) Action("KICK_FROM_CHANNEL", "Kick from channel") { kick = false } - if (server.canKickFromServer) Action("KICK_FROM_SERVER", "Kick from server") { kick = true } - if (server.canBanClients) Action("BAN_CLIENT", "Ban") { banning = true } - } - if (serverGroups.any { it.allowed() }) Action("PERMISSIONS_SERVER_GROUPS", "Server groups") { groups = true } - if (channelGroups.any { it.allowed() && !it.assigned() }) { - Action("PERMISSIONS_CHANNEL_GROUPS", "Channel group") { groups = false } - } - - kick?.let { fromServer -> - KickPrompt( - if (fromServer) "Kick ${client.name} from the server?" else "Kick ${client.name} from the channel?", - onDismiss = { kick = null }, - ) { reason -> - kick = null - if (fromServer) server.kickFromServer(client.id, reason) else server.kickFromChannel(client.id, reason) - onDone() - } - } - if (banning) { - BanPrompt(client.name, server.maxBanSeconds, onDismiss = { banning = false }) { seconds, reason -> - banning = false - server.ban(client.id, seconds, reason) - onDone() - } - } - groups?.let { ofServer -> - GroupsDialog( - if (ofServer) "Server groups" else "Channel group", - if (ofServer) serverGroups else channelGroups, - single = !ofServer, - onDismiss = { groups = null }, - ) { groupId, assign -> - if (ofServer) server.setServerGroup(client.id, groupId, assign) else server.setChannelGroup(client.id, groupId) - } - } -} diff --git a/android/app/src/main/java/com/ts3client/android/ui/MyTeamSpeakScreen.kt b/android/app/src/main/java/com/ts3client/android/ui/MyTeamSpeakScreen.kt deleted file mode 100644 index 9f42cd6..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/MyTeamSpeakScreen.kt +++ /dev/null @@ -1,247 +0,0 @@ -package com.ts3client.android.ui - -import androidx.activity.compose.BackHandler -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.PaddingValues -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.foundation.text.selection.SelectionContainer -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.ArrowBack -import androidx.compose.material3.Button -import androidx.compose.material3.Checkbox -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.LinearProgressIndicator -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.input.KeyboardType -import androidx.compose.ui.text.input.PasswordVisualTransformation -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import com.ts3client.android.SessionController -import com.ts3client.myts.AccountInfo -import com.ts3client.myts.MyTeamSpeak -import com.ts3client.myts.MyTsException -import com.ts3client.teamspeak.SyncItem -import kotlinx.coroutines.launch -import java.io.IOException -import java.time.ZoneId -import java.time.format.DateTimeFormatter -import java.time.format.FormatStyle - -private data class ItemRow(val item: SyncItem, val imported: Boolean, val selected: Boolean) - -/** - * The myTeamSpeak account: sign in and out, and pick what the account synchronises to - * import. Signing in lasts until signing out; the password itself is not kept. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) { - val login = vm.myTeamSpeak - val scope = rememberCoroutineScope() - var signedIn by remember { mutableStateOf(login.isSignedIn) } - var busy by remember { mutableStateOf(false) } - var message by remember { mutableStateOf(null) } - var error by remember { mutableStateOf(false) } - var email by remember { mutableStateOf("") } - var password by remember { mutableStateOf("") } - var info by remember { mutableStateOf(null) } - var all by remember { mutableStateOf(emptyList()) } - var rows by remember { mutableStateOf(emptyList()) } - BackHandler(onBack = onBack) - - fun show(account: MyTeamSpeak.Account) { - info = account.info() - all = account.items() - rows = all.filter { it !is SyncItem.Folder }.map { - val imported = vm.isImported(it) - ItemRow(it, imported, !imported) - } - message = if (rows.isEmpty()) "The account holds no bookmarks or identities." else null - error = false - } - - fun work(block: suspend () -> Unit) { - busy = true - message = null - scope.launch { - try { - block() - } catch (e: MyTsException) { - message = e.message - error = true - } catch (e: IOException) { - message = "Could not reach myTeamSpeak: ${e.message}" - error = true - } - // A sign-in the server no longer takes has signed out. - signedIn = login.isSignedIn - busy = false - } - } - - LaunchedEffect(Unit) { - if (signedIn) work { show(vm.fetchMyTeamSpeak()) } - } - - Scaffold( - topBar = { - TopAppBar( - title = { Text("myTeamSpeak") }, - navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } }, - actions = { - if (signedIn) { - IconButton(onClick = { work { show(vm.fetchMyTeamSpeak()) } }, enabled = !busy) { - PackIcon("REFRESH", "Refresh") - } - } - }, - ) - }, - ) { padding -> - LazyColumn( - Modifier.padding(padding).imePadding(), - contentPadding = PaddingValues(vertical = 8.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - if (busy) item { LinearProgressIndicator(Modifier.fillMaxWidth().padding(horizontal = 16.dp)) } - if (!signedIn) { - item { - Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { - Text("Sign in to bring over the bookmarks and identities your account synchronises. " + - "The app stays signed in; your password itself is not kept.") - OutlinedTextField(email, { email = it }, Modifier.fillMaxWidth(), label = { Text("Email") }, - singleLine = true, enabled = !busy, - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email)) - OutlinedTextField(password, { password = it }, Modifier.fillMaxWidth(), label = { Text("Password") }, - singleLine = true, enabled = !busy, visualTransformation = PasswordVisualTransformation(), - keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)) - Button( - onClick = { - work { - show(vm.signInMyTeamSpeak(email.trim(), password)) - password = "" - } - }, - enabled = !busy && email.isNotBlank() && password.isNotEmpty(), - ) { Text("Sign in") } - } - } - } else { - item { - Row(Modifier.padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) { - Column(Modifier.weight(1f)) { - Text("Signed in as ${login.username()}", style = MaterialTheme.typography.titleMedium) - Text(login.email(), style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant) - } - OutlinedButton(onClick = { - scope.launch { vm.signOutMyTeamSpeak() } - signedIn = false - rows = emptyList() - all = emptyList() - info = null - message = null - }) { Text("Sign out") } - } - } - info?.let { details -> - item { - Column(Modifier.padding(horizontal = 16.dp)) { - if (details.userId().isNotEmpty()) Detail("ID", details.userId()) - if (details.uuid().isNotEmpty()) Detail("UUID", details.uuid()) - details.created()?.let { Detail("Created", dateFormat.format(it)) } - } - } - } - if (rows.isNotEmpty()) { - item { - Text("Synchronised by the account", Modifier.padding(start = 16.dp, top = 16.dp), - style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary) - } - } - items(rows, key = { it.item.uuid() }) { row -> - val toggle = { rows = rows.map { if (it === row) it.copy(selected = !it.selected) else it } } - ListItem( - headlineContent = { Text(name(row.item), maxLines = 1, overflow = TextOverflow.Ellipsis) }, - supportingContent = { Text(details(row.item), maxLines = 1, overflow = TextOverflow.Ellipsis) }, - leadingContent = { Checkbox(row.selected, { toggle() }) }, - trailingContent = if (row.imported) ({ Text("Imported", style = MaterialTheme.typography.labelMedium) }) else null, - modifier = Modifier.clickable(onClick = toggle), - ) - } - if (rows.isNotEmpty()) { - item { - Button( - onClick = { - work { - val r = vm.importMyTeamSpeak(all, rows.filter { it.selected }.map { it.item }) - rows = rows.map { it.copy(imported = vm.isImported(it.item), selected = false) } - message = "Imported ${count(r.identitiesAdded(), "identity", "identities")} and " + - "${count(r.bookmarksAdded(), "bookmark", "bookmarks")}." - } - }, - enabled = !busy && rows.any { it.selected }, - modifier = Modifier.padding(horizontal = 16.dp), - ) { Text("Import selected") } - } - } - } - message?.let { text -> - item { - Text(text, Modifier.padding(horizontal = 16.dp), - color = if (error) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurface) - } - } - } - } -} - -private val dateFormat = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withZone(ZoneId.systemDefault()) - -/** A labelled value that can be selected and copied. */ -@Composable -private fun Detail(label: String, value: String) { - Column(Modifier.padding(top = 8.dp)) { - Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) - SelectionContainer { Text(value, style = MaterialTheme.typography.bodyMedium) } - } -} - -private fun name(item: SyncItem) = when (item) { - is SyncItem.Bookmark -> item.name().ifBlank { item.address() } - is SyncItem.Identity -> "Identity: ${item.name()}" - else -> "" -} - -private fun details(item: SyncItem) = when (item) { - is SyncItem.Bookmark -> "${item.address()}:${item.port()}" - is SyncItem.Identity -> item.nickname() - else -> "" -} - -private fun count(n: Int, one: String, many: String) = "$n ${if (n == 1) one else many}" diff --git a/android/app/src/main/java/com/ts3client/android/ui/NetworkSettingsScreen.kt b/android/app/src/main/java/com/ts3client/android/ui/NetworkSettingsScreen.kt deleted file mode 100644 index 4380817..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/NetworkSettingsScreen.kt +++ /dev/null @@ -1,88 +0,0 @@ -package com.ts3client.android.ui - -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Modifier -import androidx.compose.ui.unit.dp -import com.ts3client.android.SessionController -import com.ts3client.config.Settings -import kotlin.math.abs -import kotlin.math.roundToInt - -private const val MIN_BITRATE_KBITS = 8f -private const val MAX_BITRATE_KBITS = 160f - -/** What voice costs and survives on the wire: the encoder, duplicate packets and receive buffering. */ -@Composable -fun NetworkSettingsScreen(vm: SessionController, onBack: () -> Unit) { - val settings = vm.settings - fun change(edit: Settings.() -> Unit) { - settings.edit() - vm.applySettings() - } - var vbr by remember { mutableStateOf(settings.vbr) } - var fec by remember { mutableStateOf(settings.fec) } - var music by remember { mutableStateOf(settings.music) } - var redundancy by remember { mutableStateOf(settings.redundancyDelay) } - var copies by remember { mutableStateOf(settings.redundancyCopies) } - var receiveBuffer by remember { mutableStateOf(settings.receiveBuffer) } - - SubScreen("Network", onBack) { padding -> - Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { - Section("Encoder") - Level("Bitrate", settings.bitrate / 1000f, MIN_BITRATE_KBITS..MAX_BITRATE_KBITS, { "${it.roundToInt()} kbit/s" }) { - change { bitrate = it.roundToInt() * 1000 } - } - Toggle("Variable bitrate (VBR)", vbr) { - vbr = it - change { this.vbr = it } - } - Toggle("Forward error correction (FEC)", fec) { - fec = it - change { this.fec = it } - } - Level("Complexity", settings.complexity.toFloat(), 0f..10f, { "${it.roundToInt()}" }, steps = 9) { - change { complexity = it.roundToInt() } - } - Toggle("Music codec (stereo, higher fidelity)", music) { - music = it - change { this.music = it } - } - - Section("Redundancy") - ChoiceLevel("Delay", Settings.REDUNDANCY_DELAYS, redundancy) { - redundancy = it - change { redundancyDelay = it } - } - if (redundancy > 0) { - Level("Copies", copies.toFloat(), 1f..Settings.MAX_REDUNDANCY_COPIES.toFloat(), { "${it.roundToInt()}" }, - steps = Settings.MAX_REDUNDANCY_COPIES - 2) { - copies = it.roundToInt() - change { redundancyCopies = copies } - } - } - - Section("Receive") - ChoiceLevel("Extra buffering", Settings.RECEIVE_BUFFERS, receiveBuffer) { - receiveBuffer = it - change { this.receiveBuffer = it } - } - } - } -} - -/** A slider stepping through the millisecond [choices], starting at the one nearest [ms]. */ -@Composable -private fun ChoiceLevel(label: String, choices: IntArray, ms: Int, onDone: (Int) -> Unit) { - val index = choices.indices.minBy { abs(choices[it] - ms) } - fun at(position: Float) = choices[position.roundToInt()] - Level(label, index.toFloat(), 0f..(choices.size - 1).toFloat(), { at(it).let { v -> if (v == 0) "Off" else "$v ms" } }, - steps = choices.size - 2) { onDone(at(it)) } -} diff --git a/android/app/src/main/java/com/ts3client/android/ui/PackIcon.kt b/android/app/src/main/java/com/ts3client/android/ui/PackIcon.kt deleted file mode 100644 index 8683ee2..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/PackIcon.kt +++ /dev/null @@ -1,42 +0,0 @@ -package com.ts3client.android.ui - -import androidx.compose.foundation.Image -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.size -import androidx.compose.material3.LocalContentColor -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.remember -import androidx.compose.runtime.staticCompositionLocalOf -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.asImageBitmap -import androidx.compose.ui.graphics.toArgb -import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.unit.Dp -import androidx.compose.ui.unit.dp -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import com.ts3client.android.IconTheme - -val LocalIconTheme = staticCompositionLocalOf { error("No icon theme provided") } - -/** An icon of the active pack, named by its TeamSpeak key; art in the text colour takes [LocalContentColor]. */ -@Composable -fun PackIcon(key: String, contentDescription: String?, modifier: Modifier = Modifier, size: Dp = 24.dp) = - PackIcon(listOf(key), contentDescription, modifier, size) - -/** The first of [keys] the pack has, for icons packs need not ship in every variant. */ -@Composable -fun PackIcon(keys: List, contentDescription: String?, modifier: Modifier = Modifier, size: Dp = 24.dp) { - val theme = LocalIconTheme.current - val active by theme.active.collectAsStateWithLifecycle() - val pixels = with(LocalDensity.current) { size.roundToPx() } - val color = LocalContentColor.current - val rgb = color.copy(alpha = 1f).toArgb() - val bitmap = remember(keys, pixels, rgb, active) { theme.render(keys, pixels, rgb)?.asImageBitmap() } - if (bitmap == null) { - Spacer(modifier.size(size)) - } else { - // Disabled controls fade their content colour; the pack's own colours fade with it. - Image(bitmap, contentDescription, modifier.size(size), alpha = color.alpha) - } -} diff --git a/android/app/src/main/java/com/ts3client/android/ui/PictureViewer.kt b/android/app/src/main/java/com/ts3client/android/ui/PictureViewer.kt deleted file mode 100644 index 67c7930..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/PictureViewer.kt +++ /dev/null @@ -1,220 +0,0 @@ -package com.ts3client.android.ui - -import android.content.ClipData -import android.content.ClipboardManager -import android.widget.Toast -import androidx.compose.foundation.Image -import androidx.compose.foundation.background -import androidx.compose.foundation.gestures.detectTapGestures -import androidx.compose.foundation.gestures.detectTransformGestures -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.statusBarsPadding -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.ArrowBack -import androidx.compose.material.icons.filled.MoreVert -import androidx.compose.material3.DropdownMenu -import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.LocalContentColor -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.CompositionLocalProvider -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableFloatStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.produceState -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.setValue -import androidx.compose.runtime.staticCompositionLocalOf -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.graphics.Brush -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.graphicsLayer -import androidx.compose.ui.input.pointer.pointerInput -import androidx.compose.ui.layout.ContentScale -import androidx.compose.ui.layout.onSizeChanged -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.unit.IntSize -import androidx.compose.ui.window.Dialog -import androidx.compose.ui.window.DialogProperties -import com.ts3client.android.Picture -import com.ts3client.android.SavedPictures -import com.ts3client.android.ServerController -import com.ts3client.android.decodePicture -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext - -/** A picture to open full size. */ -class ViewedPicture( - /** What to call it when saved, without an extension. */ - val name: String, - /** Where it is on the web; null for an avatar. */ - val url: String? = null, - /** Follows the link it sits in; null when it sits in none. */ - val openLink: (() -> Unit)? = null, - /** Our own avatar, which there is no taking. */ - val ownAvatar: Boolean = false, - /** Its file; null when it is not there. */ - val read: suspend () -> ByteArray?, -) - -/** Opens a picture full size; null where nothing can. */ -val LocalPictureViewer = staticCompositionLocalOf<((ViewedPicture) -> Unit)?> { null } - -/** Lets [content] open pictures full size, over everything, with [server] to take one as our avatar on. */ -@Composable -fun PictureViewerHost(server: ServerController, content: @Composable () -> Unit) { - var viewed by remember { mutableStateOf(null) } - CompositionLocalProvider(LocalPictureViewer provides { viewed = it }, content = content) - val context = LocalContext.current - viewed?.let { picture -> - PictureViewer( - picture, - onSteal = if (picture.ownAvatar) null else { data -> - val error = server.setAvatar(data) - Toast.makeText(context, error ?: "Avatar set.", Toast.LENGTH_SHORT).show() - }, - onDismiss = { viewed = null }, - ) - } -} - -/** A name to save the picture at [url] under: its file's, or "picture" when it has none. */ -fun pictureName(url: String): String = - url.substringBefore('?').substringBefore('#').trimEnd('/').substringAfterLast('/') - .substringBeforeLast('.').ifBlank { "picture" } - -/** The picture on black, filling the screen; pinch or double-tap to zoom, tap to hide the bar. */ -@Composable -private fun PictureViewer( - picture: ViewedPicture, - /** Takes the picture as our avatar; null when it cannot be. */ - onSteal: (suspend (ByteArray) -> Unit)?, - onDismiss: () -> Unit, -) { - val state by produceState(null, picture) { - val data = picture.read() - value = Shown(data, data?.let { withContext(Dispatchers.Default) { decodePicture(it, MAX_PX) } }) - } - val data = state?.data - var bar by remember { mutableStateOf(true) } - var scale by remember { mutableFloatStateOf(1f) } - var offset by remember { mutableStateOf(Offset.Zero) } - var size by remember { mutableStateOf(IntSize.Zero) } - fun panTo(target: Offset) { - val maxX = size.width * (scale - 1) / 2 - val maxY = size.height * (scale - 1) / 2 - offset = Offset(target.x.coerceIn(-maxX, maxX), target.y.coerceIn(-maxY, maxY)) - } - - Dialog(onDismiss, DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) { - Box( - Modifier.fillMaxSize().background(Color.Black).onSizeChanged { size = it } - .pointerInput(Unit) { - detectTapGestures( - onTap = { bar = !bar }, - onDoubleTap = { scale = if (scale > 1f) 1f else DOUBLE_TAP_SCALE; panTo(Offset.Zero) }, - ) - } - .pointerInput(Unit) { - detectTransformGestures { _, pan, zoom, _ -> - scale = (scale * zoom).coerceIn(1f, MAX_SCALE) - panTo(offset + pan) - } - }, - contentAlignment = Alignment.Center, - ) { - val shown = state?.picture - when { - state == null -> PackIcon("LOADING_IMAGE", "Loading picture") - shown == null -> PackIcon("BROKEN_IMAGE", "Broken picture") - else -> Image( - rememberPicturePainter(shown), null, - Modifier.fillMaxSize().graphicsLayer { - scaleX = scale - scaleY = scale - translationX = offset.x - translationY = offset.y - }, - contentScale = ContentScale.Fit, - ) - } - if (bar) { - CompositionLocalProvider(LocalContentColor provides Color.White) { - Bar(picture, data, onSteal, onDismiss, Modifier.align(Alignment.TopCenter)) - } - } - } - } -} - -@Composable -private fun Bar( - picture: ViewedPicture, - data: ByteArray?, - onSteal: (suspend (ByteArray) -> Unit)?, - onDismiss: () -> Unit, - modifier: Modifier, -) { - val context = LocalContext.current - val scope = rememberCoroutineScope() - var menu by remember { mutableStateOf(false) } - Row( - modifier.fillMaxWidth() - .background(Brush.verticalGradient(listOf(Color.Black.copy(alpha = 0.6f), Color.Transparent))) - .statusBarsPadding(), - verticalAlignment = Alignment.CenterVertically, - ) { - IconButton(onClick = onDismiss) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } - Box(Modifier.weight(1f)) - Box { - IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "Picture options") } - DropdownMenu(menu, onDismissRequest = { menu = false }) { - DropdownMenuItem({ Text("Save") }, enabled = data != null, onClick = { - menu = false - val bytes = data ?: return@DropdownMenuItem - scope.launch { - val saved = SavedPictures.save(context, picture.name, bytes) - Toast.makeText(context, if (saved) "Saved." else "Could not save.", Toast.LENGTH_SHORT).show() - } - }) - if (onSteal != null) { - DropdownMenuItem({ Text("Steal for avatar") }, enabled = data != null, onClick = { - menu = false - val bytes = data ?: return@DropdownMenuItem - scope.launch { onSteal(bytes) } - }) - } - picture.url?.let { url -> - DropdownMenuItem({ Text("Copy URL") }, onClick = { - menu = false - context.getSystemService(ClipboardManager::class.java) - .setPrimaryClip(ClipData.newPlainText("URL", url)) - }) - } - picture.openLink?.let { open -> - DropdownMenuItem({ Text("Open link") }, onClick = { - menu = false - onDismiss() - open() - }) - } - } - } - } -} - -/** The picture's file, and the picture when the file is one; both null when it is not there. */ -private class Shown(val data: ByteArray?, val picture: Picture?) - -private const val MAX_PX = 4096 -private const val MAX_SCALE = 8f -private const val DOUBLE_TAP_SCALE = 2.5f diff --git a/android/app/src/main/java/com/ts3client/android/ui/PushToTalk.kt b/android/app/src/main/java/com/ts3client/android/ui/PushToTalk.kt deleted file mode 100644 index 7d98f45..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/PushToTalk.kt +++ /dev/null @@ -1,95 +0,0 @@ -package com.ts3client.android.ui - -import androidx.compose.foundation.gestures.awaitEachGesture -import androidx.compose.foundation.gestures.awaitFirstDown -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.remember -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.Shape -import androidx.compose.ui.input.pointer.pointerInput -import androidx.compose.ui.text.TextStyle -import androidx.compose.ui.unit.dp -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import com.ts3client.android.ServerController -import com.ts3client.android.ServerTree -import com.ts3client.android.SessionController -import com.ts3client.android.SessionState -import com.ts3client.net.ClientStatus -import kotlinx.coroutines.flow.MutableStateFlow - -/** What push-to-talk would talk on: the server holding the microphone, which need not be the one on screen. */ -internal class PttTarget(val owner: ServerController?, val state: SessionState, val talking: Boolean) - -@Composable -internal fun rememberPttTarget(vm: SessionController): PttTarget { - val owner by vm.micOwner.collectAsStateWithLifecycle() - val state by remember(owner) { owner?.state ?: MutableStateFlow(SessionState()) }.collectAsStateWithLifecycle() - val tree by remember(owner) { owner?.tree ?: MutableStateFlow(ServerTree()) }.collectAsStateWithLifecycle() - val self = tree.client(state.selfClientId) - val talking = self?.status == ClientStatus.TALKING || self?.status == ClientStatus.COMMANDER_TALKING - return PttTarget(owner, state, talking) -} - -/** Talks while held. */ -@Composable -internal fun PushToTalk( - talking: Boolean, - onPressed: (Boolean) -> Unit, - modifier: Modifier, - shape: Shape = RoundedCornerShape(24.dp), - textStyle: TextStyle = MaterialTheme.typography.titleMedium, -) { - val colors = MaterialTheme.colorScheme - Surface( - modifier.pointerInput(Unit) { - // Held until the finger lifts, wherever it wanders; a tap gesture would end once it left the button. - awaitEachGesture { - awaitFirstDown() - onPressed(true) - try { - do { - val event = awaitPointerEvent() - event.changes.forEach { it.consume() } - } while (event.changes.any { it.pressed }) - } finally { - onPressed(false) - } - } - }, - shape = shape, - color = if (talking) StatusColors.talking else colors.primaryContainer, - contentColor = if (talking) Color.White else colors.onPrimaryContainer, - ) { - Box(contentAlignment = Alignment.Center) { - Text(if (talking) "Talking…" else "Hold to talk", style = textStyle) - } - } -} - -/** Nothing but a push-to-talk button, as big as the screen; it talks in any input mode. */ -@Composable -fun GiantPttScreen(vm: SessionController, onBack: () -> Unit) { - val target = rememberPttTarget(vm) - SubScreen("Giant PTT", onBack) { padding -> - val fill = Modifier.padding(padding).fillMaxSize().padding(16.dp) - if (target.owner != null && target.state.connected) { - PushToTalk(target.talking, vm::setForceTransmit, fill, RoundedCornerShape(32.dp), - MaterialTheme.typography.displaySmall) - } else { - Box(fill, contentAlignment = Alignment.Center) { - Text("Not connected", - style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) - } - } - } -} diff --git a/android/app/src/main/java/com/ts3client/android/ui/RowColorPicker.kt b/android/app/src/main/java/com/ts3client/android/ui/RowColorPicker.kt deleted file mode 100644 index bd37551..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/RowColorPicker.kt +++ /dev/null @@ -1,120 +0,0 @@ -package com.ts3client.android.ui - -import androidx.compose.foundation.background -import androidx.compose.foundation.border -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.DropdownMenu -import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Slider -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.unit.Dp -import androidx.compose.ui.unit.dp -import com.ts3client.config.ClientRowColors - -/** A row background: none, a preset, or a custom colour. [argb] is 0 for none. */ -@Composable -internal fun RowColorPicker(label: String, argb: Int, onChange: (Int) -> Unit) { - var open by remember { mutableStateOf(false) } - var custom by remember { mutableStateOf(false) } - Box { - Row(Modifier.fillMaxWidth().clickable { open = true }.padding(horizontal = 16.dp, vertical = 8.dp), - verticalAlignment = Alignment.CenterVertically) { - Column(Modifier.weight(1f)) { - Text(label) - Text(nameOf(argb), style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant) - } - Swatch(argb, 28.dp) - } - DropdownMenu(open, { open = false }) { - DropdownMenuItem({ Text("None") }, leadingIcon = { Swatch(0) }, onClick = { - open = false - onChange(0) - }) - for (p in ClientRowColors.PRESETS) { - DropdownMenuItem({ Text(p.name()) }, leadingIcon = { Swatch(p.argb()) }, onClick = { - open = false - onChange(p.argb()) - }) - } - DropdownMenuItem({ Text("Custom…") }, onClick = { - open = false - custom = true - }) - } - } - if (custom) { - CustomColorDialog(if (argb != 0) argb else 0x59808080, onDismiss = { custom = false }) { - custom = false - onChange(it) - } - } -} - -private fun nameOf(argb: Int): String = - if (argb == 0) "None" else ClientRowColors.presetOf(argb)?.name() ?: "Custom" - -@Composable -private fun CustomColorDialog(initial: Int, onDismiss: () -> Unit, onPick: (Int) -> Unit) { - var alpha by remember { mutableIntStateOf(initial ushr 24) } - var red by remember { mutableIntStateOf(initial shr 16 and 0xFF) } - var green by remember { mutableIntStateOf(initial shr 8 and 0xFF) } - var blue by remember { mutableIntStateOf(initial and 0xFF) } - val argb = (alpha shl 24) or (red shl 16) or (green shl 8) or blue - AlertDialog( - onDismissRequest = onDismiss, - title = { Text("Custom colour") }, - text = { - Column { - Box(Modifier.fillMaxWidth().height(40.dp).clip(RoundedCornerShape(6.dp)) - .background(MaterialTheme.colorScheme.surface)) { - Box(Modifier.fillMaxWidth().height(40.dp).background(Color(argb))) - } - Channel("Red", red) { red = it } - Channel("Green", green) { green = it } - Channel("Blue", blue) { blue = it } - Channel("Opacity", alpha) { alpha = it } - } - }, - confirmButton = { TextButton({ onPick(argb) }, enabled = argb != 0) { Text("OK") } }, - dismissButton = { TextButton(onDismiss) { Text("Cancel") } }, - ) -} - -@Composable -private fun Channel(label: String, value: Int, onChange: (Int) -> Unit) { - Row(verticalAlignment = Alignment.CenterVertically) { - Text(label, Modifier.width(64.dp), style = MaterialTheme.typography.bodySmall) - Slider(value.toFloat(), { onChange(it.toInt()) }, Modifier.weight(1f), valueRange = 0f..255f) - } -} - -/** The colour over the screen's background, as a row would show it; outlined so "none" shows too. */ -@Composable -private fun Swatch(argb: Int, size: Dp = 20.dp) { - val shape = RoundedCornerShape(4.dp) - Box(Modifier.size(size).clip(shape).background(MaterialTheme.colorScheme.surface).background(Color(argb)) - .border(1.dp, MaterialTheme.colorScheme.outline, shape)) -} diff --git a/android/app/src/main/java/com/ts3client/android/ui/ServerImage.kt b/android/app/src/main/java/com/ts3client/android/ui/ServerImage.kt deleted file mode 100644 index 83dd208..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/ServerImage.kt +++ /dev/null @@ -1,140 +0,0 @@ -package com.ts3client.android.ui - -import android.graphics.BitmapFactory -import android.graphics.drawable.AnimatedImageDrawable -import android.graphics.drawable.Drawable -import android.os.Handler -import android.os.Looper -import androidx.compose.foundation.Image -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.LocalContentColor -import androidx.compose.runtime.Composable -import androidx.compose.runtime.DisposableEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.runtime.staticCompositionLocalOf -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.geometry.Size -import androidx.compose.ui.graphics.ImageBitmap -import androidx.compose.ui.graphics.asImageBitmap -import androidx.compose.ui.graphics.drawscope.DrawScope -import androidx.compose.ui.graphics.drawscope.drawIntoCanvas -import androidx.compose.ui.graphics.nativeCanvas -import androidx.compose.ui.graphics.painter.BitmapPainter -import androidx.compose.ui.graphics.painter.Painter -import androidx.compose.ui.graphics.toArgb -import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.unit.Dp -import androidx.compose.ui.unit.dp -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import com.ts3client.android.Picture -import com.ts3client.android.ServerImages -import com.ts3client.gfx.CountryFlags -import com.ts3client.net.IconRepository -import java.util.Optional -import java.util.concurrent.ConcurrentHashMap -import kotlin.math.roundToInt - -/** The images of the server on screen. */ -val LocalServerImages = staticCompositionLocalOf { null } - -/** - * A group, channel or server icon; nothing while it has none or it is still downloading. - * TeamSpeak's default group icons are the pack's, drawn in its style, as on the desktop. - */ -@Composable -fun ServerIcon(id: Long, modifier: Modifier = Modifier, size: Dp = 16.dp) { - if (id == 0L) return - if (id in 1..IconRepository.MAX_BUNDLED_ID) { - val theme = LocalIconTheme.current - val active by theme.active.collectAsStateWithLifecycle() - val pixels = with(LocalDensity.current) { size.roundToPx() } - val rgb = LocalContentColor.current.copy(alpha = 1f).toArgb() - val themed = remember(id, pixels, rgb, active) { theme.render(listOf("GROUP_$id"), pixels, rgb)?.asImageBitmap() } - if (themed != null) { - Image(themed, null, modifier.size(size)) - return - } - } - val images = LocalServerImages.current ?: return - val version by images.version.collectAsStateWithLifecycle() - val bitmap = remember(id, version) { images.icon(id) } ?: return - Image(bitmap, null, modifier.size(size)) -} - -/** A client's avatar, moving if it is an animated GIF; nothing while they have none or it is still downloading. */ -@Composable -fun Avatar(uniqueId: String, flag: String, modifier: Modifier = Modifier, size: Dp = 64.dp) { - val images = LocalServerImages.current ?: return - val version by images.version.collectAsStateWithLifecycle() - val picture = remember(flag, version) { images.avatar(uniqueId, flag) } ?: return - Image(rememberPicturePainter(picture), "Avatar", modifier.size(size).clip(RoundedCornerShape(8.dp))) -} - -/** Draws [picture], playing it while on screen if it moves. */ -@Composable -fun rememberPicturePainter(picture: Picture): Painter = when (picture) { - is Picture.Still -> remember(picture) { BitmapPainter(picture.bitmap) } - is Picture.Moving -> rememberMovingPainter(picture.drawable) -} - -@Composable -private fun rememberMovingPainter(drawable: AnimatedImageDrawable): Painter { - val painter = remember(drawable) { MovingPainter(drawable) } - DisposableEffect(drawable) { - drawable.callback = painter - drawable.start() - onDispose { - drawable.stop() - if (drawable.callback === painter) drawable.callback = null - } - } - return painter -} - -private class MovingPainter(private val drawable: AnimatedImageDrawable) : Painter(), Drawable.Callback { - /** Read while drawing, so that each new frame draws again. */ - private var frame by mutableIntStateOf(0) - private val main = Handler(Looper.getMainLooper()) - - override val intrinsicSize = Size(drawable.intrinsicWidth.toFloat(), drawable.intrinsicHeight.toFloat()) - - override fun DrawScope.onDraw() { - frame - drawIntoCanvas { canvas -> - drawable.setBounds(0, 0, size.width.roundToInt(), size.height.roundToInt()) - drawable.draw(canvas.nativeCanvas) - } - } - - override fun invalidateDrawable(who: Drawable) { - frame++ - } - - override fun scheduleDrawable(who: Drawable, what: Runnable, `when`: Long) { - main.postAtTime(what, `when`) - } - - override fun unscheduleDrawable(who: Drawable, what: Runnable) { - main.removeCallbacks(what) - } -} - -private val flags = ConcurrentHashMap>() - -/** The flag of a country, at TeamSpeak's 16×11; nothing for no country or one without a flag. */ -@Composable -fun CountryFlag(code: String, modifier: Modifier = Modifier) { - if (code.isEmpty()) return - val bitmap = remember(code) { - flags.getOrPut(code) { - Optional.ofNullable(CountryFlags.png(code)?.let { BitmapFactory.decodeByteArray(it, 0, it.size)?.asImageBitmap() }) - }.orElse(null) - } ?: return - Image(bitmap, CountryFlags.name(code), modifier.size(16.dp, 11.dp)) -} - diff --git a/android/app/src/main/java/com/ts3client/android/ui/ServerScreen.kt b/android/app/src/main/java/com/ts3client/android/ui/ServerScreen.kt deleted file mode 100644 index 24befc1..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/ServerScreen.kt +++ /dev/null @@ -1,686 +0,0 @@ -package com.ts3client.android.ui - -import android.widget.Toast -import androidx.activity.compose.BackHandler -import androidx.compose.foundation.Image -import androidx.compose.foundation.clickable -import androidx.compose.foundation.combinedClickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.consumeWindowInsets -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.imePadding -import androidx.compose.foundation.layout.navigationBarsPadding -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.rememberLazyListState -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.ArrowDropDown -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.Badge -import androidx.compose.material3.BadgedBox -import androidx.compose.material3.DropdownMenu -import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.FilledTonalButton -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.IconToggleButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.MenuDefaults -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.SnackbarHostState -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.material3.minimumInteractiveComponentSize -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.key -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.saveable.Saver -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.alpha -import androidx.compose.ui.draw.clip -import androidx.compose.ui.input.key.Key -import androidx.compose.ui.input.key.KeyEventType -import androidx.compose.ui.input.key.isCtrlPressed -import androidx.compose.ui.input.key.key -import androidx.compose.ui.input.key.onPreviewKeyEvent -import androidx.compose.ui.input.key.type -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.platform.LocalUriHandler -import androidx.compose.ui.semantics.Role -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import androidx.lifecycle.compose.LifecycleResumeEffect -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import com.ts3client.android.ChannelItem -import com.ts3client.android.ChatKey -import com.ts3client.android.ChatMatch -import com.ts3client.android.ServerController -import com.ts3client.android.SessionController -import com.ts3client.android.SessionState -import com.ts3client.android.TreeFind -import com.ts3client.android.findIn -import com.ts3client.config.Settings -import com.ts3client.config.WhisperList -import com.ts3client.myts.ChatAttachment -import com.ts3client.session.ServerLink -import com.ts3client.text.TsLink -import kotlinx.coroutines.launch - -private val ChatKeySaver = Saver( - save = { key -> - when (key) { - ChatKey.Server -> "server" - ChatKey.Channel -> "channel" - is ChatKey.Private -> "private:${key.clientId}" - } - }, - restore = { saved -> - when { - saved == "server" -> ChatKey.Server - saved.startsWith("private:") -> ChatKey.Private(saved.substringAfter(':').toInt()) - else -> ChatKey.Channel - } - }, -) - -private val ChannelEditSaver = Saver( - save = { edit -> edit?.let { intArrayOf(it.channelId, it.parentId) } }, - restore = { ChannelEdit(it[0], it[1]) }, -) - -/** A channel whose files are browsed, with the password they take. */ -private data class FilesOf(val channelId: Int, val name: String, val password: String) - -private val FilesOfSaver = Saver>( - save = { f -> f?.let { listOf(it.channelId, it.name, it.password) } }, - restore = { FilesOf(it[0] as Int, it[1] as String, it[2] as String) }, -) - -/** A connection: the channel tree and the chat, with the voice controls underneath. */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun ServerScreen( - vm: SessionController, - server: ServerController, - snackbar: SnackbarHostState, - onSettings: () -> Unit, - /** Opens the given client's contact page. */ - onEditContact: (String) -> Unit, - onEnableMicrophone: () -> Unit, - onConnectOther: () -> Unit, - onEditBookmark: (BookmarkEdit) -> Unit, -) { - val state by server.state.collectAsStateWithLifecycle() - val tree by server.tree.collectAsStateWithLifecycle() - val chats by server.chats.collectAsStateWithLifecycle() - val collapsed by server.collapsed.collectAsStateWithLifecycle() - - var showChat by rememberSaveable { mutableStateOf(false) } - // Out here, so the tree keeps its place while the chat or another screen replaces it. - val treeList = rememberLazyListState() - var chatKey by rememberSaveable(stateSaver = ChatKeySaver) { mutableStateOf(ChatKey.Channel) } - val conversation = chats[chatKey] ?: chats.channel - var clientSheet by remember { mutableStateOf(null) } - var clientSheetFromTree by remember { mutableStateOf(false) } - /** A row to show in the tree. */ - var reveal by remember { mutableStateOf(null) } - var channelSheet by remember { mutableStateOf(null) } - /** A locked channel being joined, while its password is asked for. */ - var joinLocked by remember { mutableStateOf(null) } - val join = { channel: ChannelItem -> - if (channel.locked) joinLocked = channel.id else server.joinChannel(channel.id) - } - var serverSheet by remember { mutableStateOf(false) } - val bookmarkHere = { channelId: Int -> server.bookmark(channelId)?.let { onEditBookmark(BookmarkEdit(-1, it)) } } - var banList by rememberSaveable { mutableStateOf(false) } - var channelEdit by rememberSaveable(stateSaver = ChannelEditSaver) { mutableStateOf(null) } - var files by rememberSaveable(stateSaver = FilesOfSaver) { mutableStateOf(null) } - /** A locked channel whose files are wanted, while its password is asked for. */ - var filesLocked by remember { mutableStateOf(null) } - var deletingChannel by remember { mutableStateOf(null) } - var whisperLists by rememberSaveable { mutableStateOf(false) } - /** What is being added to a whisper list, while the list is picked: its name and how to add it. */ - var toWhisperList by remember { mutableStateOf Unit>?>(null) } - var connectionInfo by rememberSaveable { mutableStateOf(null) } - /** The client to move, while a channel for them is being picked. */ - var moving by remember { mutableStateOf(null) } - val infoUpdates by server.infoUpdates.collectAsStateWithLifecycle() - - val chatRequest by server.chatRequest.collectAsStateWithLifecycle() - LaunchedEffect(chatRequest) { - val key = chatRequest ?: return@LaunchedEffect - chatKey = if (chats[key] != null) key else server.openPrivateChat(key.clientId) - showChat = true - server.chatRequestHandled() - } - - val viewing = if (showChat) conversation.key else null - LifecycleResumeEffect(viewing) { - server.viewing = viewing - onPauseOrDispose { server.viewing = null } - } - - val uriHandler = LocalUriHandler.current - val attachments = rememberAttachmentActions(vm, server, snackbar, conversation.key) - val onLink: (String) -> Unit = { href -> - val ref = TsLink.parse(href) - when { - ChatAttachment.isHref(href) -> attachments.open(href) - ServerLink.isLink(href) -> ServerLink.parse(href)?.let { vm.open(it) } - ref == null -> runCatching { uriHandler.openUri(href) } - ref.client -> { clientSheet = ref.id; clientSheetFromTree = false } - else -> channelSheet = ref.id - } - } - - // Find: in the tree, clients or channels; in the chat, the conversation on screen. - val find = rememberSaveable(saver = FindState.Saver) { FindState() } - val treeFind = TreeFind(find.usable, find.channels) - val treeHits = remember(tree, treeFind) { tree.hits(treeFind) } - val treeFiltering = find.filter && !treeFind.query.isEmpty - val shownTree = remember(tree, treeFind, treeFiltering) { if (treeFiltering) tree.only(treeFind) else tree } - // While the tree is filtered every channel opens, so every match shows; folding one then lasts as long as the filter. - var filterCollapsed by remember(treeFiltering, treeFind) { mutableStateOf(emptySet()) } - /** The match the tree is on. */ - var treeAt by remember { mutableStateOf(null) } - // Lambdas, not local functions: Compose remembers a reference to a local function with what it first captured. - val showTreeHit = { id: Int? -> - if (id != null) { - treeAt = id - val path = (if (treeFind.channels) tree.parentsOf(id) else tree.pathTo(id)).orEmpty() - if (treeFiltering) filterCollapsed = filterCollapsed - path.toSet() else server.expand(path) - reveal = TreeRef(treeFind.channels, id) - } - } - LaunchedEffect(treeFind, showChat) { - treeAt = null - if (!showChat) showTreeHit(treeHits.firstOrNull()) - } - - val chatQuery = find.usable - val chatLines = remember(conversation.lines, chatQuery, find.filter) { - if (find.filter && !chatQuery.isEmpty) conversation.lines.filter { chatQuery.matches(it.plain) } else conversation.lines - } - val chatHits = remember(chatLines, chatQuery) { findIn(chatLines, chatQuery, MAX_CHAT_MATCHES) } - /** The match the chat is on; a new search starts from the newest. */ - var chatAt by remember { mutableStateOf(null) } - var chatReveal by remember { mutableStateOf(null) } - LaunchedEffect(chatQuery, conversation.key, find.filter, showChat) { - chatAt = if (showChat) chatHits.lastOrNull() else null - chatReveal = chatAt?.line - } - - val step = { delta: Int -> - if (showChat && chatHits.isNotEmpty()) { - chatAt = chatHits[next(chatHits.indexOf(chatAt), delta, chatHits.size)] - chatReveal = chatAt?.line - } else if (!showChat && treeHits.isNotEmpty()) { - showTreeHit(treeHits[next(treeHits.indexOf(treeAt), delta, treeHits.size)]) - } - } - - if (banList) { - BanListScreen(server, vm.banReasons, onBack = { banList = false }) - return - } - channelEdit?.let { - ChannelEditScreen(server, it, onDone = { channelEdit = null }) - return - } - files?.let { - FilesScreen(server, it.channelId, it.name, it.password, onBack = { files = null }) - return - } - if (whisperLists) { - WhisperListsScreen(vm, server, onBack = { whisperLists = false }) - return - } - connectionInfo?.let { id -> - ConnectionInfoScreen(server, id, tree.client(id), onBack = { connectionInfo = null }) - return - } - - BackHandler(showChat) { showChat = false } - BackHandler(moving != null && !showChat) { moving = null } - BackHandler(find.open) { find.open = false } - - Scaffold( - // A hardware keyboard's Ctrl+F, as on the desktop. - modifier = Modifier.onPreviewKeyEvent { e -> - val ctrlF = e.isCtrlPressed && e.key == Key.F - if (ctrlF && e.type == KeyEventType.KeyDown) find.show() - ctrlF - }, - topBar = { - if (find.open) { - if (showChat) { - FindBar(find, inTree = false, chatHits.indexOf(chatAt) + 1, chatHits.size, - chatHits.size == MAX_CHAT_MATCHES, step) - } else { - FindBar(find, inTree = true, treeHits.indexOf(treeAt) + 1, treeHits.size, false, step) - } - } else { - TopAppBar( - title = { ServerSwitcher(vm, server, state, onConnectOther) }, - expandedHeight = 48.dp, - actions = { - state.hostButton?.let { HostButtonAction(it) { url -> runCatching { uriHandler.openUri(url) } } } - if (state.connected) WhisperMenu(vm, server, state) { whisperLists = true } - IconButton(onClick = find::show) { PackIcon("FIND", "Find") } - IconButton(onClick = onSettings) { PackIcon("SETTINGS", "Settings") } - }, - ) - } - }, - bottomBar = { - Column { - val ptt = rememberPttTarget(vm) - WhisperBanner(state) { server.setWhisper(null) } - VoiceBar(state, ptt.owner != null, ptt.talking, vm, server, onEnableMicrophone, showChat, chats.anyUnread) { - showChat = !showChat - } - } - }, - snackbarHost = { SnackbarHost(snackbar) }, - ) { padding -> - Column(Modifier.padding(padding).consumeWindowInsets(padding).imePadding()) { - if (!showChat) { - moving?.let { id -> - val client = tree.client(id) - if (client == null) { - LaunchedEffect(id) { moving = null } - } else { - MovePrompt(client.name) { moving = null } - } - } - ChannelTree( - serverName = state.title, - tree = shownTree, - collapsed = if (treeFiltering) filterCollapsed else collapsed, - currentChannel = state.channelId, - onToggle = { - if (!treeFiltering) server.toggleCollapsed(it.id) - else if (it.id in filterCollapsed) filterCollapsed -= it.id - else filterCollapsed += it.id - }, - onChannel = { channel -> - val client = moving - when { - channel.spacer != null -> {} - client != null -> { server.moveClient(client, channel.id); moving = null } - else -> channelSheet = channel.id - } - }, - onChannelDoubleTap = { channel -> - val client = moving - when { - client != null -> { server.moveClient(client, channel.id); moving = null } - channel.id == state.channelId -> {} - else -> join(channel) - } - }, - onClient = { clientSheet = it.id; clientSheetFromTree = true }, - onServer = { serverSheet = true }, - modifier = Modifier.weight(1f), - reveal = reveal, - onRevealed = { reveal = null }, - found = remember(treeHits) { treeHits.mapTo(HashSet()) { TreeRef(treeFind.channels, it) } }, - foundCurrent = treeAt?.takeIf { it in treeHits }?.let { TreeRef(treeFind.channels, it) }, - listState = treeList, - onShowSelf = { - val path = tree.pathTo(state.selfClientId).orEmpty() - if (treeFiltering) filterCollapsed = filterCollapsed - path.toSet() else server.expand(path) - reveal = TreeRef(false, state.selfClientId) - }, - ) - } else { - ChatPane( - chats = chats, - selected = conversation, - canSend = state.connected, - onSelect = { chatKey = it }, - onClose = { key -> - if (chatKey == key) chatKey = ChatKey.Channel - server.closePrivateChat(key) - }, - onSend = { server.send(conversation.key, it) }, - onAttach = attachments.share, - onLink = onLink, - modifier = Modifier.weight(1f), - lines = chatLines, - find = chatQuery, - current = chatAt, - reveal = chatReveal, - onRevealed = { chatReveal = null }, - ) - } - } - } - - // A sheet goes with its client or channel when that leaves the tree. - clientSheet?.let { id -> - LaunchedEffect(id) { server.requestClientDetails(id) } - tree.client(id)?.let { client -> - ClientSheet( - client = client, - details = remember(id, tree, infoUpdates) { server.clientDetails(id) }, - onLink = onLink, - away = state.away, - initialVolume = remember(id) { server.clientVolume(id) }, - onDismiss = { clientSheet = null }, - onMessage = { - clientSheet = null - chatKey = server.openPrivateChat(id) - showChat = true - }, - onPoke = { server.poke(id, it); clientSheet = null }, - onVolume = { server.setClientVolume(id, it) }, - onAway = { server.setAway(it); clientSheet = null }, - onAddContact = { server.addContact(id, it) }, - onEditContact = { clientSheet = null; onEditContact(client.uniqueId) }, - onConnectionInfo = { clientSheet = null; connectionInfo = id }, - onWhisper = { clientSheet = null; server.whisperToClient(id) }, - onAddToWhisperList = { - clientSheet = null - server.clientRef(id)?.let { ref -> toWhisperList = client.name to { it.clients.add(ref) } } - }, - onMove = if (server.canMoveClients) ({ clientSheet = null; moving = id }) else null, - onMoveToOwnChannel = if (server.canMoveClients && tree.channel(state.channelId)?.clients?.none { it.id == id } == true) { - { server.moveClient(id, state.channelId); clientSheet = null } - } else null, - onFindInTree = if (clientSheetFromTree) null else ({ - clientSheet = null - tree.pathTo(id)?.let { server.expand(it) } - showChat = false - reveal = TreeRef(false, id) - }), - moderation = { ClientModeration(server, client) { clientSheet = null } }, - ) - } - } - channelSheet?.let { id -> - LaunchedEffect(id) { server.requestChannelDetails(id) } - tree.channel(id)?.let { channel -> - ChannelSheet( - channel = channel, - details = remember(id, tree, infoUpdates) { server.channelDetails(id) }, - onLink = onLink, - current = id == state.channelId, - onDismiss = { channelSheet = null }, - onJoin = { join(channel); channelSheet = null }, - onSubscribe = { server.setSubscribed(id, it); channelSheet = null }, - onBookmark = { channelSheet = null; bookmarkHere(id) }, - onWhisper = { channelSheet = null; server.whisperToChannel(id) }, - onAddToWhisperList = { - channelSheet = null - server.channelRef(id)?.let { ref -> toWhisperList = channel.name to { it.channels.add(ref) } } - }, - onFiles = { - channelSheet = null - if (channel.locked) filesLocked = id else files = FilesOf(id, channel.name, "") - }, - onCreateSub = if (server.canCreateChannels) ({ channelSheet = null; channelEdit = ChannelEdit(0, id) }) else null, - onEdit = if (server.canEditChannels) ({ channelSheet = null; channelEdit = ChannelEdit(id) }) else null, - onDelete = if (server.canDeleteChannels) ({ channelSheet = null; deletingChannel = id }) else null, - ) - } - } - joinLocked?.let { id -> - TextPrompt( - title = "Join ${tree.channel(id)?.name.orEmpty()}", - label = "Channel password", - confirm = "Join", - password = true, - onDismiss = { joinLocked = null }, - onConfirm = { joinLocked = null; server.joinChannel(id, it) }, - ) - } - filesLocked?.let { id -> - TextPrompt( - title = "Files of ${tree.channel(id)?.name.orEmpty()}", - label = "Channel password", - confirm = "Open", - password = true, - onDismiss = { filesLocked = null }, - onConfirm = { filesLocked = null; files = FilesOf(id, tree.channel(id)?.name.orEmpty(), it) }, - ) - } - deletingChannel?.let { id -> - val channel = tree.channel(id) - val scope = rememberCoroutineScope() - AlertDialog( - onDismissRequest = { deletingChannel = null }, - title = { Text("Delete ${channel?.name.orEmpty()}?") }, - text = if (channel != null && (channel.children.isNotEmpty() || channel.clients.isNotEmpty())) { - { Text("Its sub-channels go with it, and whoever is in it is moved out.") } - } else null, - confirmButton = { - TextButton(onClick = { - deletingChannel = null - scope.launch { server.deleteChannel(id)?.let { snackbar.showSnackbar("Could not delete the channel: $it") } } - }) { Text("Delete") } - }, - dismissButton = { TextButton(onClick = { deletingChannel = null }) { Text("Cancel") } }, - ) - } - toWhisperList?.let { (name, add) -> - AddToWhisperListDialog(vm, name, onDismiss = { toWhisperList = null }) { index, newName -> - toWhisperList = null - vm.addToWhisperList(index, newName, add) - } - } - if (serverSheet) { - remember(tree, infoUpdates) { server.serverDetails() }?.let { - ServerSheet(it, onLink, onDismiss = { serverSheet = false }, - onBookmark = { serverSheet = false; bookmarkHere(state.channelId) }, - onBanList = if (server.canViewBanList) ({ serverSheet = false; banList = true }) else null, - onCreateChannel = if (server.canCreateChannels) ({ serverSheet = false; channelEdit = ChannelEdit(0, 0) }) else null) - } - } -} - -/** More matches than this nobody steps through one by one. */ -private const val MAX_CHAT_MATCHES = 5000 - -/** The index [delta] on from [at] among [size], wrapping around; from none, the first or the last. */ -private fun next(at: Int, delta: Int, size: Int): Int = - if (at < 0) (if (delta > 0) 0 else size - 1) else Math.floorMod(at + delta, size) - -/** Says a channel is being picked for [name] to move to, until it is or [onCancel]. */ -@Composable -private fun MovePrompt(name: String, onCancel: () -> Unit) { - Surface(color = MaterialTheme.colorScheme.secondaryContainer) { - Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) { - PackIcon("CHANNEL_SWITCH", null) - Text("Move $name to…", Modifier.weight(1f).padding(horizontal = 12.dp), maxLines = 1, - overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium) - TextButton(onClick = onCancel) { Text("Cancel") } - } - } -} - -/** - * Mute, deafen, away and the chat, around the push-to-talk button when that is how the - * microphone is used. Holding the mute button switches between push to talk and voice activation. - */ -@Composable -private fun VoiceBar( - state: SessionState, - /** Whether some server holds the microphone, for push-to-talk to talk on. */ - captured: Boolean, - talking: Boolean, - vm: SessionController, - server: ServerController, - onEnableMicrophone: () -> Unit, - showChat: Boolean, - unread: Boolean, - onChat: () -> Unit, -) { - val context = LocalContext.current - val ptt = state.connected && captured && state.inputMode == Settings.InputMode.PUSH_TO_TALK - val mic = @Composable { - BarButton( - onClick = { server.setMicMuted(!state.micMuted) }, - onLongClick = { - val mode = vm.toggleInputMode() - val text = if (mode == Settings.InputMode.PUSH_TO_TALK) "Switched to push-to-talk mode." - else "Switched to voice activation mode." - Toast.makeText(context, text, Toast.LENGTH_SHORT).show() - }, - enabled = state.connected, - ) { - if (state.micMuted) PackIcon("INPUT_MUTED", "Unmute microphone") - else PackIcon("CAPTURE", "Mute microphone") - } - } - val deafen = @Composable { - IconToggleButton(state.deafened, { server.setDeafened(it) }, enabled = state.connected) { - if (state.deafened) PackIcon("OUTPUT_MUTED", "Undeafen") - else PackIcon("PLAYBACK", "Deafen") - } - } - // Another server holds the microphone. - val activate = @Composable { - if (state.connected && state.micPermission && !state.micActive) { - IconButton(onClick = onEnableMicrophone) { PackIcon("ACTIVATE_MICROPHONE", "Speak on this server") } - } - } - val middle = @Composable { - when { - ptt -> PushToTalk(talking, vm::setPushToTalk, Modifier.fillMaxWidth().height(48.dp)) - !state.micPermission -> FilledTonalButton(onClick = onEnableMicrophone) { - PackIcon("CAPTURE", null) - Text("Use microphone", Modifier.padding(start = 8.dp), maxLines = 1) - } - } - } - val away = @Composable { - IconToggleButton(state.away, { server.setAway(it) }, enabled = state.connected) { - PackIcon("AWAY", if (state.away) "Back" else "Away", Modifier.alpha(if (state.away) 1f else 0.5f)) - } - } - val chat = @Composable { - IconToggleButton(showChat, { onChat() }) { - BadgedBox(badge = { if (unread && !showChat) Badge() }) { - PackIcon(listOf("MESSAGES", "CHANNEL_CHAT"), if (showChat) "Channels" else "Chat", - Modifier.alpha(if (showChat) 1f else 0.7f)) - } - } - } - Surface(tonalElevation = 3.dp) { - // The same places whatever shows: sides of three buttons each keep the talk button centred. - Row(Modifier.fillMaxWidth().navigationBarsPadding().padding(horizontal = 8.dp, vertical = 4.dp), - horizontalArrangement = Arrangement.spacedBy(4.dp), - verticalAlignment = Alignment.CenterVertically) { - Row(Modifier.width(SIDE), verticalAlignment = Alignment.CenterVertically) { - Slot { mic() }; Slot { deafen() }; Slot { activate() } - } - Box(Modifier.weight(1f).height(48.dp), contentAlignment = Alignment.Center) { middle() } - Row(Modifier.width(SIDE), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) { - Slot { away() }; Slot { chat() } - } - } - } -} - -private val SLOT = 48.dp -private val SIDE = SLOT * 3 - -/** One button's place in the bar, kept whether or not the button shows. */ -@Composable -private fun Slot(content: @Composable () -> Unit) { - Box(Modifier.size(SLOT), contentAlignment = Alignment.Center) { content() } -} - -/** An icon button that also answers a long press. */ -@Composable -private fun BarButton(onClick: () -> Unit, onLongClick: () -> Unit, enabled: Boolean, content: @Composable () -> Unit) { - Box( - Modifier - .minimumInteractiveComponentSize() - .size(40.dp) - .clip(CircleShape) - .combinedClickable(enabled = enabled, role = Role.Button, onLongClick = onLongClick, onClick = onClick) - .alpha(if (enabled) 1f else 0.38f), - contentAlignment = Alignment.Center, - ) { content() } -} - -/** The server's own icon, else the pack's server icon. */ -@Composable -private fun ServerLogo(server: ServerController, modifier: Modifier = Modifier) { - val tree by server.tree.collectAsStateWithLifecycle() - val version by server.images.version.collectAsStateWithLifecycle() - val icon = remember(tree.serverIconId, version) { server.images.icon(tree.serverIconId) } - if (icon != null) Image(icon, null, modifier.size(24.dp)) - else PackIcon("SERVER_GREEN", null, modifier) -} - -/** The server on screen, opening onto the others and connecting to another. */ -@Composable -private fun ServerSwitcher(vm: SessionController, server: ServerController, state: SessionState, onConnectOther: () -> Unit) { - val servers by vm.servers.collectAsStateWithLifecycle() - var open by remember { mutableStateOf(false) } - Box(Modifier.fillMaxWidth()) { - Row(Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable { open = true }, - verticalAlignment = Alignment.CenterVertically) { - ServerLogo(server, Modifier.padding(end = 12.dp)) - Column(Modifier.weight(1f)) { - Text(state.title, maxLines = 1, overflow = TextOverflow.Ellipsis) - if (!state.connected) { - Text(state.status, style = MaterialTheme.typography.bodySmall, maxLines = 1, - overflow = TextOverflow.Ellipsis) - } - } - Icon(Icons.Filled.ArrowDropDown, "Servers") - } - DropdownMenu(open, onDismissRequest = { open = false }) { - for (other in servers) { - key(other.id) { - val otherState by other.state.collectAsStateWithLifecycle() - DropdownMenuItem( - text = { Text(otherState.title, maxLines = 1, overflow = TextOverflow.Ellipsis) }, - onClick = { open = false; vm.select(other) }, - leadingIcon = { - ServerLogo(other, Modifier.alpha(if (otherState.connected) 1f else 0.5f)) - }, - trailingIcon = if (otherState.micActive) ({ PackIcon("ACTIVATE_MICROPHONE", "Microphone") }) else null, - colors = if (other == server) MenuDefaults.itemColors(textColor = MaterialTheme.colorScheme.primary) - else MenuDefaults.itemColors(), - ) - } - } - HorizontalDivider() - DropdownMenuItem( - text = { Text("Connect…") }, - onClick = { open = false; onConnectOther() }, - leadingIcon = { PackIcon("CONNECT", null) }, - ) - DropdownMenuItem( - text = { Text("Disconnect from current") }, - onClick = { open = false; server.disconnect() }, - leadingIcon = { PackIcon("DISCONNECT", null) }, - ) - } - } -} - diff --git a/android/app/src/main/java/com/ts3client/android/ui/SettingsScreen.kt b/android/app/src/main/java/com/ts3client/android/ui/SettingsScreen.kt deleted file mode 100644 index 5ef86ca..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/SettingsScreen.kt +++ /dev/null @@ -1,127 +0,0 @@ -package com.ts3client.android.ui - -import androidx.activity.compose.rememberLauncherForActivityResult -import androidx.activity.result.contract.ActivityResultContracts -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Modifier -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import com.ts3client.android.IconTheme -import com.ts3client.android.SessionController -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext - -private enum class SettingsPage { SOUND, NETWORK, GIANT_PTT, DESIGN, IDENTITIES, MY_TEAMSPEAK } - -/** - * The settings, by category. Every change is saved and put into effect at once, - * as there is no dialog to confirm. - */ -@Composable -fun SettingsScreen(vm: SessionController, onContacts: () -> Unit, onBack: () -> Unit) { - var page by rememberSaveable { mutableStateOf(null) } - when (page) { - SettingsPage.SOUND -> return SoundSettingsScreen(vm, onBack = { page = null }) - SettingsPage.NETWORK -> return NetworkSettingsScreen(vm, onBack = { page = null }) - SettingsPage.GIANT_PTT -> return GiantPttScreen(vm, onBack = { page = null }) - SettingsPage.DESIGN -> return DesignScreen(vm, onBack = { page = null }) - SettingsPage.IDENTITIES -> return IdentitiesScreen(vm.identities, onBack = { page = null }) - SettingsPage.MY_TEAMSPEAK -> return MyTeamSpeakScreen(vm, onBack = { page = null }) - null -> {} - } - - SubScreen("Settings", onBack) { padding -> - Column(Modifier.padding(padding).verticalScroll(rememberScrollState())) { - LinkRow("Contacts", "Friends and blocked users", "CONTACT", onContacts) - LinkRow("Sound Settings", "Devices, transmission, voice activation, processing, volume", "PLAYBACK") { - page = SettingsPage.SOUND - } - LinkRow("Network", "Bitrate, error correction, redundancy, buffering", "PING_4") { - page = SettingsPage.NETWORK - } - LinkRow("Giant PTT", "A push-to-talk button filling the screen", "CAPTURE") { - page = SettingsPage.GIANT_PTT - } - LinkRow("Design", "Icon pack, country flags, client colours, description pictures", "GUISETUP") { - page = SettingsPage.DESIGN - } - LinkRow("Identities", "Create, import, export, security level", - "IDENTITY_MANAGER") { page = SettingsPage.IDENTITIES } - LinkRow("myTeamSpeak", - if (vm.myTeamSpeak.isSignedIn) "Signed in as ${vm.myTeamSpeak.username()}" - else "Sign in to bring over your synchronised bookmarks and identities", - "MYTS_ACCOUNT") { page = SettingsPage.MY_TEAMSPEAK } - } - } -} - -@Composable -private fun DesignScreen(vm: SessionController, onBack: () -> Unit) { - SubScreen("Design", onBack) { padding -> - Column(Modifier.padding(padding).verticalScroll(rememberScrollState())) { - IconPackPicker(vm.icons) - var pictures by remember { mutableStateOf(vm.settings.descriptionPictures) } - Toggle("Show pictures in descriptions", pictures) { - pictures = it - vm.setDescriptionPictures(it) - } - Section("Channel tree") - var flags by remember { mutableStateOf(vm.settings.countryFlags) } - Toggle("Show country flags in the channel tree", flags) { - flags = it - vm.setCountryFlags(it) - } - val colors = vm.settings.clientRowColors - var any by remember { mutableIntStateOf(colors.any) } - var talking by remember { mutableIntStateOf(colors.talking) } - var mutedAway by remember { mutableIntStateOf(colors.mutedAway) } - RowColorPicker("Client background", any) { - any = it - colors.any = it - vm.clientRowColorsChanged() - } - RowColorPicker("While talking", talking) { - talking = it - colors.talking = it - vm.clientRowColorsChanged() - } - RowColorPicker("Muted / away", mutedAway) { - mutedAway = it - colors.mutedAway = it - vm.clientRowColorsChanged() - } - } - } -} - -/** Chooses the icon pack, and brings in TeamSpeak packs from a file. */ -@Composable -private fun IconPackPicker(theme: IconTheme) { - val packs by theme.packs.collectAsStateWithLifecycle() - val active by theme.active.collectAsStateWithLifecycle() - val scope = rememberCoroutineScope() - var failed by remember { mutableStateOf(null) } - val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> - if (uri != null) scope.launch { - val pack = withContext(Dispatchers.IO) { runCatching { theme.import(uri) }.getOrNull() } - failed = if (pack == null) "That file is not an icon pack." else null - } - } - Picker("Icon pack", packs.map { it to it.name() }, active) { theme.select(it) } - LinkRow("Import icon pack", "A TeamSpeak 3 pack (.zip), such as those in the gfx folder of a TeamSpeak 3 install") { - importer.launch(arrayOf("application/zip", "application/octet-stream")) - } - failed?.let { Hint(it) } -} - diff --git a/android/app/src/main/java/com/ts3client/android/ui/SettingsWidgets.kt b/android/app/src/main/java/com/ts3client/android/ui/SettingsWidgets.kt deleted file mode 100644 index 6bb9547..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/SettingsWidgets.kt +++ /dev/null @@ -1,175 +0,0 @@ -package com.ts3client.android.ui - -import androidx.activity.compose.BackHandler -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.BoxWithConstraints -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.PaddingValues -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.RowScope -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.ArrowBack -import androidx.compose.material3.DropdownMenu -import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.RadioButton -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SegmentedButton -import androidx.compose.material3.SegmentedButtonDefaults -import androidx.compose.material3.SingleChoiceSegmentedButtonRow -import androidx.compose.material3.Slider -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.SnackbarHostState -import androidx.compose.material3.Switch -import androidx.compose.material3.Text -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableFloatStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp - -/** The width a segment needs for a label of a word or two; narrower screens get a list instead. */ -private val SEGMENT_WIDTH = 110.dp - -/** A full-screen page with a back arrow; the system back gesture leaves it the same way. */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -internal fun SubScreen( - title: String, - onBack: () -> Unit, - actions: @Composable RowScope.() -> Unit = {}, - snackbar: SnackbarHostState? = null, - content: @Composable (PaddingValues) -> Unit, -) { - BackHandler(onBack = onBack) - Scaffold( - snackbarHost = { snackbar?.let { SnackbarHost(it) } }, - topBar = { - TopAppBar( - title = { Text(title, maxLines = 1, overflow = TextOverflow.Ellipsis) }, - navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } }, - actions = actions, - ) - }, - content = content, - ) -} - -/** A row that opens another page, or does one thing when tapped. */ -@Composable -internal fun LinkRow(title: String, summary: String?, iconKey: String? = null, onClick: () -> Unit) { - ListItem( - headlineContent = { Text(title) }, - supportingContent = summary?.let { { Text(it) } }, - leadingContent = iconKey?.let { { PackIcon(it, null) } }, - modifier = Modifier.clickable(onClick = onClick), - ) -} - -@Composable -internal fun Section(title: String) { - Text(title, Modifier.padding(start = 16.dp, top = 24.dp, bottom = 4.dp), - style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary) -} - -@Composable -internal fun Choice(label: String, selected: Boolean, onSelect: () -> Unit) { - Row(Modifier.fillMaxWidth().clickable(onClick = onSelect).padding(horizontal = 16.dp, vertical = 4.dp), - verticalAlignment = Alignment.CenterVertically) { - RadioButton(selected, onClick = onSelect) - Text(label, Modifier.padding(start = 8.dp)) - } -} - -/** One of [options] as a row of segments, or as radio buttons where the segments would not fit. */ -@Composable -internal fun Segments(options: List>, selected: T, onSelect: (T) -> Unit) { - BoxWithConstraints(Modifier.fillMaxWidth()) { - if (maxWidth - 32.dp < SEGMENT_WIDTH * options.size) { - Column { for ((value, label) in options) Choice(label, value == selected) { onSelect(value) } } - return@BoxWithConstraints - } - SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp)) { - options.forEachIndexed { index, (value, label) -> - SegmentedButton( - selected = value == selected, - onClick = { onSelect(value) }, - shape = SegmentedButtonDefaults.itemShape(index, options.size), - ) { Text(label, maxLines = 1, overflow = TextOverflow.Ellipsis) } - } - } - } -} - -@Composable -internal fun Toggle(label: String, checked: Boolean, onChange: (Boolean) -> Unit) { - Row(Modifier.fillMaxWidth().clickable { onChange(!checked) }.padding(horizontal = 16.dp, vertical = 2.dp), - verticalAlignment = Alignment.CenterVertically) { - Text(label, Modifier.weight(1f)) - Switch(checked, onChange) - } -} - -@Composable -internal fun Hint(text: String) { - Text(text, Modifier.padding(horizontal = 16.dp, vertical = 2.dp), - style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) -} - -/** One of [options], shown as its label and picked from a menu. */ -@Composable -internal fun Picker(label: String, options: List>, selected: T, onSelect: (T) -> Unit) { - var open by remember { mutableStateOf(false) } - Box { - Column(Modifier.fillMaxWidth().clickable { open = true }.padding(horizontal = 16.dp, vertical = 8.dp)) { - Text(label) - Text(options.firstOrNull { it.first == selected }?.second ?: "", style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant) - } - DropdownMenu(open, { open = false }) { - for ((value, text) in options) { - DropdownMenuItem({ Text(text) }, onClick = { - open = false - onSelect(value) - }) - } - } - } -} - -/** A slider that applies its value once let go of. */ -@Composable -internal fun Level( - label: String, - value: Float, - range: ClosedFloatingPointRange, - format: (Float) -> String, - steps: Int = 0, - onChange: (Float) -> Unit = {}, - onDone: (Float) -> Unit, -) { - var current by remember(value) { mutableFloatStateOf(value) } - Column(Modifier.padding(horizontal = 16.dp, vertical = 4.dp)) { - Row { - Text(label, Modifier.weight(1f)) - Text(format(current), color = MaterialTheme.colorScheme.onSurfaceVariant) - } - Slider(current, { - current = it - onChange(it) - }, valueRange = range, steps = steps, onValueChangeFinished = { onDone(current) }) - } -} diff --git a/android/app/src/main/java/com/ts3client/android/ui/Sheets.kt b/android/app/src/main/java/com/ts3client/android/ui/Sheets.kt deleted file mode 100644 index 30e3d61..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/Sheets.kt +++ /dev/null @@ -1,238 +0,0 @@ -package com.ts3client.android.ui - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.navigationBarsPadding -import androidx.compose.foundation.layout.padding -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.ListItem -import androidx.compose.material3.ListItemDefaults -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.ModalBottomSheet -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Slider -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableFloatStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.text.input.PasswordVisualTransformation -import androidx.compose.ui.text.input.VisualTransformation -import androidx.compose.ui.unit.dp -import androidx.compose.foundation.clickable -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import com.ts3client.android.ChannelItem -import com.ts3client.android.ClientItem -import com.ts3client.contacts.ContactType -import com.ts3client.net.Details -import kotlin.math.roundToInt - -/** What can be done with a client: the private chat, a poke, a move, their volume, filing them as a contact. */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun ClientSheet( - client: ClientItem, - details: Details?, - onLink: (String) -> Unit, - away: Boolean, - initialVolume: Double, - onDismiss: () -> Unit, - onMessage: () -> Unit, - onPoke: (String) -> Unit, - onVolume: (Double) -> Unit, - onAway: (Boolean) -> Unit, - onAddContact: (ContactType) -> Unit, - onEditContact: () -> Unit, - onConnectionInfo: () -> Unit, - onWhisper: () -> Unit, - onAddToWhisperList: () -> Unit, - /** Null when the client cannot be moved. */ - onMove: (() -> Unit)?, - /** Null when the client cannot be moved, or is in our channel already. */ - onMoveToOwnChannel: (() -> Unit)?, - /** Null when the sheet was opened from the tree. */ - onFindInTree: (() -> Unit)?, - /** Kicks, bans and groups, as far as we may use them. */ - moderation: @Composable () -> Unit = {}, -) { - var poking by remember { mutableStateOf(false) } - ModalBottomSheet(onDismissRequest = onDismiss) { - Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) { - Row(Modifier.padding(horizontal = 24.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp)) { - StatusIcon(client.status) - Column(Modifier.weight(1f)) { - // The country's flag goes before the name, as in TeamSpeak's info frame. - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { - CountryFlag(client.country) - Text(client.name, style = MaterialTheme.typography.titleLarge) - } - if (client.name != client.nickname) Text(client.nickname, style = MaterialTheme.typography.bodyMedium) - if (client.awayMessage.isNotEmpty()) Text(client.awayMessage, style = MaterialTheme.typography.bodyMedium) - } - val viewer = LocalPictureViewer.current - val images = LocalServerImages.current - Avatar(client.uniqueId, client.avatarFlag, Modifier.clickable(enabled = viewer != null && images != null) { - viewer?.invoke(ViewedPicture("avatar_${client.nickname}", ownAvatar = client.self) { - images?.avatarData(client.uniqueId, client.avatarFlag) - }) - }) - } - details?.let { DetailsSection(it, onLink, Modifier.padding(bottom = 8.dp)) } - onFindInTree?.let { Action("CHANNEL_SWITCH", "Find client in channel tree", onClick = it) } - Action("INFO", "Connection info", onClick = onConnectionInfo) - if (client.self) { - Action("AWAY", if (away) "Back" else "Away") { onAway(!away) } - moderation() - } else { - Action("PLAYER_CHAT", "Send message", onClick = onMessage) - Action("POKE", "Poke") { poking = true } - Action("PLAYER_WHISPER", "Whisper", onClick = onWhisper) - Action("ON_WHISPERLIST", "Add to whisper list…", onClick = onAddToWhisperList) - onMove?.let { Action("CHANNEL_SWITCH", "Move to channel…", onClick = it) } - onMoveToOwnChannel?.let { Action("MOVE_CLIENT_TO_OWN_CHANNEL", "Move to own channel", onClick = it) } - moderation() - if (client.contactType == null) { - Row { - Action("ADD_FRIEND", "Add as friend", Modifier.weight(1f)) { onAddContact(ContactType.FRIEND) } - Action("ADD_FOE", "Block", Modifier.weight(1f)) { onAddContact(ContactType.BLOCKED) } - } - } else { - Action("EDIT_FRIEND_FOE_STATUS", "Edit contact", onClick = onEditContact) - } - var volume by remember { mutableFloatStateOf(initialVolume.toFloat()) } - Text("Volume: ${if (volume > 0) "+" else ""}${volume.roundToInt()} dB", - Modifier.padding(start = 24.dp, top = 8.dp), style = MaterialTheme.typography.bodyMedium) - Slider( - volume, { volume = it.roundToInt().toFloat() }, - Modifier.padding(horizontal = 24.dp), - valueRange = -30f..20f, - onValueChangeFinished = { onVolume(volume.toDouble()) }, - ) - } - } - } - if (poking) { - TextPrompt( - title = "Poke ${client.name}", - label = "Message", - confirm = "Poke", - onDismiss = { poking = false }, - onConfirm = { poking = false; onPoke(it) }, - ) - } -} - -/** What can be done with a channel: join it, whether to hear who is in it, whisper to it, its files, and editing it. */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun ChannelSheet( - channel: ChannelItem, - details: Details?, - onLink: (String) -> Unit, - current: Boolean, - onDismiss: () -> Unit, - onJoin: () -> Unit, - onSubscribe: (Boolean) -> Unit, - onBookmark: () -> Unit, - onWhisper: () -> Unit, - onAddToWhisperList: () -> Unit, - onFiles: () -> Unit, - /** Each null when we may not. */ - onCreateSub: (() -> Unit)?, - onEdit: (() -> Unit)?, - onDelete: (() -> Unit)?, -) { - ModalBottomSheet(onDismissRequest = onDismiss) { - Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) { - Text(channel.name, Modifier.padding(horizontal = 24.dp, vertical = 8.dp), - style = MaterialTheme.typography.titleLarge) - details?.let { DetailsSection(it, onLink, Modifier.padding(bottom = 8.dp)) } - if (!current) { - Action("CHANNEL_SWITCH", "Join", onClick = onJoin) - } - if (channel.subscribed) { - Action("UNSUBSCRIBE_FROM_CHANNEL", "Unsubscribe") { onSubscribe(false) } - } else { - Action("SUBSCRIBE_TO_CHANNEL", "Subscribe") { onSubscribe(true) } - } - Action("WHISPER", "Whisper", onClick = onWhisper) - Action("ON_WHISPERLIST", "Add to whisper list…", onClick = onAddToWhisperList) - Action("FILETRANSFER", "Browse files", onClick = onFiles) - Action("BOOKMARK_ADD", "Add to bookmarks", onClick = onBookmark) - onCreateSub?.let { Action("CHANNEL_CREATE_SUB", "Create sub-channel", onClick = it) } - onEdit?.let { Action("CHANNEL_EDIT", "Edit channel", onClick = it) } - onDelete?.let { Action("CHANNEL_DELETE", "Delete channel", onClick = it) } - } - } -} - -/** The server's details: its version, who is on it, its welcome message. */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun ServerSheet( - details: Details, - onLink: (String) -> Unit, - onDismiss: () -> Unit, - onBookmark: () -> Unit, - onBanList: (() -> Unit)?, - onCreateChannel: (() -> Unit)?, -) { - ModalBottomSheet(onDismissRequest = onDismiss) { - Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) { - Row(Modifier.padding(horizontal = 24.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp)) { - PackIcon("SERVER_GREEN", null) - Text(details.title(), style = MaterialTheme.typography.titleLarge) - } - DetailsSection(details, onLink) - Action("BOOKMARK_ADD", "Add to bookmarks", onClick = onBookmark) - onCreateChannel?.let { Action("CHANNEL_CREATE", "Create channel", onClick = it) } - onBanList?.let { Action("BAN_LIST", "Ban list", onClick = it) } - } - } -} - -@Composable -internal fun Action(iconKey: String, label: String, modifier: Modifier = Modifier.fillMaxWidth(), onClick: () -> Unit) { - ListItem( - headlineContent = { Text(label) }, - leadingContent = { PackIcon(iconKey, null) }, - colors = ListItemDefaults.colors(containerColor = Color.Transparent), - modifier = modifier.clickable(onClick = onClick).padding(horizontal = 8.dp), - ) -} - -/** Asks for one line of text. */ -@Composable -fun TextPrompt( - title: String, - label: String, - confirm: String, - onDismiss: () -> Unit, - onConfirm: (String) -> Unit, - initial: String = "", - password: Boolean = false, -) { - var text by remember { mutableStateOf(initial) } - AlertDialog( - onDismissRequest = onDismiss, - title = { Text(title) }, - text = { - OutlinedTextField(text, { text = it }, label = { Text(label) }, singleLine = true, - visualTransformation = if (password) PasswordVisualTransformation() else VisualTransformation.None) - }, - confirmButton = { TextButton(onClick = { onConfirm(text) }) { Text(confirm) } }, - dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, - ) -} diff --git a/android/app/src/main/java/com/ts3client/android/ui/SoundSettingsScreen.kt b/android/app/src/main/java/com/ts3client/android/ui/SoundSettingsScreen.kt deleted file mode 100644 index 33e932a..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/SoundSettingsScreen.kt +++ /dev/null @@ -1,260 +0,0 @@ -package com.ts3client.android.ui - -import android.content.Intent -import android.net.Uri -import android.provider.Settings.ACTION_MANAGE_OVERLAY_PERMISSION -import android.provider.Settings.canDrawOverlays -import androidx.activity.compose.rememberLauncherForActivityResult -import androidx.activity.result.contract.ActivityResultContracts -import androidx.compose.foundation.Canvas -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableFloatStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Modifier -import androidx.compose.ui.geometry.CornerRadius -import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.geometry.Size -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.unit.dp -import androidx.lifecycle.compose.LifecycleStartEffect -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import com.ts3client.android.MicLevel -import com.ts3client.android.SessionController -import com.ts3client.android.audio.AudioRoute -import com.ts3client.audio.AudioDevice -import com.ts3client.audio.InputLevel -import com.ts3client.config.Settings -import kotlin.math.roundToInt - -private val DENOISE_LEVELS = listOf("Off", "6 dB", "12 dB", "18 dB", "21 dB") - -/** Audio devices, transmission, voice activation, processing and playback. */ -@Composable -fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) { - val settings = vm.settings - fun change(edit: Settings.() -> Unit) { - settings.edit() - vm.applySettings() - } - var inputMode by remember { mutableStateOf(settings.inputMode) } - var vadMode by remember { mutableStateOf(settings.vadMode) } - var agc by remember { mutableStateOf(settings.agc) } - var mutedTalkWarning by remember { mutableStateOf(settings.mutedTalkWarning) } - var threshold by remember { mutableFloatStateOf(settings.vadThresholdDb.toFloat()) } - var inputDevice by remember { mutableStateOf(settings.inputDevice) } - var outputDevice by remember { mutableStateOf(settings.outputDevice) } - val inputs by vm.inputDevices.collectAsStateWithLifecycle() - val outputs by vm.outputDevices.collectAsStateWithLifecycle() - val route by vm.route.collectAsStateWithLifecycle() - val level by vm.micLevel.collectAsStateWithLifecycle() - val packs by vm.soundPacks.collectAsStateWithLifecycle() - var pack by remember { mutableStateOf(vm.soundPack?.id()) } - LifecycleStartEffect(Unit) { - vm.watchLevel(true) - onStopOrDispose { vm.watchLevel(false) } - } - - SubScreen("Sound Settings", onBack) { padding -> - Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { - Section("Devices") - DevicePicker("Microphone", inputs, inputDevice) { - inputDevice = it - change { this.inputDevice = it } - } - DevicePicker("Speaker", outputs, outputDevice) { - outputDevice = it - change { this.outputDevice = it } - } - Picker( - "Microphone preset", - INPUT_PRESETS.map { (preset, label) -> - val unsupported = preset == AudioRoute.InputPreset.UNPROCESSED && !vm.unprocessedSupported - preset to if (unsupported) "$label (not supported here)" else label - }, - route.inputPreset(), - ) { vm.setRoute(AudioRoute(it, route.usage())) } - Hint(PRESET_HINTS.getValue(route.inputPreset())) - Text("Play voices", Modifier.padding(start = 16.dp, top = 8.dp)) - for ((usage, label) in USAGES) { - Choice(label, route.usage() == usage) { vm.setRoute(AudioRoute(route.inputPreset(), usage)) } - } - - Section("Transmission") - for ((mode, label) in INPUT_MODES) { - Choice(label, inputMode == mode) { - inputMode = mode - change { this.inputMode = mode } - } - } - if (inputMode == Settings.InputMode.PUSH_TO_TALK) FloatingButtonToggle(vm) - val gated = inputMode == Settings.InputMode.VOICE_ACTIVATION && vadMode != Settings.VadMode.AUTOMATIC - LevelMeter(level, threshold.takeIf { gated }) - if (!level.live) { - Hint(if (vm.hasMicPermission()) "The microphone is not available right now." else "Allow the microphone to see its level.") - } - - if (inputMode == Settings.InputMode.VOICE_ACTIVATION) { - Section("Voice activation") - for ((mode, label) in VAD_MODES) { - Choice(label, vadMode == mode) { - vadMode = mode - change { this.vadMode = mode } - } - } - if (vadMode != Settings.VadMode.AUTOMATIC) { - Level("Volume threshold", settings.vadThresholdDb.toFloat(), -50f..50f, { "${it.roundToInt()}" }, - onChange = { threshold = it }) { - change { vadThresholdDb = it.roundToInt().toDouble() } - } - } - if (vadMode != Settings.VadMode.VOLUME_GATE) { - Level("Speech likelihood", settings.speechThreshold.toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) { - change { speechThreshold = it.toDouble() } - } - } - } - - Section("Processing") - val suppression = if (settings.denoise) settings.denoiserLevel + 1 else 0 - Level("Noise suppression", suppression.toFloat(), 0f..DENOISE_LEVELS.lastIndex.toFloat(), - { DENOISE_LEVELS[it.roundToInt()] }, steps = DENOISE_LEVELS.lastIndex - 1) { - val step = it.roundToInt() - change { - denoise = step > 0 - if (step > 0) denoiserLevel = step - 1 - } - } - Toggle("Automatic gain control", agc) { - agc = it - change { this.agc = it } - } - if (agc) { - Level("Boost quiet speech", settings.agcBoostDb.toFloat(), 0f..Settings.MAX_AGC_BOOST_DB.toFloat(), - { "+${it.roundToInt()} dB" }, steps = Settings.MAX_AGC_BOOST_DB - 1) { - change { agcBoostDb = it.roundToInt() } - } - } - - Section("Playback") - Level("Volume", settings.outputVolume.toFloat(), 0f..2f, { "${(it * 100).roundToInt()} %" }) { - change { outputVolume = it.toDouble() } - } - - Section("Notification sounds") - if (packs.isEmpty()) { - Hint("This build of the app came without sound packs.") - } else { - Picker("Sound pack", packs.map { it.id() to it.name() }, pack) { id -> - packs.firstOrNull { it.id() == id }?.let(vm::setSoundPack) - pack = id - } - } - Level("Volume", settings.soundVolume.toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) { - change { soundVolume = it.toDouble() } - } - Toggle("Beep when talking while muted", mutedTalkWarning) { - mutedTalkWarning = it - change { this.mutedTalkWarning = it } - } - } - } -} - -private val INPUT_MODES = listOf( - Settings.InputMode.VOICE_ACTIVATION to "Voice activation", - Settings.InputMode.PUSH_TO_TALK to "Push to talk", - Settings.InputMode.CONTINUOUS to "Continuous", -) - -private val INPUT_PRESETS = listOf( - AudioRoute.InputPreset.VOICE_RECOGNITION to "Voice recognition", - AudioRoute.InputPreset.VOICE_COMMUNICATION to "Voice communication", - AudioRoute.InputPreset.UNPROCESSED to "Unprocessed", - AudioRoute.InputPreset.VOICE_PERFORMANCE to "Voice performance", - AudioRoute.InputPreset.GENERIC to "Generic", - AudioRoute.InputPreset.CAMCORDER to "Camcorder", -) - -private val PRESET_HINTS = mapOf( - AudioRoute.InputPreset.VOICE_RECOGNITION to "Little or no processing by the phone; the client's own does the rest.", - AudioRoute.InputPreset.VOICE_COMMUNICATION to - "The phone's call processing: echo cancellation, noise suppression and gain. Works best with voices played as a call.", - AudioRoute.InputPreset.UNPROCESSED to "The raw microphone signal.", - AudioRoute.InputPreset.VOICE_PERFORMANCE to "Low latency and no processing, meant for live performance.", - AudioRoute.InputPreset.GENERIC to "The phone's default microphone source, with whatever it applies to it.", - AudioRoute.InputPreset.CAMCORDER to "Tuned for recording video, often with the rear microphone.", -) - -private val USAGES = listOf( - AudioRoute.Usage.MEDIA to "As media (Bluetooth stays in high quality)", - AudioRoute.Usage.VOICE_COMMUNICATION to "As a call (lets the phone cancel echo)", -) - -private val VAD_MODES = listOf( - Settings.VadMode.AUTOMATIC to "Automatic", - Settings.VadMode.VOLUME_GATE to "Volume gate", - Settings.VadMode.HYBRID to "Hybrid", -) - -/** The push-to-talk button over other apps, which first needs the user to allow the app to draw there. */ -@Composable -private fun FloatingButtonToggle(vm: SessionController) { - val context = LocalContext.current - val enabled by vm.pttOverlay.collectAsStateWithLifecycle() - val allow = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { - if (canDrawOverlays(context)) vm.setPttOverlay(true) - } - Toggle("Floating button over other apps", enabled && canDrawOverlays(context)) { on -> - if (!on || canDrawOverlays(context)) vm.setPttOverlay(on) - else allow.launch(Intent(ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:${context.packageName}"))) - } - Hint("Hold it to talk. Double-tap and keep holding to drag it elsewhere.") -} - -/** Picks a device by its settings id; one that is not plugged in now still shows as chosen. */ -@Composable -private fun DevicePicker(label: String, devices: List, selected: String, onSelect: (String) -> Unit) { - val options = devices.map { it.id() to it.label() }.let { list -> - if (list.any { it.first == selected }) list else list + (selected to "Not connected") - } - Picker(label, options, selected, onSelect) -} - -/** The microphone level, lit while it would be sent, with the volume gate's threshold marked. */ -@Composable -private fun LevelMeter(level: MicLevel, thresholdDb: Float?) { - val track = MaterialTheme.colorScheme.surfaceVariant - val fill = if (level.transmitting) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline - val marker = MaterialTheme.colorScheme.onSurface - fun fraction(db: Double) = - ((db - InputLevel.MIN_DB) / (InputLevel.MAX_DB - InputLevel.MIN_DB)).toFloat().coerceIn(0f, 1f) - Column(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) { - Row { - Text("Microphone level", Modifier.weight(1f)) - if (level.live) Text("${level.db.roundToInt()}", color = MaterialTheme.colorScheme.onSurfaceVariant) - } - Canvas(Modifier.fillMaxWidth().padding(top = 6.dp).height(12.dp)) { - val radius = CornerRadius(size.height / 2) - drawRoundRect(track, cornerRadius = radius) - if (level.live) { - drawRoundRect(fill, size = Size(size.width * fraction(level.db), size.height), cornerRadius = radius) - } - if (thresholdDb != null) { - val x = size.width * fraction(thresholdDb.toDouble()) - drawLine(marker, Offset(x, -2.dp.toPx()), Offset(x, size.height + 2.dp.toPx()), strokeWidth = 2.dp.toPx()) - } - } - } -} diff --git a/android/app/src/main/java/com/ts3client/android/ui/Theme.kt b/android/app/src/main/java/com/ts3client/android/ui/Theme.kt deleted file mode 100644 index b70e551..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/Theme.kt +++ /dev/null @@ -1,38 +0,0 @@ -package com.ts3client.android.ui - -import androidx.compose.foundation.isSystemInDarkTheme -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.dynamicDarkColorScheme -import androidx.compose.material3.dynamicLightColorScheme -import androidx.compose.runtime.Composable -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.platform.LocalContext - -/** Colours that mean the same in either theme, as TeamSpeak uses them. */ -object StatusColors { - val talking = Color(0xFF2E9BF0) - val muted = Color(0xFFD9443A) - val away = Color(0xFF9E8A2E) - val friend = Color(0xFF3A9D4A) - val blocked = Color(0xFFD9443A) -} - -/** Links in chat and descriptions: blue, as links are, whatever the wallpaper's colours. */ -@Composable -fun linkColor(): Color = if (isSystemInDarkTheme()) Color(0xFF7AB4FF) else Color(0xFF1A62D0) - -/** Behind every match of the find bar's query, as on the desktop. */ -@Composable -fun findMatchColor(): Color = if (isSystemInDarkTheme()) Color(0xFF5C4E1A) else Color(0xFFFFEBA3) - -/** Behind the match the find bar is on. */ -@Composable -fun findCurrentColor(): Color = if (isSystemInDarkTheme()) Color(0xFF9C6A12) else Color(0xFFFFB84D) - -/** The system's own (wallpaper) colours, which every supported Android version offers. */ -@Composable -fun Ts3Theme(content: @Composable () -> Unit) { - val context = LocalContext.current - val colors = if (isSystemInDarkTheme()) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) - MaterialTheme(colorScheme = colors, content = content) -} diff --git a/android/app/src/main/java/com/ts3client/android/ui/Whisper.kt b/android/app/src/main/java/com/ts3client/android/ui/Whisper.kt deleted file mode 100644 index 40334b2..0000000 --- a/android/app/src/main/java/com/ts3client/android/ui/Whisper.kt +++ /dev/null @@ -1,254 +0,0 @@ -package com.ts3client.android.ui - -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.lazy.itemsIndexed -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Close -import androidx.compose.material.icons.filled.MoreVert -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.DropdownMenu -import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.ListItem -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import com.ts3client.android.ServerController -import com.ts3client.android.SessionController -import com.ts3client.android.SessionState -import com.ts3client.config.WhisperList -import com.ts3client.net.Whisper - -/** Says the microphone whispers instead of talking in the channel, until stopped. */ -@Composable -fun WhisperBanner(state: SessionState, onStop: () -> Unit) { - val target = state.whisper ?: return - Surface(color = MaterialTheme.colorScheme.tertiaryContainer) { - Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) { - PackIcon("WHISPER", null) - Column(Modifier.weight(1f).padding(horizontal = 12.dp)) { - Text("Whispering to $target", maxLines = 1, overflow = TextOverflow.Ellipsis, - style = MaterialTheme.typography.bodyMedium) - if (state.whisperNobody) { - Text("Nobody there", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) - } - } - TextButton(onClick = onStop) { Text("Stop") } - } - } -} - -/** The top bar's whisper button: a list to whisper to, a reply to the last whisper, the lists' editor. */ -@Composable -fun WhisperMenu(vm: SessionController, server: ServerController, state: SessionState, onManage: () -> Unit) { - val lists by vm.whisperLists.collectAsStateWithLifecycle() - var open by remember { mutableStateOf(false) } - Box { - IconButton(onClick = { open = true }) { PackIcon("WHISPER", "Whisper") } - DropdownMenu(open, { open = false }) { - val replyTo = remember(open) { server.lastWhisperer() } - replyTo?.let { client -> - DropdownMenuItem({ Text("Reply to ${client.nickname}") }, leadingIcon = { PackIcon("PLAYER_WHISPER", null) }, - onClick = { open = false; server.whisperToClient(client.id) }) - } - for (list in lists) { - DropdownMenuItem({ Text(list.name.ifBlank { "Unnamed" }) }, - leadingIcon = { PackIcon("ON_WHISPERLIST", null) }, - enabled = !list.isEmpty, - onClick = { open = false; server.setWhisper(Whisper.of(list)) }) - } - if (state.whisper != null) { - DropdownMenuItem({ Text("Stop whispering") }, leadingIcon = { PackIcon("WHISPER", null) }, - onClick = { open = false; server.setWhisper(null) }) - } - if (replyTo != null || lists.isNotEmpty() || state.whisper != null) HorizontalDivider() - DropdownMenuItem({ Text("Whisper lists…") }, leadingIcon = { PackIcon("WHISPERLISTS", null) }, - onClick = { open = false; onManage() }) - } - } -} - -/** Picks the whisper list to add something to, or names a new one. */ -@Composable -fun AddToWhisperListDialog(vm: SessionController, what: String, onDismiss: () -> Unit, onPick: (index: Int, newName: String) -> Unit) { - val lists by vm.whisperLists.collectAsStateWithLifecycle() - var naming by remember { mutableStateOf(false) } - if (naming) { - TextPrompt("New whisper list", "Name", "Add", onDismiss = onDismiss, onConfirm = { - if (it.isNotBlank()) onPick(-1, it.trim()) else onDismiss() - }) - return - } - AlertDialog( - onDismissRequest = onDismiss, - title = { Text("Add $what to") }, - text = { - Column(Modifier.verticalScroll(rememberScrollState())) { - lists.forEachIndexed { index, list -> - ListItem(headlineContent = { Text(list.name.ifBlank { "Unnamed" }) }, - modifier = Modifier.clickable { onPick(index, "") }) - } - ListItem(headlineContent = { Text("New list…") }, modifier = Modifier.clickable { naming = true }) - } - }, - confirmButton = {}, - dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, - ) -} - -/** The saved whisper lists, each opening onto its channels and clients. */ -@Composable -fun WhisperListsScreen(vm: SessionController, server: ServerController, onBack: () -> Unit) { - val lists by vm.whisperLists.collectAsStateWithLifecycle() - /** The list being edited: its index, -1 for a new one; null on the overview. */ - var editing by rememberSaveable { mutableStateOf(null) } - editing?.let { index -> - WhisperListScreen(vm, server, index, lists.getOrNull(index) ?: WhisperList(), onBack = { editing = null }) - return - } - SubScreen("Whisper lists", onBack = onBack, actions = { - TextButton(onClick = { editing = -1 }) { Text("New") } - }) { padding -> - if (lists.isEmpty()) { - Box(Modifier.padding(padding).fillMaxWidth().padding(24.dp)) { - Text("No whisper lists", color = MaterialTheme.colorScheme.onSurfaceVariant) - } - return@SubScreen - } - LazyColumn(Modifier.padding(padding)) { - itemsIndexed(lists) { index, list -> - var menu by remember { mutableStateOf(false) } - ListItem( - headlineContent = { Text(list.name.ifBlank { "Unnamed" }) }, - supportingContent = { Text(summary(list)) }, - leadingContent = { PackIcon("ON_WHISPERLIST", null) }, - trailingContent = { - Box { - IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "List options") } - DropdownMenu(menu, { menu = false }) { - DropdownMenuItem({ Text("Whisper") }, enabled = !list.isEmpty, onClick = { - menu = false - server.setWhisper(Whisper.of(list)) - onBack() - }) - DropdownMenuItem({ Text("Remove") }, onClick = { menu = false; vm.removeWhisperList(index) }) - } - } - }, - modifier = Modifier.clickable { editing = index }, - ) - } - } - } -} - -private fun summary(list: WhisperList): String { - val parts = listOfNotNull( - list.channels.size.takeIf { it > 0 }?.let { if (it == 1) "1 channel" else "$it channels" }, - list.clients.size.takeIf { it > 0 }?.let { if (it == 1) "1 client" else "$it clients" }, - ) - return parts.joinToString(", ").ifEmpty { "Empty" } -} - -/** One whisper list: its name, channels and clients, saved on Save. */ -@Composable -private fun WhisperListScreen(vm: SessionController, server: ServerController, index: Int, saved: WhisperList, onBack: () -> Unit) { - var name by rememberSaveable { mutableStateOf(saved.name) } - var list by remember { mutableStateOf(saved.copy()) } - val change = { f: WhisperList.() -> Unit -> list = list.copy().apply(f) } - var addingChannel by remember { mutableStateOf(false) } - var addingClient by remember { mutableStateOf(false) } - - SubScreen(if (index < 0) "New whisper list" else "Edit whisper list", onBack = onBack, actions = { - TextButton(onClick = { - vm.saveWhisperList(index, list.copy().apply { this.name = name.trim() }) - onBack() - }, enabled = name.isNotBlank()) { Text("Save") } - }) { padding -> - LazyColumn(Modifier.padding(padding)) { - item { - OutlinedTextField(name, { name = it }, Modifier.fillMaxWidth().padding(16.dp), label = { Text("Name") }, - singleLine = true) - } - item { Section("Channels") } - items(list.channels) { channel -> - RemovableRow("CHANNEL_GREEN", channel) { change { channels.remove(channel) } } - } - item { LinkRow("Add channel…", null, "CHANNEL_CREATE") { addingChannel = true } } - item { Section("Clients") } - items(list.clients) { client -> - RemovableRow("PLAYER_WHISPER", client.nickname.ifBlank { client.uniqueId }) { change { clients.remove(client) } } - } - item { LinkRow("Add client…", null, "ADD_FRIEND") { addingClient = true } } - } - } - - if (addingChannel) { - val paths = remember { server.channelPaths().filter { it !in list.channels } } - ChoiceDialog("Add channel", paths, { it }, onDismiss = { addingChannel = false }) { - addingChannel = false - change { channels.add(it) } - } - } - if (addingClient) { - val online = remember { server.clientRefs().filter { c -> list.clients.none { it.uniqueId == c.uniqueId } } } - ChoiceDialog("Add client", online, { it.nickname }, onDismiss = { addingClient = false }) { - addingClient = false - change { clients.add(it) } - } - } -} - -@Composable -private fun RemovableRow(iconKey: String, label: String, onRemove: () -> Unit) { - ListItem( - headlineContent = { Text(label, maxLines = 1, overflow = TextOverflow.Ellipsis) }, - leadingContent = { PackIcon(iconKey, null) }, - trailingContent = { IconButton(onClick = onRemove) { Icon(Icons.Default.Close, "Remove") } }, - ) -} - -/** Picks one of [choices], of the server on screen; says so when it has none. */ -@Composable -private fun ChoiceDialog(title: String, choices: List, label: (T) -> String, onDismiss: () -> Unit, onPick: (T) -> Unit) { - AlertDialog( - onDismissRequest = onDismiss, - title = { Text(title) }, - text = { - if (choices.isEmpty()) Text("Nothing to add on this server") - else LazyColumn(Modifier.heightIn(max = 400.dp)) { - items(choices) { choice -> - ListItem(headlineContent = { Text(label(choice), maxLines = 1, overflow = TextOverflow.Ellipsis) }, - modifier = Modifier.clickable { onPick(choice) }) - } - } - }, - confirmButton = {}, - dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, - ) -} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/AudioRoutePrefs.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/AudioRoutePrefs.kt new file mode 100644 index 0000000..9e6669b --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/AudioRoutePrefs.kt @@ -0,0 +1,30 @@ +package eu.lixko.ts3j.client.android + +import android.content.Context +import eu.lixko.ts3j.client.android.audio.AudioRoute + +/** Where the Android-only audio choices are kept; the rest live in the shared settings. */ +class AudioRoutePrefs(context: Context) { + + private val prefs = context.getSharedPreferences("audio", Context.MODE_PRIVATE) + + fun load(): AudioRoute = AudioRoute( + enumOr(prefs.getString(INPUT_PRESET, null), AudioRoute.DEFAULT.inputPreset()), + enumOr(prefs.getString(USAGE, null), AudioRoute.DEFAULT.usage()), + ) + + fun save(route: AudioRoute) { + prefs.edit() + .putString(INPUT_PRESET, route.inputPreset().name) + .putString(USAGE, route.usage().name) + .apply() + } + + private inline fun > enumOr(name: String?, default: E): E = + enumValues().firstOrNull { it.name == name } ?: default + + private companion object { + const val INPUT_PRESET = "inputPreset" + const val USAGE = "usage" + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/BookmarkShortcuts.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/BookmarkShortcuts.kt new file mode 100644 index 0000000..079a63c --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/BookmarkShortcuts.kt @@ -0,0 +1,80 @@ +package eu.lixko.ts3j.client.android + +import android.content.Context +import android.content.Intent +import android.content.pm.ShortcutInfo +import android.content.pm.ShortcutManager +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.Canvas +import android.graphics.Rect +import android.graphics.drawable.Icon +import eu.lixko.ts3j.client.config.Bookmark +import eu.lixko.ts3j.client.net.IconRepository + +/** + * Home-screen shortcuts that connect to a bookmark in one tap. A shortcut names its bookmark by + * [Bookmark.id], so editing the bookmark carries over and removing it disables the shortcut. + */ +internal class BookmarkShortcuts(private val context: Context, private val icons: IconTheme) { + + private val manager = context.getSystemService(ShortcutManager::class.java) + + val supported: Boolean get() = manager?.isRequestPinShortcutSupported == true + + /** Asks the launcher to pin a shortcut; it confirms with the user itself. */ + fun pin(bookmark: Bookmark) { + manager?.requestPinShortcut(info(bookmark), null) + } + + /** Pinned shortcuts take on their bookmarks' current names and icons; those of removed ones stop working. */ + fun sync(bookmarks: List) { + val manager = manager ?: return + val byId = bookmarks.associateBy { shortcutId(it.id) } + val pinned = manager.pinnedShortcuts + val gone = pinned.map { it.id }.filter { it !in byId } + if (gone.isNotEmpty()) manager.disableShortcuts(gone, "Bookmark removed") + val kept = pinned.mapNotNull { byId[it.id] } + if (kept.isNotEmpty()) { + manager.enableShortcuts(kept.map { shortcutId(it.id) }) + manager.updateShortcuts(kept.map(::info)) + } + } + + private fun info(bookmark: Bookmark): ShortcutInfo = + ShortcutInfo.Builder(context, shortcutId(bookmark.id)) + .setShortLabel(bookmark.displayName()) + .setLongLabel(listOfNotNull(bookmark.displayName(), bookmark.channel.ifBlank { null }).joinToString(" · ")) + .setIcon(icon(bookmark.iconId)) + .setIntent(Intent(context, MainActivity::class.java) + .setAction(ACTION_CONNECT) + .putExtra(EXTRA_BOOKMARK, bookmark.id)) + .build() + + /** The server's own icon as last seen there, else the pack's server icon, inside the adaptive icon's safe zone. */ + private fun icon(iconId: Long): Icon { + val art = IconRepository.cached(iconId)?.let { BitmapFactory.decodeByteArray(it, 0, it.size) } + ?: icons.render(listOf("SERVER_GREEN", "BOOKMARK_MANAGER"), ART_PX, 0x202020) + val canvas = Bitmap.createBitmap(ADAPTIVE_PX, ADAPTIVE_PX, Bitmap.Config.ARGB_8888) + Canvas(canvas).apply { + drawColor(BACKGROUND) + if (art != null) { + val inset = (ADAPTIVE_PX - ART_PX) / 2 + drawBitmap(art, null, Rect(inset, inset, inset + ART_PX, inset + ART_PX), null) + } + } + return Icon.createWithAdaptiveBitmap(canvas) + } + + companion object { + const val ACTION_CONNECT = "eu.lixko.ts3j.client.android.CONNECT_BOOKMARK" + const val EXTRA_BOOKMARK = "bookmark" + + /** 108 dp at xxxhdpi; the inner 72 dp always shows, the art sits well within. */ + private const val ADAPTIVE_PX = 432 + private const val ART_PX = 192 + private const val BACKGROUND = 0xFFE8EEF4.toInt() + + private fun shortcutId(bookmarkId: String) = "bookmark:$bookmarkId" + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/Chats.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/Chats.kt new file mode 100644 index 0000000..d28f679 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/Chats.kt @@ -0,0 +1,88 @@ +package eu.lixko.ts3j.client.android + +import androidx.compose.runtime.Immutable +import eu.lixko.ts3j.client.text.HtmlText +import eu.lixko.ts3j.client.text.TextQuery + +/** Which conversation a chat line belongs to. */ +sealed interface ChatKey { + data object Server : ChatKey + data object Channel : ChatKey + data class Private(val clientId: Int) : ChatKey +} + +/** One entry of a chat, as HTML in the form [eu.lixko.ts3j.client.text.ChatHtml] writes. */ +@Immutable +data class ChatLine(val id: Long, val html: String) { + /** The text to find in. */ + val plain: String by lazy { HtmlText.plain(html) } +} + +@Immutable +data class Conversation( + val key: ChatKey, + val title: String, + /** The peer's unique id in a private chat, once known. */ + val uniqueId: String = "", + val lines: List = emptyList(), + val unread: Boolean = false, +) + +/** Every conversation of the session: the server's, the channel's, then the private ones. */ +@Immutable +data class Chats( + val server: Conversation = Conversation(ChatKey.Server, "Server"), + val channel: Conversation = Conversation(ChatKey.Channel, "Channel"), + val private: List = emptyList(), +) { + val all: List get() = listOf(server, channel) + private + + val anyUnread: Boolean get() = all.any { it.unread } + + operator fun get(key: ChatKey): Conversation? = when (key) { + ChatKey.Server -> server + ChatKey.Channel -> channel + is ChatKey.Private -> private.firstOrNull { it.key == key } + } + + /** Applies [change] to a conversation, opening a private one titled [title] if needed. */ + fun update(key: ChatKey, title: String = "", change: (Conversation) -> Conversation): Chats = when (key) { + ChatKey.Server -> copy(server = change(server)) + ChatKey.Channel -> copy(channel = change(channel)) + is ChatKey.Private -> { + val existing = private.indexOfFirst { it.key == key } + if (existing < 0) { + copy(private = private + change(Conversation(key, title))) + } else { + copy(private = private.toMutableList().also { it[existing] = change(it[existing]) }) + } + } + } + + fun close(key: ChatKey.Private): Chats = copy(private = private.filter { it.key != key }) + + companion object { + /** As many lines as a log history loads; older ones leave the conversation. */ + const val MAX_LINES = 1000 + } +} + +fun Conversation.append(line: ChatLine, read: Boolean): Conversation = + copy(lines = (lines + line).takeLast(Chats.MAX_LINES), unread = unread || !read) + +/** The [nth] match of the find bar's query in the line [line]. */ +data class ChatMatch(val line: Long, val nth: Int) + +/** Every match of [query] in [lines], oldest first; past [limit], only the newest. */ +fun findIn(lines: List, query: TextQuery, limit: Int): List { + if (query.isEmpty) return emptyList() + val out = ArrayList() + for (line in lines) { + val m = query.matcher(line.plain) ?: return emptyList() + var n = 0 + while (m.find()) { + if (m.end() > m.start()) out += ChatMatch(line.id, n++) + } + } + return if (out.size > limit) out.subList(out.size - limit, out.size) else out +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ConnectionService.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ConnectionService.kt new file mode 100644 index 0000000..55c12a1 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ConnectionService.kt @@ -0,0 +1,238 @@ +package eu.lixko.ts3j.client.android + +import android.Manifest +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Intent +import android.content.pm.PackageManager +import android.content.pm.ServiceInfo +import android.graphics.Color +import android.graphics.drawable.Icon +import android.net.wifi.WifiManager +import android.os.PowerManager +import androidx.lifecycle.LifecycleService +import androidx.lifecycle.lifecycleScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay +import eu.lixko.ts3j.client.config.Settings +import eu.lixko.ts3j.client.net.ClientStatus +import eu.lixko.ts3j.client.session.SelfState +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.conflate +import kotlinx.coroutines.flow.drop +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.launch +import kotlin.math.roundToInt + +/** + * Keeps the process in the foreground while connected, so the connection and its audio + * survive the app leaving the screen, and offers the essentials in its notification. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class ConnectionService : LifecycleService() { + + private lateinit var sessions: SessionController + private lateinit var wifiLock: WifiManager.WifiLock + private lateinit var wifiBackgroundLock: WifiManager.WifiLock + private lateinit var wakeLock: PowerManager.WakeLock + private lateinit var overlay: PttOverlay + private var foregroundTypes = 0 + private var shown: ServerController? = null + + override fun onCreate() { + super.onCreate() + sessions = (application as Ts3Application).sessions + getSystemService(NotificationManager::class.java).createNotificationChannel( + NotificationChannel(CHANNEL, getString(R.string.connection_channel), NotificationManager.IMPORTANCE_LOW) + ) + // Voice goes out every 20 ms; Wi-Fi power saving and a sleeping CPU would stretch that. + // Low-latency mode only holds while we are in the foreground with the screen on, so the + // high-performance lock keeps power saving off the rest of the time. + val wifi = getSystemService(WifiManager::class.java) + wifiLock = wifi.createWifiLock(WifiManager.WIFI_MODE_FULL_LOW_LATENCY, "ts3j:voice") + .apply { setReferenceCounted(false); acquire() } + @Suppress("DEPRECATION") + wifiBackgroundLock = wifi.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "ts3j:voice-background") + .apply { setReferenceCounted(false); acquire() } + wakeLock = getSystemService(PowerManager::class.java) + .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ts3j:connection") + .apply { setReferenceCounted(false); acquire() } + + show(sessions.current.value?.state?.value ?: SessionState(), capturing = false) + lifecycleScope.launch { + // The server count shows in the notification too. + combine(shownServer(), sessions.micOwner, sessions.servers) { shown, owner, _ -> shown to (owner != null) } + .conflate() + .collect { (shown, capturing) -> + if (shown != null) { + this@ConnectionService.shown = shown.first + show(shown.second, capturing) + // Talking flips the icon often, and Android drops updates that come too fast. + delay(MIN_UPDATE_MS) + } + } + } + lifecycleScope.launch { + sessions.current.flatMapLatest { it?.state ?: flowOf(null) }.collectLatest { state -> + if (state == null) { + // A reconnect leaves the server briefly; only stop once it stays gone. + delay(STOP_DELAY_MS) + stopSelf() + } + } + } + lifecycleScope.launch { + sessions.icons.active.drop(1).collect { shown?.let { show(it.state.value, sessions.micOwner.value != null) } } + } + + overlay = PttOverlay(this, sessions.icons, sessions::setPushToTalk) + lifecycleScope.launch { + val owner = sessions.micOwner.flatMapLatest { server -> + server?.let { combine(it.state, it.tree) { state, tree -> state to tree } } ?: flowOf(null) + } + combine(owner, sessions.onScreen, sessions.pttOverlay) { held, onScreen, enabled -> + val (state, tree) = held ?: return@combine null + val wanted = enabled && !onScreen && state.connected && state.micActive && + state.inputMode == Settings.InputMode.PUSH_TO_TALK + val status = tree.client(state.selfClientId)?.status + when { + !wanted -> null + state.micMuted -> PttOverlay.Look.MUTED + status == ClientStatus.TALKING || status == ClientStatus.COMMANDER_TALKING -> PttOverlay.Look.TALKING + else -> PttOverlay.Look.IDLE + } + }.distinctUntilChanged().collect { look -> + if (look == null) overlay.hide() else overlay.show(look) + } + } + } + + /** + * The server the notification speaks for, as the desktop tray icon does: the one + * holding the microphone, or the visible one when nobody is capturing. + */ + private fun shownServer(): Flow?> = + combine(sessions.current, sessions.micOwner) { current, owner -> current to owner } + .flatMapLatest { (current, owner) -> + combine(current?.state ?: flowOf(null), owner?.state ?: flowOf(null)) { currentState, ownerState -> + when { + owner != null && ownerState?.connected == true -> owner to ownerState + current != null && currentState != null -> current to currentState + else -> null + } + } + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + super.onStartCommand(intent, flags, startId) + val server = shown ?: sessions.current.value ?: return START_NOT_STICKY + val state = server.state.value + when (intent?.action) { + ACTION_TOGGLE_MUTE -> server.setMicMuted(!state.micMuted) + ACTION_TOGGLE_DEAFEN -> server.setDeafened(!state.deafened) + ACTION_DISCONNECT -> server.disconnect() + } + return START_NOT_STICKY + } + + /** + * The user swiped the app away: they are done with it, connection included. Leaving + * properly spares the server a ghost that would hold our identity until it times out. + */ + override fun onTaskRemoved(rootIntent: Intent?) { + super.onTaskRemoved(rootIntent) + lifecycleScope.launch(Dispatchers.IO) { + sessions.leave() + stopSelf() + } + } + + override fun onDestroy() { + overlay.hide() + wifiLock.release() + wifiBackgroundLock.release() + wakeLock.release() + super.onDestroy() + } + + /** Posts the notification, re-declaring what the service uses when that changed. */ + private fun show(state: SessionState, capturing: Boolean) { + val types = ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK or + if (capturing && hasMicPermission()) ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE else 0 + val notification = notification(state) + if (types != foregroundTypes) { + startForeground(NOTIFICATION_ID, notification, types) + foregroundTypes = types + } else { + getSystemService(NotificationManager::class.java).notify(NOTIFICATION_ID, notification) + } + } + + private fun hasMicPermission() = + checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED + + private fun notification(state: SessionState): Notification { + val open = PendingIntent.getActivity( + this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE + ) + val others = sessions.servers.value.size - 1 + return Notification.Builder(this, CHANNEL) + .setSmallIcon(statusIcon(state.self)) + .setLargeIcon(largeIcon(state.self)) + .setContentTitle(if (others > 0) "${state.title} +$others" else state.title) + .setContentText(state.status) + .setContentIntent(open) + .setOngoing(true) + .addAction(action(ACTION_TOGGLE_MUTE, if (state.micMuted) "Unmute" else "Mute")) + .addAction(action(ACTION_TOGGLE_DEAFEN, if (state.deafened) "Undeafen" else "Deafen")) + .addAction(action(ACTION_DISCONNECT, "Disconnect")) + .build() + } + + /** + * The status bar shows only the shape of an icon, which pack art loses, so it is + * drawn from the Material pack whatever pack is chosen. + */ + private fun statusIcon(self: SelfState): Icon { + val key = self.iconKey() ?: return Icon.createWithResource(this, android.R.drawable.ic_btn_speak_now) + val size = (STATUS_ICON_DP * resources.displayMetrics.density).roundToInt() + val bitmap = sessions.icons.renderMaterial(key, size, Color.WHITE) + ?: return Icon.createWithResource(this, android.R.drawable.ic_btn_speak_now) + return Icon.createWithBitmap(bitmap) + } + + /** The expanded notification has room for the chosen pack's own art, as the tree draws it. */ + private fun largeIcon(self: SelfState): Icon? { + val key = self.iconKey() ?: return null + val size = (LARGE_ICON_DP * resources.displayMetrics.density).roundToInt() + return sessions.icons.render(listOf(key), size, getColor(android.R.color.system_neutral1_500)) + ?.let(Icon::createWithBitmap) + } + + private fun action(action: String, label: String): Notification.Action { + val intent = PendingIntent.getService( + this, action.hashCode(), Intent(this, ConnectionService::class.java).setAction(action), + PendingIntent.FLAG_IMMUTABLE + ) + return Notification.Action.Builder(null, label, intent).build() + } + + private companion object { + const val CHANNEL = "connection" + const val NOTIFICATION_ID = 1 + const val STOP_DELAY_MS = 3_000L + const val MIN_UPDATE_MS = 250L + const val STATUS_ICON_DP = 24 + const val LARGE_ICON_DP = 48 + const val ACTION_TOGGLE_MUTE = "eu.lixko.ts3j.client.android.TOGGLE_MUTE" + const val ACTION_TOGGLE_DEAFEN = "eu.lixko.ts3j.client.android.TOGGLE_DEAFEN" + const val ACTION_DISCONNECT = "eu.lixko.ts3j.client.android.DISCONNECT" + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/FileTransfers.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/FileTransfers.kt new file mode 100644 index 0000000..1d32ac0 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/FileTransfers.kt @@ -0,0 +1,132 @@ +package eu.lixko.ts3j.client.android + +import android.content.Context +import android.net.Uri +import android.provider.OpenableColumns +import eu.lixko.ts3j.client.net.TeamspeakConnection +import eu.lixko.ts3j.client.net.filetransfer.FileTransfer +import eu.lixko.ts3j.client.net.filetransfer.RemoteFile +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.withContext +import java.io.File +import java.io.IOException +import java.util.concurrent.atomic.AtomicLong + +/** One upload or download as the file browser shows it. */ +data class TransferRow( + val id: Long, + val name: String, + val upload: Boolean, + val channelId: Int, + /** The directory an upload goes into, to list again once it is there. */ + val directory: String, + val transferred: Long, + val total: Long, + val state: FileTransfer.State, + val error: String?, +) { + val done: Boolean get() = state != FileTransfer.State.PENDING && state != FileTransfer.State.ACTIVE + val progress: Float get() = if (total > 0) (transferred.toFloat() / total).coerceIn(0f, 1f) else 0f +} + +/** + * The channel file transfers of one server. Transfers go through files of our own in the cache, + * as the core reads and writes plain files: a download is copied where the user picked once + * complete, an upload is copied out of the picked document first. They outlive the browser page. + */ +class FileTransfers internal constructor(private val context: Context, private val conn: () -> TeamspeakConnection) { + + private val ids = AtomicLong() + private val handles = HashMap() + + private val _rows = MutableStateFlow(emptyList()) + val rows: StateFlow> = _rows + + /** Downloads [file] into the document at [target]. */ + fun download(channelId: Int, password: String, file: RemoteFile, target: Uri) { + val temp = File.createTempFile("download", null, context.cacheDir) + val row = add(file.name, upload = false, channelId, file.parentPath, file.size) + start(row, temp, onComplete = { + context.contentResolver.openOutputStream(target)?.use { out -> temp.inputStream().use { it.copyTo(out) } } + ?: throw IOException("Could not write the file") + }) { listener -> conn().downloadFile(channelId, password, file.fullPath, temp, listener) } + } + + /** Uploads the document at [source] into [directory] (ending in "/"), replacing a file of the same name. */ + suspend fun upload(channelId: Int, password: String, directory: String, source: Uri) { + val (name, temp) = withContext(Dispatchers.IO) { copyIn(source) } + val row = add(name, upload = true, channelId, directory, temp.length()) + start(row, temp, onComplete = {}) { listener -> + conn().uploadFile(channelId, password, directory + name, temp, true, listener) + } + } + + fun cancel(id: Long) { + synchronized(handles) { handles[id] }?.cancel() + } + + fun clearFinished() = _rows.update { rows -> rows.filterNot { it.done } } + + private fun add(name: String, upload: Boolean, channelId: Int, directory: String, total: Long): TransferRow { + val row = TransferRow(ids.incrementAndGet(), name, upload, channelId, directory, 0, total, + FileTransfer.State.PENDING, null) + _rows.update { it + row } + return row + } + + /** Runs a transfer through [temp], which goes once it is done with; [onComplete] finishes a successful one. */ + private fun start(row: TransferRow, temp: File, onComplete: () -> Unit, + begin: (FileTransfer.Listener) -> FileTransfer) { + var lastUpdate = 0L + val listener = FileTransfer.Listener { t -> + val now = System.nanoTime() + // Progress comes per buffer; the list need not redraw that often. + if (!t.isDone && now - lastUpdate < UPDATE_NANOS) return@Listener + lastUpdate = now + var error = t.errorMessage + if (t.state == FileTransfer.State.COMPLETED) { + error = runCatching(onComplete).exceptionOrNull()?.let { it.message ?: "Could not save the file" } + } + if (t.isDone) { + temp.delete() + synchronized(handles) { handles.remove(row.id) } + } + val state = if (error != null) FileTransfer.State.FAILED else t.state + update(row.id) { it.copy(transferred = t.transferredBytes, total = maxOf(t.totalBytes, 0), state = state, error = error) } + } + try { + val handle = begin(listener) + synchronized(handles) { if (!handle.isDone) handles[row.id] = handle } + } catch (e: RuntimeException) { + temp.delete() + update(row.id) { it.copy(state = FileTransfer.State.FAILED, error = e.message ?: "Not connected") } + } + } + + private fun update(id: Long, change: (TransferRow) -> TransferRow) = + _rows.update { rows -> rows.map { if (it.id == id) change(it) else it } } + + private fun copyIn(uri: Uri): Pair { + val resolver = context.contentResolver + val name = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c -> + if (c.moveToFirst()) c.getString(0) else null + }?.takeIf { it.isNotBlank() } ?: uri.lastPathSegment ?: "file" + val temp = File.createTempFile("upload", null, context.cacheDir) + try { + resolver.openInputStream(uri)?.use { input -> temp.outputStream().use { input.copyTo(it) } } + ?: throw IOException("Could not read the file") + } catch (e: IOException) { + temp.delete() + throw e + } + // A server path takes no slashes in a file name. + return name.replace('/', '_') to temp + } + + private companion object { + const val UPDATE_NANOS = 200_000_000L + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/IconTheme.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/IconTheme.kt new file mode 100644 index 0000000..75fa46a --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/IconTheme.kt @@ -0,0 +1,143 @@ +package eu.lixko.ts3j.client.android + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.RectF +import android.net.Uri +import android.provider.OpenableColumns +import android.util.LruCache +import com.caverock.androidsvg.RenderOptions +import com.caverock.androidsvg.SVG +import eu.lixko.ts3j.client.config.AppDirs +import eu.lixko.ts3j.client.config.Settings +import eu.lixko.ts3j.client.gfx.IconPack +import eu.lixko.ts3j.client.gfx.IconPacks +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import java.io.File + +/** + * The icon packs the app draws with: the Material pack it ships, and TeamSpeak packs + * imported into its `gfx` folder, which are the very zips a TeamSpeak 3 install keeps in + * its own. Whatever the chosen pack lacks comes from the Material one. + */ +class IconTheme(private val context: Context, private val settings: Settings) { + + private val folder = File(AppDirs.profile(), "gfx") + private val material: IconPack = IconPacks.material() + @Volatile + private var lookupOrder = listOf(material) + private val cache = LruCache(256) + + private val _packs = MutableStateFlow(emptyList()) + val packs: StateFlow> = _packs + + private val _active = MutableStateFlow(material) + val active: StateFlow = _active + + init { + reload() + } + + fun select(pack: IconPack) { + settings.iconPack = pack.id() + settings.save() + reload() + } + + /** + * Copies a pack's zip into the app and switches to it. + * + * @return the pack, or `null` when the file is no icon pack + */ + fun import(uri: Uri): IconPack? { + folder.mkdirs() + val target = File(folder, displayName(uri).substringAfterLast('/').let { + if (it.endsWith(".zip", ignoreCase = true)) it else "$it.zip" + }) + val staged = File(folder, target.name + ".part") + context.contentResolver.openInputStream(uri)?.use { input -> + staged.outputStream().use { input.copyTo(it) } + } ?: return null + target.delete() + staged.renameTo(target) + val pack = IconPack.load(target) + if (pack == null) { + target.delete() + return null + } + select(pack) + return _active.value + } + + /** + * Draws the first of [keys] the packs have. + * + * @param rgb the colour for art that paints in the text colour + */ + fun render(keys: List, size: Int, rgb: Int): Bitmap? = render(lookupOrder, keys, size, rgb) + + /** Draws from the Material pack whatever pack is chosen, for chrome that must stay legible on its own colours. */ + fun renderMaterial(key: String, size: Int, rgb: Int): Bitmap? = render(listOf(material), listOf(key), size, rgb) + + private fun render(order: List, keys: List, size: Int, rgb: Int): Bitmap? { + val cacheKey = "${order.first().id()}/${keys.joinToString(",")}@$size#$rgb" + cache.get(cacheKey)?.let { return it } + for (key in keys) { + for (pack in order) { + val data = pack.icon(key, size) ?: continue + val bitmap = (if (pack.isVector(key, size)) rasterize(IconPack.withCurrentColor(data, rgb), size) + else decode(data, size)) ?: continue + cache.put(cacheKey, bitmap) + return bitmap + } + } + return null + } + + private fun reload() { + val packs = IconPacks.findAll(folder, null) + val active = IconPacks.select(packs, settings.iconPack) ?: material + lookupOrder = IconPacks.lookupOrder(active, packs, material) + cache.evictAll() + _packs.value = packs + _active.value = active + } + + private fun displayName(uri: Uri): String = + context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { + if (it.moveToFirst()) it.getString(0) else null + } ?: uri.lastPathSegment ?: "iconpack.zip" + + private fun rasterize(svg: ByteArray, size: Int): Bitmap? = try { + val document = SVG.getFromString(String(svg, Charsets.UTF_8)) + if (document.documentViewBox == null && document.documentWidth > 0 && document.documentHeight > 0) { + document.setDocumentViewBox(0f, 0f, document.documentWidth, document.documentHeight) + } + // Otherwise the art keeps the size it was authored at inside the viewport. + document.setDocumentWidth("100%") + document.setDocumentHeight("100%") + Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).also { + document.renderToCanvas(Canvas(it), RenderOptions().viewPort(0f, 0f, size.toFloat(), size.toFloat())) + } + } catch (e: Exception) { + null + } + + /** Scales a bitmap icon into the square, keeping the aspect ratio of art that is not. */ + private fun decode(data: ByteArray, size: Int): Bitmap? { + val source = BitmapFactory.decodeByteArray(data, 0, data.size) ?: return null + if (source.width == size && source.height == size) return source + val factor = minOf(size.toFloat() / source.width, size.toFloat() / source.height) + val w = source.width * factor + val h = source.height * factor + return Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).also { + val left = (size - w) / 2 + val top = (size - h) / 2 + Canvas(it).drawBitmap(source, null, RectF(left, top, left + w, top + h), Paint(Paint.FILTER_BITMAP_FLAG)) + } + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/IdentityManager.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/IdentityManager.kt new file mode 100644 index 0000000..bb04ef4 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/IdentityManager.kt @@ -0,0 +1,170 @@ +package eu.lixko.ts3j.client.android + +import android.content.Context +import android.net.Uri +import eu.lixko.ts3j.client.config.Bookmarks +import eu.lixko.ts3j.client.config.IdentityEntry +import eu.lixko.ts3j.client.config.IdentityStore +import eu.lixko.ts3j.client.config.Settings +import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter +import eu.lixko.ts3j.client.teamspeak.TeamSpeakSettingsDb +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.IOException + +/** What the identity manager shows of one identity. */ +data class IdentityInfo( + val id: String, + val name: String, + val uniqueId: String, + val securityLevel: Int, + val isDefault: Boolean, + val nickname: String, + val phoneticNickname: String, +) + +/** A search for a better key offset under way. */ +data class Improvement(val id: String, val target: Int, val reached: Int) + +/** + * The identities, as TeamSpeak's Tools → Identities manages them: create, import, export, + * rename, remove, pick the default and raise the security level. Raising the level runs + * on until it is reached or stopped, whichever page is on screen. + */ +class IdentityManager( + private val context: Context, + private val store: IdentityStore, + private val settings: Settings, + private val bookmarks: Bookmarks, + private val onBookmarksChanged: () -> Unit, +) { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + private val _all = MutableStateFlow(snapshot()) + val all: StateFlow> = _all + + private val _improving = MutableStateFlow(null) + val improving: StateFlow = _improving + private var improvement: Job? = null + + /** Picks up identities added elsewhere, such as by an import or a first connect. */ + fun refresh() { + _all.value = snapshot() + } + + private fun snapshot(): List = store.all().map { + IdentityInfo(it.id, it.name, it.uniqueId, it.securityLevel, it.id == settings.defaultIdentityId, + it.nickname, it.phoneticNickname) + } + + /** Generates an identity at TeamSpeak's default security level; the first one becomes the default. */ + suspend fun generate(name: String): IdentityInfo = added { + store.generate(name, IdentityStore.DEFAULT_SECURITY_LEVEL) + } + + /** Imports a TeamSpeak identity file, under the name it carries. */ + suspend fun importFile(uri: Uri): IdentityInfo = added { + context.contentResolver.openInputStream(uri)?.use { store.importStream(it, null) } + ?: throw IOException("Cannot open the file") + } + + /** Imports the identities of a TeamSpeak 3 `settings.db`. */ + suspend fun importFromTeamSpeak(uri: Uri): TeamSpeakImporter.Result = withContext(Dispatchers.IO) { + withLocalCopy(context, uri) { TeamSpeakImporter(store, bookmarks, settings).importIdentities(it) } + }.also { + adoptDefault(null) + refresh() + } + + private suspend fun added(create: () -> IdentityEntry): IdentityInfo { + val entry = withContext(Dispatchers.IO) { create() } + adoptDefault(entry) + refresh() + return _all.value.first { it.id == entry.id } + } + + /** Makes [entry], or else the first identity, the default while there is none. */ + private fun adoptDefault(entry: IdentityEntry?) { + if (store.byId(settings.defaultIdentityId) != null) return + val fallback = entry ?: store.all().firstOrNull() ?: return + settings.defaultIdentityId = fallback.id + settings.save() + } + + /** Writes the identity out in TeamSpeak's format, for the official client or another device. */ + suspend fun export(id: String, uri: Uri) = withContext(Dispatchers.IO) { + val entry = store.byId(id) ?: return@withContext + val out = context.contentResolver.openOutputStream(uri, "wt") ?: throw IOException("Cannot write the file") + store.exportTo(entry, out) + } + + fun rename(id: String, name: String) { + val entry = store.byId(id) ?: return + scope.launch(Dispatchers.IO) { + store.rename(entry, name) + refresh() + } + } + + fun setNicknames(id: String, nickname: String, phoneticNickname: String) { + val entry = store.byId(id) ?: return + scope.launch(Dispatchers.IO) { + store.setNicknames(entry, nickname, phoneticNickname) + refresh() + } + } + + /** The nickname of the identity a connect with [id] uses; empty when it has none. */ + fun nicknameOf(id: String): String = + (store.byId(id) ?: store.byId(settings.defaultIdentityId))?.nickname.orEmpty() + + fun setDefault(id: String) { + settings.defaultIdentityId = id + settings.save() + refresh() + } + + /** Deletes the identity; bookmarks that connected with it fall back to the default. */ + fun remove(id: String) { + val entry = store.byId(id) ?: return + scope.launch(Dispatchers.IO) { + // Else the search would write the file back once it ends. + if (_improving.value?.id == id) improvement?.cancelAndJoin() + store.remove(entry, settings, bookmarks) + onBookmarksChanged() + refresh() + } + } + + /** Searches for a key offset reaching [target], keeping the best found when stopped. */ + fun improve(id: String, target: Int) { + if (improvement?.isActive == true) return + val entry = store.byId(id) ?: return + _improving.value = Improvement(id, target, entry.securityLevel) + improvement = scope.launch { + try { + store.improveSecurity(entry, target) { reached, _ -> + _improving.value = Improvement(id, target, reached) + isActive + } + } catch (e: IOException) { + // The level reached stays in memory for this run. + } finally { + _improving.value = null + refresh() + } + } + } + + fun stopImproving() { + improvement?.cancel() + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/LevelMonitor.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/LevelMonitor.kt new file mode 100644 index 0000000..026e0d3 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/LevelMonitor.kt @@ -0,0 +1,95 @@ +package eu.lixko.ts3j.client.android + +import eu.lixko.ts3j.client.audio.AudioBackend +import eu.lixko.ts3j.client.audio.InputLevel +import eu.lixko.ts3j.client.audio.VoiceInput +import eu.lixko.ts3j.client.config.Settings +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow + +/** The microphone's level on [InputLevel]'s scale, and whether that would be sent. */ +data class MicLevel( + val db: Double = InputLevel.SILENCE_DB, + val transmitting: Boolean = false, + /** Whether a microphone is being listened to at all. */ + val live: Boolean = false, +) + +/** + * The level meter behind the voice-activation settings. While connected it listens to the + * connection's own microphone, so it shows exactly what gets sent; otherwise it runs a test + * microphone of its own for as long as someone watches. + */ +class LevelMonitor(private val settings: Settings, private val audio: AudioBackend) { + + private val _level = MutableStateFlow(MicLevel()) + val level: StateFlow = _level + + /** The connection's microphone, when that is the one listened to. */ + private var borrowed: VoiceInput? = null + private var test: VoiceInput? = null + + /** + * Starts or stops listening. + * + * @param source the connection's microphone while it captures, else null + * @param busy whether a connection is under way, which will bring its own microphone + */ + @Synchronized + fun update(watching: Boolean, source: VoiceInput?, busy: Boolean, mayCapture: Boolean) { + when { + !watching -> release() + source != null -> if (borrowed !== source) { + release() + source.setLevelListener(::onLevel) + borrowed = source + } + busy || !mayCapture -> release() + test == null -> startTest() + } + } + + /** The own microphone's transmit state, which the connection reports. */ + fun talking(transmitting: Boolean) { + if (borrowed != null) _level.value = _level.value.copy(transmitting = transmitting) + } + + /** Puts changed voice settings into effect on the test microphone. */ + @Synchronized + fun apply() { + test?.let { + it.apply(settings) + it.setMode(testMode()) + } + } + + private fun startTest() { + release() + val input = audio.createInput(settings) + input.setMode(testMode()) + input.setLevelListener(::onLevel) + input.setTalkListener { _level.value = _level.value.copy(transmitting = it) } + try { + input.start() + } catch (e: RuntimeException) { + return // no microphone to be had; the meter stays idle + } + test = input + } + + private fun release() { + borrowed?.setLevelListener(null) + borrowed = null + test?.stop() + test = null + _level.value = MicLevel() + } + + private fun onLevel(db: Double) { + _level.value = _level.value.copy(db = db, live = true) + } + + /** Push-to-talk would never open without the button, and the test is there to tune the gate. */ + private fun testMode() = + if (settings.inputMode == Settings.InputMode.PUSH_TO_TALK) Settings.InputMode.VOICE_ACTIVATION else settings.inputMode +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/LocalCopy.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/LocalCopy.kt new file mode 100644 index 0000000..1bd8686 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/LocalCopy.kt @@ -0,0 +1,21 @@ +package eu.lixko.ts3j.client.android + +import android.content.Context +import android.net.Uri +import java.io.File +import java.io.IOException + +/** + * Hands [read] a temporary copy of the document at [uri], for readers that need a file they + * can seek in, which a content URI is not. + */ +internal fun withLocalCopy(context: Context, uri: Uri, read: (File) -> T): T { + val copy = File.createTempFile("import", null, context.cacheDir) + try { + val input = context.contentResolver.openInputStream(uri) ?: throw IOException("Cannot open the file") + input.use { copy.outputStream().use { out -> it.copyTo(out) } } + return read(copy) + } finally { + copy.delete() + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/MainActivity.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/MainActivity.kt new file mode 100644 index 0000000..76fb333 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/MainActivity.kt @@ -0,0 +1,56 @@ +package eu.lixko.ts3j.client.android + +import android.content.Intent +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import eu.lixko.ts3j.client.android.ui.App +import eu.lixko.ts3j.client.android.ui.Ts3Theme +import eu.lixko.ts3j.client.session.ServerLink + +class MainActivity : ComponentActivity() { + + private val sessions get() = (application as Ts3Application).sessions + + override fun onCreate(savedInstanceState: Bundle?) { + enableEdgeToEdge() + super.onCreate(savedInstanceState) + if (savedInstanceState == null) sessions.connectStartupBookmarks(handle(intent)) + setContent { + Ts3Theme { App(sessions) } + } + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + handle(intent) + } + + override fun onStart() { + super.onStart() + sessions.foreground = true + } + + override fun onStop() { + sessions.foreground = false + super.onStop() + } + + /** A notification opens its conversation; a `ts3server://` link or a bookmark shortcut connects, returning where. */ + private fun handle(intent: Intent): ServerLink? = when (intent.action) { + Intent.ACTION_VIEW -> ServerLink.parse(intent.dataString)?.also { sessions.open(it) } + BookmarkShortcuts.ACTION_CONNECT -> intent.getStringExtra(BookmarkShortcuts.EXTRA_BOOKMARK) + ?.let(sessions::openBookmark) + else -> { + openRequestedChat(intent) + null + } + } + + private fun openRequestedChat(intent: Intent) { + val serverId = intent.getIntExtra(MessageNotifier.EXTRA_SERVER, -1) + val clientId = intent.getIntExtra(MessageNotifier.EXTRA_CHAT, -1) + if (serverId >= 0 && clientId >= 0) sessions.requestChat(serverId, clientId) + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/MessageNotifier.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/MessageNotifier.kt new file mode 100644 index 0000000..e19fd88 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/MessageNotifier.kt @@ -0,0 +1,141 @@ +package eu.lixko.ts3j.client.android + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Person +import android.app.RemoteInput +import android.content.Context +import android.content.Intent + +/** + * Tells the user about pokes and private messages while the app is out of sight. The + * notifications themselves are silent: the sound pack already plays TeamSpeak's own sound + * for either, as it does in the app. + */ +class MessageNotifier(private val context: Context) { + + private val manager = context.getSystemService(NotificationManager::class.java) + private val me = Person.Builder().setName("You").build() + + /** What each private conversation's notification shows, by [id] of server and peer. */ + private val conversations = HashMap() + + private class Conversation(val peer: Person, val messages: MutableList) + + init { + manager.createNotificationChannels(listOf( + channel(MESSAGES, R.string.messages_channel), + channel(POKES, R.string.pokes_channel), + )) + } + + private fun channel(id: String, name: Int) = + NotificationChannel(id, context.getString(name), NotificationManager.IMPORTANCE_HIGH).apply { + setSound(null, null) + enableVibration(true) + } + + fun poke(from: String, message: String) { + val notification = Notification.Builder(context, POKES) + .setSmallIcon(android.R.drawable.stat_notify_chat) + .setContentTitle("$from poked you") + .setContentText(message.ifBlank { null }) + .setCategory(Notification.CATEGORY_MESSAGE) + .setContentIntent(open(null, null)) + .setAutoCancel(true) + .build() + manager.notify(POKE_TAG, from.hashCode(), notification) + } + + fun clearPokes() { + for (active in manager.activeNotifications) { + if (active.tag == POKE_TAG) manager.cancel(POKE_TAG, active.id) + } + } + + /** A message the peer sent, which starts the conversation's notification if it had none. */ + @Synchronized + fun received(serverId: Int, clientId: Int, from: String, text: String) { + val id = id(serverId, clientId) + val conversation = conversations[id]?.takeIf { it.peer.name == from } + ?: Conversation(Person.Builder().setName(from).setKey("client:$serverId:$clientId").build(), ArrayList()) + conversations[id] = conversation + add(serverId, clientId, conversation, text, conversation.peer, alert = true) + } + + /** Our own reply, shown in a conversation already notified of; answers the reply action too. */ + @Synchronized + fun sent(serverId: Int, clientId: Int, text: String) { + val conversation = conversations[id(serverId, clientId)] ?: return + add(serverId, clientId, conversation, text, me, alert = false) + } + + private fun add(serverId: Int, clientId: Int, conversation: Conversation, text: String, sender: Person, alert: Boolean) { + conversation.messages += Notification.MessagingStyle.Message(text, System.currentTimeMillis(), sender) + if (conversation.messages.size > MAX_MESSAGES) conversation.messages.removeAt(0) + val style = Notification.MessagingStyle(me) + conversation.messages.forEach(style::addMessage) + val notification = Notification.Builder(context, MESSAGES) + .setSmallIcon(android.R.drawable.stat_notify_chat) + .setStyle(style) + .setCategory(Notification.CATEGORY_MESSAGE) + .setContentIntent(open(serverId, clientId)) + .setOnlyAlertOnce(!alert) + .setAutoCancel(true) + .addAction(replyAction(serverId, clientId)) + .build() + manager.notify(MESSAGE_TAG, id(serverId, clientId), notification) + } + + /** The conversation came on screen, or ended with the connection. */ + @Synchronized + fun clear(serverId: Int, clientId: Int) { + val id = id(serverId, clientId) + conversations.remove(id) + manager.cancel(MESSAGE_TAG, id) + } + + /** The server's conversations, as its connection ended. */ + @Synchronized + fun clearServer(serverId: Int) { + conversations.keys.filter { it ushr 16 == serverId }.forEach { clear(serverId, it and 0xFFFF) } + } + + private fun open(serverId: Int?, clientId: Int?): PendingIntent { + val intent = Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) + if (serverId != null && clientId != null) { + intent.putExtra(EXTRA_SERVER, serverId).putExtra(EXTRA_CHAT, clientId) + } + return PendingIntent.getActivity(context, if (serverId != null && clientId != null) id(serverId, clientId) else -1, + intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) + } + + private fun replyAction(serverId: Int, clientId: Int): Notification.Action { + val intent = Intent(context, ReplyReceiver::class.java) + .putExtra(EXTRA_SERVER, serverId).putExtra(EXTRA_CHAT, clientId) + // Mutable: the system fills the typed reply into it. + val pending = PendingIntent.getBroadcast(context, id(serverId, clientId), intent, + PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) + return Notification.Action.Builder(null, "Reply", pending) + .addRemoteInput(RemoteInput.Builder(KEY_REPLY).setLabel("Message").build()) + .setSemanticAction(Notification.Action.SEMANTIC_ACTION_REPLY) + .build() + } + + /** Client ids are 16 bits, and only unique on their server. */ + private fun id(serverId: Int, clientId: Int) = serverId shl 16 or clientId + + companion object { + /** The server and the client id of the private chat a notification opens or replies to. */ + const val EXTRA_SERVER = "eu.lixko.ts3j.client.android.SERVER" + const val EXTRA_CHAT = "eu.lixko.ts3j.client.android.CHAT" + const val KEY_REPLY = "reply" + private const val MESSAGES = "messages" + private const val POKES = "pokes" + private const val MESSAGE_TAG = "message" + private const val POKE_TAG = "poke" + private const val MAX_MESSAGES = 25 + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/NetworkFollower.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/NetworkFollower.kt new file mode 100644 index 0000000..1790214 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/NetworkFollower.kt @@ -0,0 +1,220 @@ +package eu.lixko.ts3j.client.android + +import android.content.Context +import android.net.ConnectivityManager +import android.net.Network +import eu.lixko.ts3j.client.session.ServerSession +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull +import java.util.concurrent.CopyOnWriteArrayList + +/** + * Keeps the connections on the network Android routes over. + * + * A TS3 server knows its clients by address, so once the phone moves from Wi-Fi to mobile + * data (or back) an old connection is dead weight: it can only time out. This notices the + * move, says goodbye over the old network while that still works, and connects again over + * the new one, back into the channel we were in. A server that still holds our old + * connection may refuse the new one for a while as a clone, so a failed attempt is retried. + * + * The process's sockets are bound to the network a connection was made over. Otherwise the + * old connection would silently follow the new default network, and its goodbye would come + * from an address the server does not know. A socket keeps the network it was made on, so + * each connection remembers its own. + */ +class NetworkFollower(context: Context) { + private val connectivity = context.getSystemService(ConnectivityManager::class.java) + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + private val follows = CopyOnWriteArrayList() + + /** The system's default network; null while there is none. */ + @Volatile + private var network: Network? = null + + init { + connectivity.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() { + override fun onAvailable(available: Network) { + network = available + follows.forEach(Follow::reconsider) + } + + override fun onLost(lost: Network) { + if (network == lost) network = null + follows.forEach(Follow::reconsider) + } + }) + } + + /** Follows [session] until [Follow.forget]. */ + fun follow(session: ServerSession, onChange: () -> Unit, system: (String) -> Unit): Follow = + Follow(session, onChange, system).also(follows::add) + + /** Binds new sockets to [to], or lets them go by the default network once no connection wants one. */ + private fun bind(to: Network?) { + connectivity.bindProcessToNetwork(to ?: follows.firstNotNullOfOrNull { f -> f.bound.takeIf { f.wanted } }) + } + + inner class Follow internal constructor( + private val session: ServerSession, + private val onChange: () -> Unit, + private val system: (String) -> Unit, + ) { + /** The network the connection was made over. */ + @Volatile + internal var bound: Network? = null + + /** The user wants to be on the server: from their connect until they, or the server, end it. */ + @Volatile + internal var wanted = false + + private var settle: Job? = null + @Volatile + private var recovery: Job? = null + @Volatile + private var attempt: CompletableDeferred? = null + + /** What to show in place of the session's status while getting back on the server. */ + @Volatile + var status: String? = null + private set + + val isRecovering: Boolean get() = recovery?.isActive == true + + /** Before a connect the user asked for, which goes over the network there is now. */ + fun connecting() { + recovery?.cancel() + wanted = true + bindHere(connectivity.activeNetwork) + } + + /** The user leaves the server. */ + fun leaving() { + wanted = false + recovery?.cancel() + unbind() + } + + /** The session is thrown away. */ + fun forget() { + leaving() + follows.remove(this) + } + + fun onConnected() { + attempt?.complete(true) + } + + fun onDisconnected() { + val pending = attempt + when { + pending != null -> pending.complete(false) + isRecovering -> {} + // A socket on a network that went away fails at once, before we hear of the change. + wanted && networkGone() -> synchronized(this) { + if (!isRecovering) recovery = recover() + } + // The server let us go (a kick, a shutdown, a failed first connect): leave it at that. + else -> { + wanted = false + unbind() + } + } + } + + /** Waits for the network to settle: a handover often shows several changes in a row. */ + internal fun reconsider() { + synchronized(this) { + settle?.cancel() + settle = scope.launch { + delay(SETTLE_MS) + synchronized(this@Follow) { + if (wanted && bound != network && !isRecovering) recovery = recover() + } + } + } + } + + private fun recover() = scope.launch { + try { + val back = withTimeoutOrNull(GIVE_UP_MS) { + system(if (connectivity.activeNetwork == null) "Network lost." else "Network changed, reconnecting…") + if (session.isBusy) session.connection().disconnectBlocking("Network changed") + var retry = RETRY_MS + while (true) { + val current = awaitNetwork() + bindHere(current) + show("Reconnecting…") + val done = CompletableDeferred() + attempt = done + session.reconnect() + val connected = done.await() + attempt = null + if (connected) break + if (session.connection().connectErrorId == ERROR_BANNED) break + show("Reconnecting, retrying soon…") + delay(retry) + retry = (retry * 2).coerceAtMost(MAX_RETRY_MS) + } + } + if (session.connection().connectErrorId == ERROR_BANNED) { + wanted = false + unbind() + } else if (back == null) { + system("Could not get back on the server.") + wanted = false + unbind() + } + } finally { + attempt = null + status = null + onChange() + // The network may have moved again while we were busy. + reconsider() + } + } + + private fun networkGone(): Boolean { + val on = bound ?: return false + return connectivity.getNetworkCapabilities(on) == null || connectivity.activeNetwork != on + } + + private suspend fun awaitNetwork(): Network { + while (true) { + connectivity.activeNetwork?.let { return it } + show("Waiting for network…") + delay(POLL_MS) + } + } + + private fun show(text: String) { + status = text + onChange() + } + + private fun bindHere(to: Network?) { + bound = to + bind(to) + } + + private fun unbind() { + bound = null + bind(null) + } + } + + private companion object { + const val SETTLE_MS = 1_500L + /** The server's refusal for a banned client; asking again will not help. */ + const val ERROR_BANNED = 3329 + const val RETRY_MS = 5_000L + const val MAX_RETRY_MS = 30_000L + const val POLL_MS = 500L + const val GIVE_UP_MS = 5 * 60_000L + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/Picture.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/Picture.kt new file mode 100644 index 0000000..9cae016 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/Picture.kt @@ -0,0 +1,42 @@ +package eu.lixko.ts3j.client.android + +import android.graphics.ImageDecoder +import android.graphics.drawable.AnimatedImageDrawable +import android.graphics.drawable.BitmapDrawable +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.asImageBitmap +import java.nio.ByteBuffer + +/** An avatar or a picture from a description: still, or moving like an animated GIF. */ +sealed interface Picture { + val width: Int + val height: Int + + data class Still(val bitmap: ImageBitmap) : Picture { + override val width get() = bitmap.width + override val height get() = bitmap.height + } + + /** Shared by whatever shows it: one animation, drawn wherever it is on screen. */ + data class Moving(val drawable: AnimatedImageDrawable) : Picture { + override val width get() = drawable.intrinsicWidth + override val height get() = drawable.intrinsicHeight + } +} + +/** Decodes any image Android knows, no larger than [maxPx] on its longer side; null if it is none. */ +internal fun decodePicture(data: ByteArray, maxPx: Int): Picture? = try { + val drawable = ImageDecoder.decodeDrawable(ImageDecoder.createSource(ByteBuffer.wrap(data))) { decoder, info, _ -> + val largest = maxOf(info.size.width, info.size.height) + if (largest > maxPx) { + decoder.setTargetSize(info.size.width * maxPx / largest, info.size.height * maxPx / largest) + } + } + when (drawable) { + is AnimatedImageDrawable -> Picture.Moving(drawable) + is BitmapDrawable -> Picture.Still(drawable.bitmap.asImageBitmap()) + else -> null + } +} catch (e: Exception) { + null +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/PttOverlay.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/PttOverlay.kt new file mode 100644 index 0000000..922d80e --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/PttOverlay.kt @@ -0,0 +1,176 @@ +package eu.lixko.ts3j.client.android + +import android.annotation.SuppressLint +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.PixelFormat +import android.provider.Settings +import android.view.Gravity +import android.view.MotionEvent +import android.view.View +import android.view.ViewConfiguration +import android.view.WindowManager + +/** + * A push-to-talk button floating over other apps. Holding it talks; a double tap whose + * second touch is held moves it instead, so moving never transmits more than the first tap. + */ +class PttOverlay( + private val context: Context, + private val icons: IconTheme, + private val onPressed: (Boolean) -> Unit, +) { + enum class Look { IDLE, TALKING, MUTED } + + private val windows = context.getSystemService(WindowManager::class.java) + private val prefs = context.getSharedPreferences("overlay", Context.MODE_PRIVATE) + private val size = (SIZE_DP * context.resources.displayMetrics.density).toInt() + private var button: Button? = null + + /** Shows the button, or updates it when it is up; nothing while the app may not draw over others. */ + fun show(look: Look) { + button?.let { + it.look = look + return + } + if (!Settings.canDrawOverlays(context)) return + val params = WindowManager.LayoutParams( + size, size, + WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, + WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, + PixelFormat.TRANSLUCENT, + ).apply { + gravity = Gravity.TOP or Gravity.START + val screen = windows.currentWindowMetrics.bounds + x = prefs.getInt(POS_X, screen.width() - size - size / 4) + y = prefs.getInt(POS_Y, screen.height() / 2) + } + val view = Button(params).also { it.look = look } + try { + windows.addView(view, params) + } catch (e: WindowManager.BadTokenException) { + // The permission went away since the check. + return + } + button = view + } + + fun hide() { + val view = button ?: return + button = null + view.release() + windows.removeView(view) + } + + @SuppressLint("ViewConstructor") + private inner class Button(private val params: WindowManager.LayoutParams) : View(context) { + + var look = Look.IDLE + set(value) { + field = value + restyle() + } + + private val paint = Paint(Paint.ANTI_ALIAS_FLAG) + private val doubleTapTimeout = ViewConfiguration.getDoubleTapTimeout().toLong() + private var pressed = false + private var dragging = false + private var lastTapUp = 0L + private var grabX = 0f + private var grabY = 0f + + init { + contentDescription = "Push to talk" + alpha = RESTING_ALPHA + } + + /** Half see-through at rest, so it hides less of the app beneath; solid while it talks. */ + private fun restyle() { + alpha = if (pressed || look == Look.TALKING) 1f else RESTING_ALPHA + invalidate() + } + + override fun onDraw(canvas: Canvas) { + val radius = width / 2f + val lit = pressed || look == Look.TALKING + paint.color = when { + look == Look.MUTED -> MUTED + lit -> TALKING + else -> IDLE + } + canvas.drawCircle(radius, radius, radius, paint) + if (lit) { + paint.color = Color.WHITE + paint.style = Paint.Style.STROKE + paint.strokeWidth = radius / 12 + canvas.drawCircle(radius, radius, radius - paint.strokeWidth, paint) + paint.style = Paint.Style.FILL + } + val iconSize = width / 2 + icon(iconSize)?.let { + val offset = (width - iconSize) / 2f + canvas.drawBitmap(it, offset, offset, null) + } + } + + private fun icon(size: Int): Bitmap? = + icons.renderMaterial(if (look == Look.MUTED) "INPUT_MUTED" else "CAPTURE", size, Color.WHITE) + + @SuppressLint("ClickableViewAccessibility") + override fun onTouchEvent(e: MotionEvent): Boolean { + when (e.actionMasked) { + MotionEvent.ACTION_DOWN -> { + dragging = e.eventTime - lastTapUp < doubleTapTimeout + if (dragging) { + grabX = e.rawX - params.x + grabY = e.rawY - params.y + } else { + press(true) + } + } + MotionEvent.ACTION_MOVE -> if (dragging) moveTo(e.rawX - grabX, e.rawY - grabY) + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { + val tap = !dragging && e.eventTime - e.downTime < doubleTapTimeout + lastTapUp = if (tap) e.eventTime else 0L + if (dragging) { + dragging = false + prefs.edit().putInt(POS_X, params.x).putInt(POS_Y, params.y).apply() + } else { + press(false) + } + } + } + return true + } + + private fun moveTo(x: Float, y: Float) { + val screen = windows.currentWindowMetrics.bounds + params.x = x.toInt().coerceIn(0, screen.width() - width) + params.y = y.toInt().coerceIn(0, screen.height() - height) + windows.updateViewLayout(this, params) + } + + private fun press(down: Boolean) { + if (pressed == down) return + pressed = down + onPressed(down) + restyle() + } + + /** Lets go of the microphone should the button vanish under the finger. */ + fun release() = press(false) + } + + private companion object { + const val SIZE_DP = 64 + const val RESTING_ALPHA = 0.5f + const val POS_X = "x" + const val POS_Y = "y" + val IDLE = Color.rgb(0x1C, 0x6F, 0xB8) + val TALKING = Color.rgb(0x2E, 0x9B, 0xF0) + val MUTED = Color.rgb(0x42, 0x42, 0x42) + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ReplyReceiver.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ReplyReceiver.kt new file mode 100644 index 0000000..60cad53 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ReplyReceiver.kt @@ -0,0 +1,17 @@ +package eu.lixko.ts3j.client.android + +import android.app.RemoteInput +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent + +/** Sends what the user typed into a private message notification. */ +class ReplyReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + val serverId = intent.getIntExtra(MessageNotifier.EXTRA_SERVER, -1) + val clientId = intent.getIntExtra(MessageNotifier.EXTRA_CHAT, -1) + val text = RemoteInput.getResultsFromIntent(intent)?.getCharSequence(MessageNotifier.KEY_REPLY)?.toString() + if (serverId < 0 || clientId < 0 || text.isNullOrBlank()) return + (context.applicationContext as Ts3Application).sessions.reply(serverId, clientId, text) + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/SavedPictures.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/SavedPictures.kt new file mode 100644 index 0000000..f8fe5c8 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/SavedPictures.kt @@ -0,0 +1,39 @@ +package eu.lixko.ts3j.client.android + +import android.content.ContentValues +import android.content.Context +import android.graphics.BitmapFactory +import android.os.Environment +import android.provider.MediaStore +import android.webkit.MimeTypeMap +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** Puts pictures into the shared Pictures collection, in a TeamSpeak album, where galleries find them. */ +object SavedPictures { + + /** Saves [data] as [name], its extension following what the data is; false if it could not be. */ + suspend fun save(context: Context, name: String, data: ByteArray): Boolean = withContext(Dispatchers.IO) { + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeByteArray(data, 0, data.size, bounds) + val mime = bounds.outMimeType ?: return@withContext false + val extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mime) + val values = ContentValues().apply { + put(MediaStore.Images.Media.DISPLAY_NAME, if (extension == null) name else "$name.$extension") + put(MediaStore.Images.Media.MIME_TYPE, mime) + put(MediaStore.Images.Media.RELATIVE_PATH, "${Environment.DIRECTORY_PICTURES}/TeamSpeak") + put(MediaStore.Images.Media.IS_PENDING, 1) + } + val resolver = context.contentResolver + val uri = resolver.insert(MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY), values) + ?: return@withContext false + try { + resolver.openOutputStream(uri)!!.use { it.write(data) } + resolver.update(uri, ContentValues().apply { put(MediaStore.Images.Media.IS_PENDING, 0) }, null, null) + true + } catch (e: Exception) { + resolver.delete(uri, null, null) + false + } + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt new file mode 100644 index 0000000..459129d --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt @@ -0,0 +1,582 @@ +package eu.lixko.ts3j.client.android + +import android.net.Uri +import eu.lixko.ts3j.client.config.Bookmark +import eu.lixko.ts3j.client.contacts.ContactType +import eu.lixko.ts3j.client.config.WhisperList +import eu.lixko.ts3j.client.net.ChannelNode +import eu.lixko.ts3j.client.net.ClientEntry +import eu.lixko.ts3j.client.net.ChannelSettings +import eu.lixko.ts3j.client.net.ConnectionStats +import eu.lixko.ts3j.client.net.Details +import eu.lixko.ts3j.client.net.GroupChoice +import eu.lixko.ts3j.client.net.Whisper +import eu.lixko.ts3j.client.net.ban.BanEntry +import eu.lixko.ts3j.client.net.ban.BanRule +import eu.lixko.ts3j.client.net.filetransfer.RemoteFile +import eu.lixko.ts3j.client.net.ConnectionListener.ChatScope +import eu.lixko.ts3j.client.session.ServerLink +import eu.lixko.ts3j.client.session.ServerSession +import eu.lixko.ts3j.client.text.ChatHtml +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.File +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicLong +import kotlin.coroutines.resume +import kotlin.coroutines.suspendCoroutine + +/** + * One server the app is on: its [ServerSession], and the snapshots the UI shows of it. Session + * callbacks arrive on connection threads and are turned into immutable snapshots. + */ +class ServerController internal constructor( + /** Unique among the servers of this process run. */ + val id: Int, + private val app: SessionController, +) { + internal val session = ServerSession( + app.settings, app.identityStore, app.audio, app.sounds, app.contactStore, Listener() + ) + internal val conn get() = session.connection() + private val network = app.network.follow(session, ::refresh, ::system) + + /** Whether this server holds the microphone; set by [SessionController] as it moves. */ + @Volatile + internal var micOwner = false + + /** Set once connecting began, so a session that never started is not taken for one that ended. */ + @Volatile + private var started = false + + /** Set when the user left, so the end needs no telling. */ + @Volatile + internal var left = false + + private val _state = MutableStateFlow(SessionState()) + val state: StateFlow = _state + + private val _tree = MutableStateFlow(ServerTree()) + val tree: StateFlow = _tree + + private val _chats = MutableStateFlow(Chats()) + val chats: StateFlow = _chats + + /** Channels the user folded away in the tree. */ + private val _collapsed = MutableStateFlow(emptySet()) + val collapsed: StateFlow> = _collapsed + + /** The conversation on screen, whose new lines are read as they come. */ + @Volatile + var viewing: ChatKey? = null + set(value) { + field = value + if (value != null) markRead(value) + if (value is ChatKey.Private) app.notifier.clear(id, value.clientId) + } + + /** Counts the answers to info requests, for the details on screen to be read again. */ + private val _infoUpdates = MutableStateFlow(0) + val infoUpdates: StateFlow = _infoUpdates + + val images = ServerImages(conn) + + /** A private chat a notification asked to show, until the UI took it up. */ + private val _chatRequest = MutableStateFlow(null) + val chatRequest: StateFlow = _chatRequest + + private val lineIds = AtomicLong() + + /** Tree snapshots are taken one at a time, at most once per [TREE_FRAME_MS]. */ + private val treeScope = CoroutineScope(SupervisorJob() + Dispatchers.Default.limitedParallelism(1)) + private val treePending = AtomicBoolean() + private val structureChanged = AtomicBoolean(true) + private var roots: List = emptyList() + + val isConnected: Boolean get() = session.isConnected + internal val isBusy: Boolean get() = session.isBusy || network.isRecovering + internal val microphone get() = if (session.isConnected) conn.microphone else null + internal val playback get() = if (session.isConnected) conn.playback else null + + /** Not on the server and not trying to get back on it: done with. */ + internal val ended: Boolean get() = started && !isBusy + + // ---- connection ---- + + internal fun start(host: String, port: Int, nickname: String, password: String, identityId: String, + channel: String, channelPassword: String) { + network.connecting() + started = true + session.connect(host, port, nickname, password, identityId, channel, channelPassword) + refresh() + } + + internal fun open(link: ServerLink, identityId: String) { + network.connecting() + started = true + session.open(link, identityId) + refresh() + } + + /** A bookmark leading back to this server, joining [channelId]; not yet saved. */ + fun bookmark(channelId: Int): Bookmark? = session.toBookmark(conn.model.channelPath(channelId)) + + fun disconnect() { + left = true + network.leaving() + session.disconnect() + } + + /** Before the app goes away with the connection, which [SessionController.leave] then ends. */ + internal fun leaving() { + left = true + network.leaving() + } + + internal fun dispose() { + network.forget() + treeScope.cancel() + session.dispose() + } + + // ---- the local client ---- + + fun setMicMuted(muted: Boolean) = session.setMicMuted(muted) + + fun setDeafened(deafened: Boolean) = session.setDeafened(deafened) + + fun setAway(away: Boolean) = session.setAway(away, null) + + // ---- channels and clients ---- + + fun joinChannel(channelId: Int, password: String? = null) { + if (session.isConnected) conn.joinChannel(channelId, password) + } + + fun setSubscribed(channelId: Int, subscribed: Boolean) { + if (session.isConnected) conn.setChannelsSubscribed(listOf(channelId), subscribed) + } + + fun toggleCollapsed(channelId: Int) = + _collapsed.update { if (channelId in it) it - channelId else it + channelId } + + fun expand(channelIds: Collection) = _collapsed.update { it - channelIds.toSet() } + + val canMoveClients: Boolean get() = session.canMoveClients() + + fun moveClient(clientId: Int, channelId: Int) { + if (session.isConnected) conn.moveClient(clientId, channelId, null) + } + + fun poke(clientId: Int, message: String) { + if (session.isConnected) conn.poke(clientId, message) + } + + /** The client's playback volume change in dB; 0 when unchanged. */ + fun clientVolume(clientId: Int): Double = + conn.model.getClient(clientId)?.let { conn.getClientVolumeModifier(it) } ?: 0.0 + + fun setClientVolume(clientId: Int, decibels: Double) { + conn.model.getClient(clientId)?.let { conn.setClientVolumeModifier(it, decibels) } + } + + // ---- whisper ---- + + fun setWhisper(whisper: Whisper?) = session.setWhisper(whisper) + + fun whisperToChannel(channelId: Int) = conn.model.getChannel(channelId)?.let { setWhisper(Whisper.toChannel(it)) } + + fun whisperToClient(clientId: Int) = conn.model.getClient(clientId)?.let { setWhisper(Whisper.toClient(it)) } + + /** The client who whispered to us last, while on the server. */ + fun lastWhisperer(): ClientEntry? = session.lastWhisperer() + + /** A channel as a whisper list holds it: by path, so the list works on any server with that channel. */ + fun channelRef(channelId: Int): String? = conn.model.getChannel(channelId)?.let { conn.model.channelPath(it.id) } + + fun clientRef(clientId: Int): WhisperList.Client? = + conn.model.getClient(clientId)?.let { WhisperList.Client(it.uniqueId, it.nickname) } + + /** The clients on the server, for adding to a whisper list; ourselves left out. */ + fun clientRefs(): List = if (!session.isConnected) emptyList() + else conn.model.allClients().filter { it.id != conn.selfClientId && !it.uniqueId.isNullOrEmpty() } + .sortedBy { it.nickname.lowercase() }.map { WhisperList.Client(it.uniqueId, it.nickname) } + + fun channelPaths(): List = session.channelPaths() + + // ---- channel administration ---- + + val canCreateChannels: Boolean get() = session.canCreateChannels() + val canEditChannels: Boolean get() = session.canEditChannels() + val canDeleteChannels: Boolean get() = session.canDeleteChannels() + + /** The channels a channel can sort after: its siblings, or [parentId]'s children for a new one. */ + fun sortChoices(channelId: Int, parentId: Int): List = + if (channelId > 0) conn.model.siblingsOf(channelId) else conn.model.childrenOf(parentId) + + /** A channel's editable properties as the server has them. */ + suspend fun channelSettings(channelId: Int): Result = suspendCoroutine { done -> + conn.requestChannelSettings(channelId) { settings, error -> + done.resume(if (error == null) Result.success(settings) else Result.failure(IllegalStateException(error))) + } + } + + /** Each of these answers null once done, else why not. */ + suspend fun editChannel(channelId: Int, changes: Map): String? = + if (changes.isEmpty()) null + else suspendCoroutine { done -> conn.applyChannelEdit(channelId, changes, emptyMap(), emptyList()) { done.resume(it) } } + + suspend fun createChannel(parentId: Int, settings: ChannelSettings): String? = suspendCoroutine { done -> + conn.createChannel(parentId, settings.creationParameters(), emptyMap()) { _, error -> done.resume(error) } + } + + /** Deletes a channel, with its sub-channels and the clients in it moved out. */ + suspend fun deleteChannel(channelId: Int): String? = + suspendCoroutine { done -> conn.deleteChannel(channelId, true) { done.resume(it) } } + + // ---- files ---- + + val files = app.fileTransfers { conn } + + /** The files in a directory of a channel's repository; empty for an empty one. */ + suspend fun listFiles(channelId: Int, password: String, path: String): Result> = + withContext(Dispatchers.IO) { runCatching { conn.listFiles(channelId, password, path) } } + + /** Each of these answers null once done, else why not. */ + suspend fun createDirectory(channelId: Int, password: String, path: String): String? = + fileCall { conn.createDirectory(channelId, password, path) } + + suspend fun deleteFile(channelId: Int, password: String, path: String): String? = + fileCall { conn.deleteFile(channelId, password, path) } + + suspend fun renameFile(channelId: Int, password: String, from: String, to: String): String? = + fileCall { conn.renameFile(channelId, password, from, to) } + + private suspend fun fileCall(call: () -> Unit): String? = withContext(Dispatchers.IO) { + runCatching(call).exceptionOrNull()?.let { it.message ?: it.javaClass.simpleName } + } + + // ---- moderation ---- + + val canKickFromChannel: Boolean get() = session.canKickFromChannel() + val canKickFromServer: Boolean get() = session.canKickFromServer() + val canBanClients: Boolean get() = session.canBanClients() + val canViewBanList: Boolean get() = session.canViewBanList() + val canCreateBans: Boolean get() = session.isConnected && conn.model.permits("b_client_ban_create") + + /** The longest ban we may hand out in seconds; 0 or -1 for no limit. */ + val maxBanSeconds: Long get() = conn.model.maxBanSeconds() + + fun kickFromChannel(clientId: Int, reason: String) { + if (session.isConnected) conn.kickFromChannel(clientId, reason) + } + + fun kickFromServer(clientId: Int, reason: String) { + if (session.isConnected) conn.kickFromServer(clientId, reason) + } + + /** Bans a client for [seconds], or for good with 0. */ + fun ban(clientId: Int, seconds: Long, reason: String) { + if (session.isConnected) conn.banClient(clientId, seconds, reason) + } + + fun serverGroupChoices(clientId: Int): List = + conn.model.getClient(clientId)?.let(conn.model::serverGroupChoices).orEmpty() + + fun channelGroupChoices(clientId: Int): List = + conn.model.getClient(clientId)?.let(conn.model::channelGroupChoices).orEmpty() + + fun setServerGroup(clientId: Int, groupId: Int, assign: Boolean) { + val client = conn.model.getClient(clientId) ?: return + if (session.isConnected) conn.setClientServerGroup(client.databaseId, groupId, assign) + } + + /** Gives a client [groupId] in the channel they are in. */ + fun setChannelGroup(clientId: Int, groupId: Int) { + val client = conn.model.getClient(clientId) ?: return + if (session.isConnected) conn.setClientChannelGroup(client.databaseId, client.channelId, groupId) + } + + // ---- ban list ---- + + /** The server's bans, or why they could not be read. */ + /** One reading of a client's connection figures, or null when not connected. */ + suspend fun connectionStats(clientId: Int): ConnectionStats? = + if (!session.isConnected) null + else suspendCoroutine { done -> conn.requestConnectionInfo(clientId) { done.resume(it) } } + + suspend fun banList(): Result> = suspendCoroutine { done -> + conn.requestBanList { bans, error -> + done.resume(if (error == null) Result.success(bans) else Result.failure(IllegalStateException(error))) + } + } + + /** Each of these answers null once done, else why not. */ + suspend fun addBan(rule: BanRule): String? = suspendCoroutine { done -> conn.addBan(rule) { done.resume(it) } } + + suspend fun replaceBan(banId: Int, rule: BanRule): String? = + suspendCoroutine { done -> conn.replaceBan(banId, rule) { done.resume(it) } } + + suspend fun deleteBans(banIds: Collection): String? = + suspendCoroutine { done -> conn.deleteBans(banIds) { done.resume(it) } } + + fun canDeleteBans(bans: Collection): Boolean = conn.model.canDeleteBans(bans, conn.selfUniqueId) + + fun canEditBan(ban: BanEntry): Boolean = conn.model.canEditBan(ban, conn.selfUniqueId) + + fun isOwnBan(ban: BanEntry): Boolean = ban.createdBy(conn.selfUniqueId) + + /** Uploads [data] as our avatar; null once it is set, else why not. */ + suspend fun setAvatar(data: ByteArray): String? { + if (!session.isConnected) return "Not connected" + val file = withContext(Dispatchers.IO) { + File.createTempFile("avatar", null, app.cacheDir).apply { writeBytes(data) } + } + return try { + suspendCoroutine { done -> conn.setAvatar(file) { done.resume(it) } } + } finally { + file.delete() + } + } + + // ---- details ---- + + fun serverDetails(): Details? = + if (session.isConnected) Details.server(conn.model, "${conn.serverHost}:${conn.serverPort}") else null + + fun channelDetails(channelId: Int): Details? = conn.model.getChannel(channelId)?.let(Details::channel) + + fun clientDetails(clientId: Int): Details? = conn.model.getClient(clientId)?.let { + Details.client(it, conn.model, app.contactStore.find(it.uniqueId)) + } + + /** Asks the server for what the channel's details lack; they change once it answers. */ + fun requestChannelDetails(channelId: Int) { + val channel = conn.model.getChannel(channelId) ?: return + if (session.isConnected && !channel.descriptionLoaded) conn.requestChannelInfo(channelId) + } + + fun requestClientDetails(clientId: Int) { + if (session.isConnected) conn.requestClientInfo(clientId) + } + + /** Files a client on the server as a contact; a new entry takes the type's defaults. */ + fun addContact(clientId: Int, type: ContactType) { + val client = conn.model.getClient(clientId) ?: return + app.contactStore.add(client.uniqueId, client.nickname, type, app.settings.contactDefaults) + } + + internal fun contactsChanged() { + treeScope.launch { conn.applyContacts() } + scheduleTree(structure = false) + } + + // ---- chat ---- + + /** Opens the private chat with a client, loading what was said before. */ + fun openPrivateChat(clientId: Int): ChatKey.Private { + val key = ChatKey.Private(clientId) + val client = conn.model.getClient(clientId) + if (client != null) { + _chats.update { chats -> + chats.update(key, conn.displayName(client)) { it.copy(uniqueId = client.uniqueId) } + } + conn.loadPrivateChatHistory(clientId, client.uniqueId) + } + return key + } + + fun closePrivateChat(key: ChatKey.Private) = _chats.update { it.close(key) } + + fun send(key: ChatKey, text: String) = session.sendChat(scope(key), peer(key), text) + + /** Shares the file at [uri] in a chat, through myTeamSpeak; failures are told in the chat or as errors. */ + suspend fun sendFile(key: ChatKey, uri: Uri) { + app.openShared(uri) + .onSuccess { session.sendAttachment(scope(key), peer(key), app.attachments, it.data, it.size, it.name) } + .onFailure { app.error(it.message ?: "Could not read the file") } + } + + private fun scope(key: ChatKey) = when (key) { + ChatKey.Server -> ChatScope.SERVER + ChatKey.Channel -> ChatScope.CHANNEL + is ChatKey.Private -> ChatScope.PRIVATE + } + + private fun peer(key: ChatKey) = if (key is ChatKey.Private) key.clientId else 0 + + /** Where files shared on this server lie; empty before it is known. */ + private val room: String get() = conn.serverUniqueId().orEmpty() + + fun markRead(key: ChatKey) { + if (_chats.value[key]?.unread == true) _chats.update { chats -> chats.update(key) { it.copy(unread = false) } } + } + + internal fun requestChat(clientId: Int) { + _chatRequest.value = ChatKey.Private(clientId) + } + + fun chatRequestHandled() { + _chatRequest.value = null + } + + /** Answers a private message from its notification. */ + internal fun reply(clientId: Int, text: String) { + if (session.isConnected) send(ChatKey.Private(clientId), text) else app.notifier.clear(id, clientId) + } + + private fun append(key: ChatKey, title: String, html: String) { + if (html.isEmpty()) return + val line = ChatLine(lineIds.incrementAndGet(), html) + _chats.update { chats -> chats.update(key, title) { it.append(line, read = viewing == key) } } + } + + private fun setHistory(key: ChatKey, title: String, entries: List) { + val lines = entries.map { ChatHtml.logEntry(it, room) }.filter { it.isNotEmpty() } + .map { ChatLine(lineIds.incrementAndGet(), it) } + _chats.update { chats -> chats.update(key, title) { it.copy(lines = lines) } } + } + + private fun system(text: String) = append(ChatKey.Server, "", ChatHtml.system(text)) + + // ---- snapshots ---- + + private fun snapshotState(): SessionState { + val self = conn.model.getClient(conn.selfClientId) + return SessionState( + title = session.title(), + status = network.status ?: session.status(), + connected = session.isConnected, + busy = isBusy, + micActive = micOwner && app.hasMicPermission(), + micPermission = app.hasMicPermission(), + micMuted = session.isMicMuted, + deafened = session.isDeafened, + away = session.isAway, + selfClientId = if (session.isConnected) conn.selfClientId else 0, + channelId = if (session.isConnected) self?.channelId ?: 0 else 0, + inputMode = app.settings.inputMode, + hostButton = if (session.isConnected) conn.model.hostButton() else null, + self = session.selfState(), + whisper = session.whisper()?.label, + whisperNobody = session.isWhisperingToNobody, + ) + } + + internal fun refresh() { + _state.value = snapshotState() + app.serverChanged(this) + } + + /** Takes a new tree snapshot soon; [structure] when channels or clients came, went or moved. */ + internal fun scheduleTree(structure: Boolean) { + if (structure) structureChanged.set(true) + if (!treePending.compareAndSet(false, true)) return + treeScope.launch { + delay(TREE_FRAME_MS) + treePending.set(false) + if (structureChanged.getAndSet(false)) roots = conn.model.buildTree() + _tree.value = ServerTree.of(roots, conn.model, conn.contacts, app.settings.colorContacts, + app.settings.countryFlags, app.settings.clientRowColors) + val serverName = if (session.isConnected) conn.model.serverName.orEmpty() else "" + val channelName = session.currentChannel()?.name.orEmpty() + _chats.update { + it.copy( + server = it.server.copy(title = serverName.ifBlank { "Server" }), + channel = it.channel.copy(title = channelName.ifBlank { "Channel" }), + ) + } + refresh() + } + } + + private inner class Listener : ServerSession.Listener { + override fun onSessionChanged() = refresh() + override fun onSystemMessage(text: String) = system(text) + + override fun onOwnChat(scope: ChatScope, peerClientId: Int, peerName: String, text: String) { + val self = conn.model.getClient(conn.selfClientId)?.nickname ?: app.settings.nickname + val html = ChatHtml.message(conn.selfClientId, conn.selfUniqueId, "$self (you)", text, room) + append(key(scope, peerClientId), peerName, html) + if (scope == ChatScope.PRIVATE) app.notifier.sent(id, peerClientId, ChatHtml.plainMessage(text)) + } + + override fun onStatus(status: String) {} + + override fun onConnected() { + network.onConnected() + app.connected(this@ServerController) + refresh() + } + + override fun onDisconnected(reason: String?) { + network.onDisconnected() + app.notifier.clearServer(id) + _chats.update { it.copy(private = emptyList()) } + app.disconnected(this@ServerController) + scheduleTree(structure = true) + refresh() + } + + override fun onModelChanged() { + scheduleTree(structure = true) + // A server edit may have changed it. + if (session.isConnected && conn.model.hostButton() != _state.value.hostButton) refresh() + } + + override fun onServerIconChanged(iconId: Long) = + app.serverIconChanged(session.address(), session.port(), iconId) + + override fun onInfoUpdated() { + _infoUpdates.update { it + 1 } + // Avatars announce their arrival as info updates. + images.loaded() + } + + override fun onIconsUpdated() = images.loaded() + + override fun onChat(scope: ChatScope, fromClientId: Int, fromUniqueId: String?, fromName: String, message: String) { + append(key(scope, fromClientId), fromName, ChatHtml.message(fromClientId, fromUniqueId, fromName, message, room)) + if (scope == ChatScope.PRIVATE && !app.foreground) { + app.notifier.received(id, fromClientId, fromName, ChatHtml.plainMessage(message)) + } + } + + override fun onChatHistory(scope: ChatScope, htmlEntries: List) { + if (scope != ChatScope.PRIVATE) setHistory(key(scope, 0), "", htmlEntries) + } + + override fun onPrivateChatHistory(clientId: Int, nickname: String, htmlEntries: List) = + setHistory(ChatKey.Private(clientId), nickname, htmlEntries) + + override fun onTalkStateChanged(clientId: Int, talking: Boolean) { + if (clientId == conn.selfClientId && micOwner) app.talking(talking) + scheduleTree(structure = false) + } + + override fun onError(message: String) = app.error(message) + + override fun onPoke(fromName: String, message: String) = app.poked(fromName, message) + + override fun onServerLog(message: String) = append(ChatKey.Server, "", ChatHtml.serverLog(message)) + override fun onServerLogHtml(html: String) = append(ChatKey.Server, "", ChatHtml.logEntry(html, room)) + } + + private fun key(scope: ChatScope, peerClientId: Int): ChatKey = when (scope) { + ChatScope.SERVER -> ChatKey.Server + ChatScope.CHANNEL -> ChatKey.Channel + ChatScope.PRIVATE -> ChatKey.Private(peerClientId) + } + + private companion object { + const val TREE_FRAME_MS = 30L + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerImages.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerImages.kt new file mode 100644 index 0000000..6b98439 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerImages.kt @@ -0,0 +1,61 @@ +package eu.lixko.ts3j.client.android + +import android.graphics.BitmapFactory +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.asImageBitmap +import eu.lixko.ts3j.client.net.TeamspeakConnection +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.update +import java.util.concurrent.ConcurrentHashMap + +/** + * One server's icons and its clients' avatars, decoded once. What is still + * downloading reads as null until [version] moves on. + */ +class ServerImages internal constructor(private val conn: TeamspeakConnection) { + + private val icons = ConcurrentHashMap() + private val avatars = ConcurrentHashMap() + + private val _version = MutableStateFlow(0) + val version: StateFlow = _version + + internal fun loaded() = _version.update { it + 1 } + + fun icon(id: Long): ImageBitmap? { + if (id == 0L) return null + icons[id]?.let { return it } + val bitmap = conn.icons.get(id)?.let { decode(it, ICON_PX) } ?: return null + icons[id] = bitmap + return bitmap + } + + fun avatar(uniqueId: String, flag: String): Picture? { + if (flag.isEmpty()) return null + avatars[flag]?.let { return it } + val picture = conn.avatars.get(uniqueId, flag)?.let { decodePicture(it.data(), AVATAR_PX) } ?: return null + avatars[flag] = picture + return picture + } + + /** The avatar's file as the server keeps it; null while it has none or it is still downloading. */ + fun avatarData(uniqueId: String, flag: String): ByteArray? = + if (flag.isEmpty()) null else conn.avatars.get(uniqueId, flag)?.data() + + /** Decoded no larger than needed: avatars may be far bigger than they are ever shown. */ + private fun decode(data: ByteArray, maxPx: Int): ImageBitmap? { + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeByteArray(data, 0, data.size, bounds) + if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null + var sample = 1 + while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= maxPx) sample *= 2 + val options = BitmapFactory.Options().apply { inSampleSize = sample } + return BitmapFactory.decodeByteArray(data, 0, data.size, options)?.asImageBitmap() + } + + private companion object { + const val ICON_PX = 64 + const val AVATAR_PX = 512 + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerTree.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerTree.kt new file mode 100644 index 0000000..9729bd2 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerTree.kt @@ -0,0 +1,192 @@ +package eu.lixko.ts3j.client.android + +import androidx.compose.runtime.Immutable +import eu.lixko.ts3j.client.config.ClientRowColors +import eu.lixko.ts3j.client.contacts.ContactStore +import eu.lixko.ts3j.client.contacts.ContactType +import eu.lixko.ts3j.client.net.ChannelNode +import eu.lixko.ts3j.client.net.ClientEntry +import eu.lixko.ts3j.client.net.ClientStatus +import eu.lixko.ts3j.client.net.ServerModel +import eu.lixko.ts3j.client.net.Spacers +import eu.lixko.ts3j.client.net.TreeMatch +import eu.lixko.ts3j.client.text.TextQuery + +/** + * A copy of the channel tree taken at one moment. The model's own nodes change in place + * on connection threads, which Compose cannot observe; these never change. + */ +@Immutable +data class ServerTree( + val channels: List = emptyList(), + /** The server's own icon; 0 for none. */ + val serverIconId: Long = 0, + /** Whether client rows show their country's flag. */ + val countryFlags: Boolean = false, +) { + + fun channel(id: Int): ChannelItem? = find(channels) { it.id == id } + + fun client(id: Int): ClientItem? { + var found: ClientItem? = null + find(channels) { c -> found = c.clients.firstOrNull { it.id == id }; found != null } + return found + } + + /** The channels from the root down to the one [clientId] is in; null when they are not in the tree. */ + fun pathTo(clientId: Int): List? { + fun walk(items: List): List? { + for (c in items) { + if (c.clients.any { it.id == clientId }) return listOf(c.id) + walk(c.children)?.let { return listOf(c.id) + it } + } + return null + } + return walk(channels) + } + + /** The channels from the root down to [channelId]'s parent; null when it is not in the tree. */ + fun parentsOf(channelId: Int): List? { + fun walk(items: List, above: List): List? { + for (c in items) { + if (c.id == channelId) return above + walk(c.children, above + c.id)?.let { return it } + } + return null + } + return walk(channels, emptyList()) + } + + /** The ids of what [find] matches, in reading order. */ + fun hits(find: TreeFind): List { + val out = ArrayList() + fun walk(items: List) { + for (c in items) { + if (find.matches(c)) out += c.id + c.clients.forEach { if (find.matches(it)) out += it.id } + walk(c.children) + } + } + if (!find.query.isEmpty) walk(channels) + return out + } + + /** Only what [find] matches: a matching channel with its clients, a matching client, and the channels leading to either. */ + fun only(find: TreeFind): ServerTree { + fun keep(c: ChannelItem): ChannelItem? { + val matches = find.matches(c) + val clients = if (matches) c.clients else c.clients.filter(find::matches) + val children = c.children.mapNotNull(::keep) + return if (matches || clients.isNotEmpty() || children.isNotEmpty()) c.copy(clients = clients, children = children) else null + } + return copy(channels = channels.mapNotNull(::keep)) + } + + private fun find(items: List, test: (ChannelItem) -> Boolean): ChannelItem? { + for (c in items) { + if (test(c)) return c + find(c.children, test)?.let { return it } + } + return null + } + + companion object { + fun of(roots: List, model: ServerModel, contacts: ContactStore, colorContacts: Boolean, + countryFlags: Boolean, rowColors: ClientRowColors): ServerTree = + ServerTree( + roots.map { channel(it, model, contacts, colorContacts, rowColors) }, + model.serverIconId(), + countryFlags, + ) + + private fun channel(c: ChannelNode, model: ServerModel, contacts: ContactStore, colorContacts: Boolean, + rowColors: ClientRowColors): ChannelItem { + val clients = c.clients + val spacer = Spacers.parse(c.name) + return ChannelItem( + id = c.id, + name = c.name ?: "", + spacer = spacer, + iconId = if (spacer == null) c.iconId else 0, + locked = c.hasPassword, + full = c.maxClients >= 0 && clients.size >= c.maxClients, + subscribed = c.subscribed, + clients = clients.map { client(it, model, contacts, colorContacts, rowColors) }, + children = c.children.map { channel(it, model, contacts, colorContacts, rowColors) }, + ) + } + + private fun client(c: ClientEntry, model: ServerModel, contacts: ContactStore, colorContacts: Boolean, + rowColors: ClientRowColors): ClientItem { + val contact = contacts.find(c.uniqueId) + val away = c.away && c.awayMessage.isNotEmpty() && contact?.ignoreAwayMessage != true + val status = ClientStatus.of(c) + return ClientItem( + id = c.id, + uniqueId = c.uniqueId, + nickname = c.nickname ?: "", + name = contact?.displayName(c.nickname) ?: c.nickname ?: "", + awayMessage = if (away) c.awayMessage else "", + status = status, + background = rowColors.of(status), + self = c.self, + contactType = contact?.type, + highlight = if (colorContacts) contact?.type ?: ContactType.NEUTRAL else ContactType.NEUTRAL, + groupIconIds = (model.serverGroupsOf(c.serverGroupIds) + listOfNotNull(model.channelGroup(c.channelGroupId))) + .map { it.iconId }.filter { it != 0L }, + avatarFlag = c.avatarFlag.orEmpty(), + country = c.country.orEmpty(), + serverGroupIds = c.serverGroupIds.toList(), + channelGroupId = c.channelGroupId, + ) + } + } +} + +/** What the find bar looks for in the tree: clients, or with [channels] channels. */ +@Immutable +data class TreeFind(val query: TextQuery, val channels: Boolean) { + fun matches(c: ChannelItem) = channels && TreeMatch.channel(query, c.name) + fun matches(c: ClientItem) = !channels && TreeMatch.client(query, c.nickname, c.name) +} + +@Immutable +data class ChannelItem( + val id: Int, + val name: String, + /** Set for a spacer: a cosmetic separator rather than a channel to join. */ + val spacer: Spacers.Spacer?, + val locked: Boolean, + val full: Boolean, + val subscribed: Boolean, + /** 0 for none. */ + val iconId: Long, + val clients: List, + val children: List, +) + +@Immutable +data class ClientItem( + val id: Int, + val uniqueId: String, + val nickname: String, + /** The name shown: the contact's own name for them where there is one. */ + val name: String, + val awayMessage: String, + val status: ClientStatus, + /** The row's background colour, ARGB; 0 for none. */ + val background: Int, + val self: Boolean, + /** How the client is filed in the contacts; null when it is not one. */ + val contactType: ContactType?, + /** The contact colour the name is drawn in, NEUTRAL when contacts are not coloured. */ + val highlight: ContactType, + /** The icons of the client's server groups, then of its channel group, as TeamSpeak lines them up. */ + val groupIconIds: List, + /** The MD5 of the client's avatar; empty for none. */ + val avatarFlag: String, + /** The code of the country the server places the client in; empty when it cannot tell. */ + val country: String, + val serverGroupIds: List, + val channelGroupId: Int, +) diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/SessionController.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/SessionController.kt new file mode 100644 index 0000000..7394e03 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/SessionController.kt @@ -0,0 +1,657 @@ +package eu.lixko.ts3j.client.android + +import android.Manifest +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import android.os.Handler +import android.os.Looper +import android.provider.OpenableColumns +import eu.lixko.ts3j.client.android.audio.AndroidAudioBackend +import eu.lixko.ts3j.client.android.audio.AudioRoute +import eu.lixko.ts3j.client.audio.AudioDevice +import eu.lixko.ts3j.client.config.BanReasonPresets +import eu.lixko.ts3j.client.config.Bookmark +import eu.lixko.ts3j.client.config.Bookmarks +import eu.lixko.ts3j.client.config.IdentityStore +import eu.lixko.ts3j.client.config.Settings +import eu.lixko.ts3j.client.config.WhisperList +import eu.lixko.ts3j.client.config.WhisperLists +import eu.lixko.ts3j.client.contacts.Contact +import eu.lixko.ts3j.client.contacts.ContactStore +import eu.lixko.ts3j.client.myts.ChatAttachment +import eu.lixko.ts3j.client.myts.ChatAttachments +import eu.lixko.ts3j.client.myts.MyTeamSpeak +import eu.lixko.ts3j.client.myts.MyTeamSpeakLogin +import eu.lixko.ts3j.client.net.HostButton +import eu.lixko.ts3j.client.net.TeamspeakConnection +import eu.lixko.ts3j.client.session.SelfState +import eu.lixko.ts3j.client.session.ServerLink +import eu.lixko.ts3j.client.session.ServerSession +import eu.lixko.ts3j.client.session.Sessions +import eu.lixko.ts3j.client.sound.SoundNotifier +import eu.lixko.ts3j.client.sound.SoundPack +import eu.lixko.ts3j.client.teamspeak.SyncItem +import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter +import eu.lixko.ts3j.client.teamspeak.TeamSpeakSettingsDb +import eu.lixko.ts3j.client.text.BBCode +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.withContext +import java.io.File +import java.io.IOException +import java.io.InputStream +import java.util.concurrent.atomic.AtomicInteger + +/** What the app shows of a connection and the local client on it. */ +data class SessionState( + val title: String = "", + val status: String = "Not connected", + val connected: Boolean = false, + val busy: Boolean = false, + /** Whether this server holds the microphone, which only one server can at a time. */ + val micActive: Boolean = false, + val micPermission: Boolean = false, + val micMuted: Boolean = false, + val deafened: Boolean = false, + val away: Boolean = false, + val selfClientId: Int = 0, + val channelId: Int = 0, + val inputMode: Settings.InputMode = Settings.InputMode.VOICE_ACTIVATION, + val hostButton: HostButton? = null, + /** What the tree shows for the local client, and the connection notification too. */ + val self: SelfState = SelfState.DISCONNECTED, + /** Who the microphone whispers to instead of the channel; null when it talks in the channel. */ + val whisper: String? = null, + /** Whether none of the whisper's channels and clients are on the server, so nobody hears it. */ + val whisperNobody: Boolean = false, +) + +/** A file to share in chat, open for reading. */ +internal class SharedFile(val name: String, val size: Long, val data: InputStream) + +/** Something that happened once, for the UI to tell the user about. */ +sealed interface SessionEvent { + data class Poke(val from: String, val message: String) : SessionEvent + data class Error(val message: String) : SessionEvent + /** A link or shortcut brought a server on screen, in front of whatever page was open. */ + data object ServerOpened : SessionEvent +} + +/** + * The servers the app is on and what they share, outliving any activity: [ConnectionService] + * keeps the process in the foreground while any is connected. Only one server captures with + * the microphone at a time; [Sessions] hands it over. + */ +class SessionController(private val context: Context) { + + val settings: Settings = Settings.load() + val icons = IconTheme(context, settings) + private val shortcuts = BookmarkShortcuts(context, icons) + val pictures = WebPictures(context.cacheDir, settings) + internal val cacheDir: File get() = context.cacheDir + internal fun fileTransfers(conn: () -> TeamspeakConnection) = FileTransfers(context, conn) + private val bookmarkStore = Bookmarks.load() + internal val identityStore = IdentityStore.load(settings) + val identities = IdentityManager(context, identityStore, settings, bookmarkStore) { + _bookmarks.value = bookmarkStore.all().toList() + } + internal val audio = AndroidAudioBackend(context) + private val soundPlayer = SpeakingSoundPlayer(context, audio.createSoundPlayer(settings)) + internal val sounds = SoundNotifier(settings).also { it.setPlayer(soundPlayer) } + internal val notifier = MessageNotifier(context) + internal val contactStore = ContactStore.load() + /** The reasons offered when adding a ban; shared by every server. */ + val banReasons: BanReasonPresets by lazy { BanReasonPresets.load() } + internal val network = NetworkFollower(context) + + private val main = Handler(Looper.getMainLooper()) + private val nextId = AtomicInteger() + /** Touched on the main thread only, as [Sessions] wants. */ + private val sessions = Sessions { main.post(::microphoneMoved) } + + private val _servers = MutableStateFlow(emptyList()) + /** Every server the app is on or getting on, in the order they were connected. */ + val servers: StateFlow> = _servers + + private val _current = MutableStateFlow(null) + /** The server on screen; null when there is none. */ + val current: StateFlow = _current + + private val _micOwner = MutableStateFlow(null) + /** The server capturing with the microphone; null when none is. */ + val micOwner: StateFlow = _micOwner + + /** Why the last connection that ended did, for the connect form to show; null when it was left. */ + private val _lastEnd = MutableStateFlow(null) + val lastEnd: StateFlow = _lastEnd + + /** Copies of the contacts, as the store's own entries change in place. */ + private val _contacts = MutableStateFlow(contactCopies()) + val contacts: StateFlow> = _contacts + + private val _bookmarks = MutableStateFlow(bookmarkStore.all().toList()) + val bookmarks: StateFlow> = _bookmarks + + private val _events = MutableSharedFlow(extraBufferCapacity = 16) + val events: SharedFlow = _events + + private val _onScreen = MutableStateFlow(false) + val onScreen: StateFlow = _onScreen + + /** Whether the app is on screen; pokes and private messages are notified of while it is not. */ + var foreground: Boolean + get() = _onScreen.value + set(value) { + _onScreen.value = value + if (value) notifier.clearPokes() + // The process may be let go of any time once out of sight. + else contactStore.flush() + } + + private val levels = LevelMonitor(settings, audio) + val micLevel: StateFlow = levels.level + @Volatile + private var watchingLevel = false + + private val routePrefs = AudioRoutePrefs(context) + private val _route = MutableStateFlow(routePrefs.load()) + val route: StateFlow = _route + + private val _inputDevices = MutableStateFlow(audio.io().inputDevices()) + val inputDevices: StateFlow> = _inputDevices + private val _outputDevices = MutableStateFlow(audio.io().outputDevices()) + val outputDevices: StateFlow> = _outputDevices + + val unprocessedSupported: Boolean get() = audio.unprocessedSupported() + + init { + audio.setRoute(_route.value) + audio.addDeviceListener { + _inputDevices.value = audio.io().inputDevices() + _outputDevices.value = audio.io().outputDevices() + } + // Mutations report on whichever thread made them, a connection thread included. + contactStore.addListener { + _contacts.value = contactCopies() + _servers.value.forEach(ServerController::contactsChanged) + } + } + + /** The nickname a connect with [identityId] goes by: the identity's own, else the global one. */ + fun nicknameFor(identityId: String): String = identities.nicknameOf(identityId).ifBlank { settings.nickname } + val lastAddress: String get() = settings.lastAddress + + // ---- connection ---- + + /** Connects to `host[:port]`, as another server; an empty [identityId] means the default identity. */ + fun connect(address: String, nickname: String, password: String = "", identityId: String = "") { + val (host, port) = parseAddress(address) + settings.lastAddress = address + if (identities.nicknameOf(identityId).isBlank()) settings.nickname = nickname + settings.save() + start(host, port, nickname, password, identityId, "", "") + } + + fun connect(bookmark: Bookmark) { + start { it.start(bookmark.address, bookmark.port, bookmark.nickname.orEmpty(), bookmark.password, + bookmark.identityId, bookmark.channel, bookmark.channelPassword) } + } + + private fun start(host: String, port: Int, nickname: String, password: String, identityId: String, + channel: String, channelPassword: String) { + start { it.start(host, port, nickname, password, identityId, channel, channelPassword) } + } + + private fun start(connect: (ServerController) -> Unit) { + val server = ServerController(nextId.incrementAndGet(), this) + sessions.add(server.session) + _servers.update { it + server } + _current.value = server + _lastEnd.value = null + context.startForegroundService(Intent(context, ConnectionService::class.java)) + connect(server) + } + + /** + * Goes where a `ts3server://` link leads: on a server we are on already, to the channel it + * names; else connects there as another server. + */ + fun open(link: ServerLink, identityId: String = "") { + if (link.bookmarkLabel.isNotEmpty()) { + bookmarkStore.add(link.toBookmark()) + saveBookmarks() + } + val on = _servers.value.firstOrNull { it.session.isOn(link) } + if (on != null) { + _current.value = on + on.session.follow(link) + } else { + start { it.open(link, identityId) } + } + _events.tryEmit(SessionEvent.ServerOpened) + } + + /** What a home-screen shortcut does: connects to the bookmark, or goes to its channel when already on its server. */ + fun openBookmark(id: String): ServerLink? { + val bookmark = bookmarkStore.find(id) + if (bookmark == null) { + error("That bookmark no longer exists") + return null + } + return ServerLink.of(bookmark).also { open(it, bookmark.identityId) } + } + + private var startedUp = false + + /** Connects the bookmarks flagged for startup, once per process; [opened] is a server the launch already went to. */ + fun connectStartupBookmarks(opened: ServerLink?) { + if (startedUp) return + startedUp = true + for (b in bookmarkStore.startupBookmarks()) { + if (opened?.pointsAt(b.address, b.port) != true) start { it.open(ServerLink.of(b), b.identityId) } + } + } + + fun select(server: ServerController) { + if (server in _servers.value) _current.value = server + } + + /** Leaves every server before returning, for when the app goes away with the connections. */ + fun leave() { + val servers = _servers.value + servers.forEach(ServerController::leaving) + ServerSession.shutdownAll(servers.map { it.session }) + contactStore.flush() + attachments.close() + } + + fun server(id: Int): ServerController? = _servers.value.firstOrNull { it.id == id } + + /** A server's state changed; one that is done with goes from the list. */ + internal fun serverChanged(server: ServerController) { + if (server.micOwner) updateLevels() + if (server.ended) main.post { remove(server) } + } + + private fun remove(server: ServerController) { + if (server !in _servers.value || !server.ended) return + sessions.remove(server.session) + val rest = _servers.value - server + _servers.value = rest + if (_current.value == server) _current.value = rest.lastOrNull() + server.dispose() + val reason = server.state.value.status + _lastEnd.value = if (server.left) null else reason + if (!server.left && rest.isNotEmpty()) error("${server.state.value.title}: $reason") + } + + internal fun connected(server: ServerController) { + // The first connect generates an identity when there was none. + identities.refresh() + main.post { + // Without the permission yet, the UI hands the microphone over once it is granted. + if (hasMicPermission()) sessions.connected(server.session) + } + } + + internal fun disconnected(server: ServerController) { + main.post { sessions.disconnected(server.session) } + } + + internal fun error(message: String) { + _events.tryEmit(SessionEvent.Error(message)) + } + + internal fun poked(from: String, message: String) { + _events.tryEmit(SessionEvent.Poke(from, message)) + if (!foreground) notifier.poke(from, BBCode.toPlain(message)) + } + + internal fun talking(transmitting: Boolean) = levels.talking(transmitting) + + // ---- bookmarks ---- + + /** A bookmark to [address] as typed into the connect form, not yet saved. */ + fun newBookmark(address: String, nickname: String, password: String, identityId: String): Bookmark { + val (host, port) = parseAddress(address) + // Only a nickname other than the identity's is the server's own. + val own = nickname.takeIf { it != nicknameFor(identityId) }.orEmpty() + return Bookmark(host, host, port, own, password).also { it.identityId = identityId } + } + + /** Puts [edited] in place of the bookmark at [index], or adds it when [index] is -1. */ + fun saveBookmark(index: Int, edited: Bookmark) { + val all = bookmarkStore.all() + if (index !in all.indices) { + bookmarkStore.add(edited) + } else { + // The icon may have been learnt meanwhile, and belongs to the server, not to the bookmark. + edited.iconId = all[index].takeIf { it.pointsAt(edited.address, edited.port) }?.iconId ?: 0 + all[index] = edited + } + saveBookmarks() + } + + /** The channels of a server we are on at [host]:[port], to pick one to join. */ + fun channelPathsAt(host: String, port: Int): List = + _servers.value.firstOrNull { + it.isConnected && it.session.port() == port && it.session.address().equals(host.trim(), ignoreCase = true) + }?.session?.channelPaths().orEmpty() + + fun removeBookmark(bookmark: Bookmark) { + val index = bookmarkStore.all().indexOf(bookmark) + if (index < 0) return + bookmarkStore.remove(index) + saveBookmarks() + } + + /** Bookmarks leading to [address]:[port] take on the icon the server shows now. */ + internal fun serverIconChanged(address: String, port: Int, iconId: Long) { + main.post { + val all = bookmarkStore.all() + var changed = false + for (i in all.indices) { + val b = all[i] + if (!b.pointsAt(address, port) || b.iconId == iconId) continue + // A new entry, so the list the UI holds changes along with it. + all[i] = b.copy().also { it.iconId = iconId } + changed = true + } + if (changed) saveBookmarks() + } + } + + private fun saveBookmarks() { + bookmarkStore.save() + _bookmarks.value = bookmarkStore.all().toList() + shortcuts.sync(_bookmarks.value) + } + + val canPinShortcuts: Boolean get() = shortcuts.supported + + /** Asks the launcher for a home-screen shortcut connecting to [bookmark]. */ + fun pinShortcut(bookmark: Bookmark) { + // A bookmark not saved since ids came in has a new one on every load until it is. + bookmarkStore.save() + shortcuts.pin(bookmark) + } + + // ---- whisper lists ---- + + private val whisperListStore = WhisperLists.load() + private val _whisperLists = MutableStateFlow(whisperListCopies()) + val whisperLists: StateFlow> = _whisperLists + + private fun whisperListCopies() = whisperListStore.all().map { it.copy() } + + /** Puts [list] in place of the one at [index], or adds it when [index] is -1. */ + fun saveWhisperList(index: Int, list: WhisperList) { + val all = whisperListStore.all() + if (index in all.indices) all[index] = list.copy() else all.add(list.copy()) + whisperListStore.save() + _whisperLists.value = whisperListCopies() + } + + /** Adds a channel or a client to the list at [index], or to a new list named [newName] when [index] is -1. */ + fun addToWhisperList(index: Int, newName: String, add: (WhisperList) -> Unit) { + val list = whisperListStore.all().getOrNull(index)?.copy() ?: WhisperList(newName) + add(list) + saveWhisperList(index, list) + } + + fun removeWhisperList(index: Int) { + val all = whisperListStore.all() + if (index !in all.indices) return + all.removeAt(index) + whisperListStore.save() + _whisperLists.value = whisperListCopies() + } + + // ---- contacts ---- + + private fun contactCopies(): List = contactStore.all().map { it.copy() } + + /** A copy of the contact to edit and hand back to [saveContact]. */ + fun contact(uniqueId: String): Contact? = contactStore.find(uniqueId)?.copy() + + fun saveContact(contact: Contact) = contactStore.put(contact) + + fun removeContact(uniqueId: String) = contactStore.remove(uniqueId) + + /** + * Adds the contacts of a TeamSpeak 3 `settings.db`, overwriting entries for the same clients. + * + * @return how many contacts the file held and how many of them were new + */ + suspend fun importContacts(uri: Uri): Pair = withContext(Dispatchers.IO) { + val found = withLocalCopy(context, uri, TeamSpeakSettingsDb::readContacts) + found.size to if (found.isEmpty()) 0 else contactStore.merge(found) + } + + // ---- myTeamSpeak ---- + + /** The account the app stays signed in to; its reads block, so they run on [Dispatchers.IO]. */ + val myTeamSpeak: MyTeamSpeakLogin = MyTeamSpeakLogin.load() + private val importer = TeamSpeakImporter(identityStore, bookmarkStore, settings) + + private val _myTeamSpeakSignedIn = MutableStateFlow(myTeamSpeak.isSignedIn) + val myTeamSpeakSignedIn: StateFlow = _myTeamSpeakSignedIn + + /** Files shared in chat, kept in the myTeamSpeak account's cloud storage. */ + internal val attachments = ChatAttachments(myTeamSpeak).also { + pictures.addSource(ChatAttachment.SCHEME, it::fetchPicture) + } + + suspend fun signInMyTeamSpeak(email: String, password: String): MyTeamSpeak.Account = + withContext(Dispatchers.IO) { myTeamSpeak.signIn(email, password) } + .also { + _myTeamSpeakSignedIn.value = true + // Shared pictures that could not be had signed out. + pictures.retryFailed() + } + + suspend fun fetchMyTeamSpeak(): MyTeamSpeak.Account = + try { + withContext(Dispatchers.IO) { myTeamSpeak.fetch() } + } finally { + // A sign-in the server no longer takes has signed out. + _myTeamSpeakSignedIn.value = myTeamSpeak.isSignedIn + } + + suspend fun signOutMyTeamSpeak() { + myTeamSpeak.signOut() + _myTeamSpeakSignedIn.value = false + withContext(Dispatchers.IO) { attachments.close() } + } + + /** Fetches a file shared in chat whole. */ + suspend fun downloadAttachment(ref: ChatAttachment.Ref): ByteArray = + withContext(Dispatchers.IO) { attachments.download(ref, ChatAttachments.MAX_UPLOAD_BYTES) } + + /** Fetches a file shared in chat into [uri], e.g. one the user picked to save it as. */ + suspend fun saveAttachment(ref: ChatAttachment.Ref, uri: Uri) { + val data = downloadAttachment(ref) + withContext(Dispatchers.IO) { + val out = context.contentResolver.openOutputStream(uri) ?: throw IOException("Could not write the file") + out.use { it.write(data) } + } + } + + /** A file picked to share in chat, or why it cannot be. */ + internal suspend fun openShared(uri: Uri): Result = withContext(Dispatchers.IO) { + runCatching { + val resolver = context.contentResolver + val (name, size) = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), + null, null, null)?.use { c -> + if (!c.moveToFirst()) null + else c.getString(0).orEmpty() to (if (c.isNull(1)) -1L else c.getLong(1)) + } ?: ("" to -1L) + when { + size < 0 -> throw IOException("Could not read the file's size") + size > ChatAttachments.MAX_UPLOAD_BYTES -> + throw IOException("Files over ${ChatAttachments.MAX_UPLOAD_BYTES shr 20} MB cannot be shared") + } + val data = resolver.openInputStream(uri) ?: throw IOException("Could not read the file") + SharedFile(name.ifBlank { uri.lastPathSegment ?: "file" }, size, data) + } + } + + fun isImported(item: SyncItem): Boolean = importer.isPresent(item) + + /** Imports [chosen] out of the account's [all] items, with the identities the chosen bookmarks use. */ + suspend fun importMyTeamSpeak(all: List, chosen: List): TeamSpeakImporter.Result = + withContext(Dispatchers.IO) { importer.importSelected(all, chosen) } + .also { + _bookmarks.value = bookmarkStore.all().toList() + identities.refresh() + } + + // ---- sound packs ---- + + private val _soundPacks = MutableStateFlow(sounds.availablePacks()) + val soundPacks: StateFlow> = _soundPacks + + val soundPack: SoundPack? get() = sounds.pack() + + fun setCountryFlags(shown: Boolean) { + settings.countryFlags = shown + settings.save() + servers.value.forEach { it.scheduleTree(structure = false) } + } + + /** Puts new client row colours, already set in [settings], into effect. */ + fun clientRowColorsChanged() { + settings.save() + servers.value.forEach { it.scheduleTree(structure = false) } + } + + fun setDescriptionPictures(shown: Boolean) { + settings.descriptionPictures = shown + settings.save() + } + + fun setSoundPack(pack: SoundPack) { + sounds.setPack(pack) + settings.save() + } + + /** Unpacks the packs the app ships with, when this version has not yet. */ + fun installSoundPacks() { + if (!SoundPackInstaller(context).install()) return + sounds.reload() + _soundPacks.value = sounds.availablePacks() + } + + // ---- the local client ---- + + fun hasMicPermission() = + context.checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED + + /** Moves the microphone to [server]; needs RECORD_AUDIO granted. */ + fun giveMicrophoneTo(server: ServerController) { + if (server.isConnected) sessions.giveMicrophoneTo(server.session) + } + + /** Opens the microphone of the server holding it while push-to-talk is held. */ + fun setPushToTalk(pressed: Boolean) = sessions.setPushToTalk(pressed) + + /** Transmits on the server holding the microphone while held, past the voice-activation gate too. */ + fun setForceTransmit(pressed: Boolean) = sessions.setForceTransmit(pressed) + + private fun microphoneMoved() { + val owner = sessions.microphoneOwner() + for (server in _servers.value) { + server.micOwner = server.session == owner + server.refresh() + } + _micOwner.value = _servers.value.firstOrNull { it.micOwner } + updateLevels() + } + + private val overlayPrefs = context.getSharedPreferences("overlay", Context.MODE_PRIVATE) + private val _pttOverlay = MutableStateFlow(overlayPrefs.getBoolean(OVERLAY_ENABLED, false)) + /** Whether push to talk floats a button over other apps while this one is off screen. */ + val pttOverlay: StateFlow = _pttOverlay + + fun setPttOverlay(enabled: Boolean) { + overlayPrefs.edit().putBoolean(OVERLAY_ENABLED, enabled).apply() + _pttOverlay.value = enabled + } + + /** Switches between push to talk and voice activation; returns the new mode. */ + fun toggleInputMode(): Settings.InputMode { + settings.inputMode = if (settings.inputMode == Settings.InputMode.PUSH_TO_TALK) + Settings.InputMode.VOICE_ACTIVATION else Settings.InputMode.PUSH_TO_TALK + applySettings() + return settings.inputMode + } + + /** Saves the settings and puts the voice and device ones into effect at once. */ + fun applySettings() { + settings.save() + soundPlayer.setOutputDevice(settings.outputDevice) + try { + for (server in _servers.value) { + server.playback?.setMasterVolume(settings.outputVolume) + server.playback?.setOutputDevice(settings.outputDevice) + server.playback?.setReceiveBuffer(settings.receiveBuffer) + server.microphone?.apply(settings) + server.refresh() + server.scheduleTree(structure = false) + } + levels.apply() + } catch (e: RuntimeException) { + error(e.message ?: "Microphone unavailable") + } + } + + /** Microphone preset and playback usage; the open lines move over at once. */ + fun setRoute(route: AudioRoute) { + routePrefs.save(route) + _route.value = route + audio.setRoute(route) + } + + /** Listens to the microphone for the level meter while [on]. */ + fun watchLevel(on: Boolean) { + watchingLevel = on + updateLevels() + } + + private fun updateLevels() { + val owner = _micOwner.value + levels.update(watchingLevel, owner?.microphone, owner?.isBusy == true, hasMicPermission()) + } + + // ---- notifications ---- + + /** Shows a private chat a notification was tapped for. */ + fun requestChat(serverId: Int, clientId: Int) { + val server = server(serverId) ?: return + _current.value = server + server.requestChat(clientId) + } + + /** Answers a private message from its notification. */ + fun reply(serverId: Int, clientId: Int, text: String) { + server(serverId)?.reply(clientId, text) ?: notifier.clear(serverId, clientId) + } + + companion object { + const val DEFAULT_PORT = 9987 + private const val OVERLAY_ENABLED = "enabled" + + /** `host[:port]` as typed, the port defaulting to TeamSpeak's. */ + fun parseAddress(address: String): Pair { + val host = address.substringBefore(':').trim() + val port = address.substringAfter(':', "").trim().toIntOrNull() ?: DEFAULT_PORT + return host to port + } + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/SoundPackInstaller.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/SoundPackInstaller.kt new file mode 100644 index 0000000..6a70783 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/SoundPackInstaller.kt @@ -0,0 +1,53 @@ +package eu.lixko.ts3j.client.android + +import android.content.Context +import android.content.res.AssetManager +import eu.lixko.ts3j.client.config.AppDirs +import java.io.File + +/** + * Unpacks the sound packs bundled in the APK into the profile's `sound` folder, where + * [eu.lixko.ts3j.client.sound.SoundNotifier] finds packs, as they are read as plain files. + * It happens once per installed version of the app; packs of other origins in the + * folder are left alone. + */ +class SoundPackInstaller(private val context: Context) { + + private val root = File(AppDirs.profile(), ASSET_DIR) + private val marker = File(root, ".bundled") + /** Where a pack is unpacked first, outside [root] so it is never seen half written. */ + private val staging = File(AppDirs.profile(), ".sound-staging") + + /** @return whether the packs were (re)installed, so the list of them has to be read again */ + fun install(): Boolean { + val version = context.packageManager.getPackageInfo(context.packageName, 0).lastUpdateTime.toString() + if (marker.isFile && marker.readText() == version) return false + val assets = context.assets + for (pack in assets.list(ASSET_DIR).orEmpty()) { + staging.deleteRecursively() + copy(assets, "$ASSET_DIR/$pack", staging) + val target = File(root, pack) + target.deleteRecursively() + root.mkdirs() + check(staging.renameTo(target)) { "Cannot install sound pack $pack" } + } + root.mkdirs() + marker.writeText(version) + return true + } + + private fun copy(assets: AssetManager, path: String, to: File) { + val children = assets.list(path).orEmpty() + if (children.isEmpty()) { + to.parentFile?.mkdirs() + assets.open(path).use { input -> to.outputStream().use { input.copyTo(it) } } + return + } + to.mkdirs() + for (child in children) copy(assets, "$path/$child", File(to, child)) + } + + private companion object { + const val ASSET_DIR = "sound" + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/SpeakingSoundPlayer.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/SpeakingSoundPlayer.kt new file mode 100644 index 0000000..d03f898 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/SpeakingSoundPlayer.kt @@ -0,0 +1,31 @@ +package eu.lixko.ts3j.client.android + +import android.content.Context +import android.os.Bundle +import android.speech.tts.TextToSpeech +import eu.lixko.ts3j.client.sound.SoundPlayer + +/** + * Adds the phone's text-to-speech to a wave player, for packs that speak their + * notifications. Sentences asked for before the engine is up are dropped: they + * would come out late, past what they announce. + */ +class SpeakingSoundPlayer(context: Context, private val waves: SoundPlayer) : SoundPlayer by waves { + + @Volatile + private var ready = false + private val tts = TextToSpeech(context.applicationContext) { status -> ready = status == TextToSpeech.SUCCESS } + + override fun canSpeak() = true + + override fun say(text: String, volume: Double) { + if (!ready) return + val params = Bundle().apply { putFloat(TextToSpeech.Engine.KEY_PARAM_VOLUME, volume.toFloat()) } + tts.speak(text, TextToSpeech.QUEUE_ADD, params, null) + } + + override fun shutdown() { + tts.shutdown() + waves.shutdown() + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/Ts3Application.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/Ts3Application.kt new file mode 100644 index 0000000..ba7912c --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/Ts3Application.kt @@ -0,0 +1,18 @@ +package eu.lixko.ts3j.client.android + +import android.app.Application +import eu.lixko.ts3j.client.config.AppDirs + +class Ts3Application : Application() { + + lateinit var sessions: SessionController + private set + + override fun onCreate() { + super.onCreate() + // Before any store loads: there is no home directory to find them in. + AppDirs.init(filesDir, filesDir.toPath().resolve("chats")) + sessions = SessionController(this) + Thread(sessions::installSoundPacks, "sound-packs").start() + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/WebPictures.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/WebPictures.kt new file mode 100644 index 0000000..14101dc --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/WebPictures.kt @@ -0,0 +1,64 @@ +package eu.lixko.ts3j.client.android + +import android.util.LruCache +import eu.lixko.ts3j.client.config.Settings +import eu.lixko.ts3j.client.net.PictureDownloads +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.withContext +import java.io.File +import java.util.concurrent.ConcurrentHashMap + +/** The pictures descriptions show, fetched by core's downloads and decoded while there is room. */ +class WebPictures(cacheDir: File, private val settings: Settings) { + + sealed interface State { + data object Loading : State + data object Broken : State + data class Shown(val picture: Picture) : State + } + + private val downloads = PictureDownloads(File(cacheDir, "pictures"), false) + private val decoded = LruCache(CACHED) + private val undecodable = ConcurrentHashMap.newKeySet() + + private val _version = MutableStateFlow(0) + /** Moves on whenever a download has come or failed. */ + val version: StateFlow = _version + + init { + downloads.addListener { _version.update { it + 1 } } + } + + /** Fetches pictures whose addresses start with [scheme] from [source] rather than the web. */ + fun addSource(scheme: String, source: PictureDownloads.Source) = downloads.addSource(scheme, source) + + /** Asks again for the pictures that could not be had. */ + fun retryFailed() = downloads.retryFailed() + + /** Whether pictures are shown at all, rather than links to them. */ + val enabled: Boolean get() = settings.descriptionPictures + + suspend fun state(url: String): State { + decoded.get(url)?.let { return State.Shown(it) } + if (url in undecodable) return State.Broken + val file = downloads.get(url) ?: return if (downloads.failed(url)) State.Broken else State.Loading + val picture = withContext(Dispatchers.IO) { decodePicture(file.readBytes(), MAX_PX) } + if (picture == null) { + undecodable += url + return State.Broken + } + decoded.put(url, picture) + return State.Shown(picture) + } + + /** The picture's file as downloaded; null while it is not there. */ + suspend fun data(url: String): ByteArray? = withContext(Dispatchers.IO) { downloads.get(url)?.readBytes() } + + private companion object { + const val CACHED = 32 + const val MAX_PX = 1024 + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/App.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/App.kt new file mode 100644 index 0000000..696c5c0 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/App.kt @@ -0,0 +1,115 @@ +package eu.lixko.ts3j.client.android.ui + +import android.Manifest +import android.content.pm.PackageManager +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.saveable.rememberSaveableStateHolder +import androidx.compose.runtime.setValue +import androidx.compose.ui.platform.LocalContext +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import eu.lixko.ts3j.client.android.SessionController +import eu.lixko.ts3j.client.android.SessionEvent + +@Composable +fun App(vm: SessionController) { + val current by vm.current.collectAsStateWithLifecycle() + // Each server keeps its own screen state (chat open, conversation) while another is shown. + val serverStates = rememberSaveableStateHolder() + var connectOpen by rememberSaveable { mutableStateOf(false) } + val snackbar = remember { SnackbarHostState() } + var settingsOpen by rememberSaveable { mutableStateOf(false) } + var contactsOpen by rememberSaveable { mutableStateOf(false) } + var editingContact by rememberSaveable { mutableStateOf(null) } + // Set when a contact's page was opened from a client, so leaving it goes back there. + var contactDirect by rememberSaveable { mutableStateOf(false) } + var editingBookmark by rememberSaveable(stateSaver = BookmarkEditSaver) { mutableStateOf(null) } + var poke by remember { mutableStateOf(null) } + + LaunchedEffect(vm) { + vm.events.collect { event -> + when (event) { + is SessionEvent.Poke -> poke = event + is SessionEvent.Error -> snackbar.showSnackbar(event.message) + SessionEvent.ServerOpened -> { + connectOpen = false + settingsOpen = false + contactsOpen = false + editingBookmark = null + } + } + } + } + + val context = LocalContext.current + val permissions = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { granted -> + if (granted[Manifest.permission.RECORD_AUDIO] == true) vm.current.value?.let(vm::giveMicrophoneTo) + } + fun missing(vararg names: String) = + names.filter { context.checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED } + + // The connection runs without either permission, just silent or without its notification. + val connectAsking: (() -> Unit) -> Unit = { connect -> + connect() + connectOpen = false + val ask = missing(Manifest.permission.RECORD_AUDIO, Manifest.permission.POST_NOTIFICATIONS) + if (ask.isNotEmpty()) permissions.launch(ask.toTypedArray()) + } + val enableMicrophone: () -> Unit = { + if (missing(Manifest.permission.RECORD_AUDIO).isEmpty()) vm.current.value?.let(vm::giveMicrophoneTo) + else permissions.launch(arrayOf(Manifest.permission.RECORD_AUDIO)) + } + + val openContacts: (String?) -> Unit = { uniqueId -> + contactsOpen = true + editingContact = uniqueId + contactDirect = uniqueId != null + } + + CompositionLocalProvider(LocalIconTheme provides vm.icons, LocalWebPictures provides vm.pictures) { + val server = current + val bookmark = editingBookmark + when { + bookmark != null -> BookmarkScreen(vm, bookmark, onDone = { editingBookmark = null }) + contactsOpen -> ContactsScreen(vm, editingContact, onEdit = { uniqueId -> + if (uniqueId == null && contactDirect) contactsOpen = false + contactDirect = false + editingContact = uniqueId + }, onBack = { contactsOpen = false }) + settingsOpen -> SettingsScreen(vm, onContacts = { openContacts(null) }, onBack = { settingsOpen = false }) + server != null && !connectOpen -> { + serverStates.SaveableStateProvider(server.id) { + CompositionLocalProvider(LocalServerImages provides server.images) { + PictureViewerHost(server) { + ServerScreen(vm, server, snackbar, { settingsOpen = true }, openContacts, enableMicrophone, + onConnectOther = { connectOpen = true }, onEditBookmark = { editingBookmark = it }) + } + } + } + } + else -> ConnectScreen(vm, snackbar, { settingsOpen = true }, connectAsking, + onEditBookmark = { editingBookmark = it }, + onBack = if (current != null) ({ connectOpen = false }) else null) + } + } + + poke?.let { p -> + AlertDialog( + onDismissRequest = { poke = null }, + title = { Text("${p.from} poked you") }, + text = if (p.message.isNotBlank()) ({ Text(p.message) }) else null, + confirmButton = { TextButton(onClick = { poke = null }) { Text("OK") } }, + ) + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Attachments.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Attachments.kt new file mode 100644 index 0000000..a4f08e7 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Attachments.kt @@ -0,0 +1,102 @@ +package eu.lixko.ts3j.client.android.ui + +import android.app.Activity +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.webkit.MimeTypeMap +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContract +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.material3.SnackbarHostState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import eu.lixko.ts3j.client.android.ChatKey +import eu.lixko.ts3j.client.android.ServerController +import eu.lixko.ts3j.client.android.SessionController +import eu.lixko.ts3j.client.myts.ChatAttachment +import eu.lixko.ts3j.client.myts.MyTsException +import kotlinx.coroutines.launch +import java.io.IOException + +/** What the chat does with shared files: [open] one it links to, [share] one into a conversation. */ +class AttachmentActions(val open: (String) -> Unit, val share: () -> Unit) + +/** + * Shared files for [server]'s chat: a picture opens full size, anything else is saved where + * the user picks; sharing picks a file to send into the conversation [shown] gives. + */ +@Composable +fun rememberAttachmentActions( + vm: SessionController, + server: ServerController, + snackbar: SnackbarHostState, + shown: ChatKey, +): AttachmentActions { + val scope = rememberCoroutineScope() + val signedIn by vm.myTeamSpeakSignedIn.collectAsStateWithLifecycle() + val key by rememberUpdatedState(shown) + val viewer = LocalPictureViewer.current + val tell = { message: String -> scope.launch { snackbar.showSnackbar(message) }; Unit } + + var saving by rememberSaveable { mutableStateOf(null) } + val saver = rememberLauncherForActivityResult(SaveAs) { uri -> + val ref = ChatAttachment.Ref.parse(saving) + saving = null + if (uri == null || ref == null) return@rememberLauncherForActivityResult + scope.launch { + val error = try { + vm.saveAttachment(ref, uri) + null + } catch (e: MyTsException) { + e.message + } catch (e: IOException) { + e.message + } + snackbar.showSnackbar(if (error == null) "Saved ${ref.fileName}." else "Could not save ${ref.fileName}: $error") + } + } + val picker = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri -> + if (uri != null) scope.launch { server.sendFile(key, uri) } + } + + return AttachmentActions( + open = open@{ href -> + val ref = ChatAttachment.Ref.parse(href) ?: return@open + when { + !signedIn -> tell(SIGN_IN) + ref.isImage() && viewer != null -> viewer(ViewedPicture(ref.fileName.substringBeforeLast('.')) { + vm.pictures.data(href) ?: runCatching { vm.downloadAttachment(ref) }.getOrNull() + }) + else -> { + saving = href + saver.launch(ref.fileName) + } + } + }, + share = { if (signedIn) picker.launch("*/*") else tell(SIGN_IN) }, + ) +} + +private const val SIGN_IN = "Sign in to myTeamSpeak to share files" + +/** Asks where to save a file of the given name, typed by its extension. */ +internal object SaveAs : ActivityResultContract() { + override fun createIntent(context: Context, input: String): Intent { + val extension = input.substringAfterLast('.', "").lowercase() + val type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) ?: "application/octet-stream" + return Intent(Intent.ACTION_CREATE_DOCUMENT) + .addCategory(Intent.CATEGORY_OPENABLE) + .setType(type) + .putExtra(Intent.EXTRA_TITLE, input) + } + + override fun parseResult(resultCode: Int, intent: Intent?): Uri? = + intent?.data.takeIf { resultCode == Activity.RESULT_OK } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/BanListScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/BanListScreen.kt new file mode 100644 index 0000000..d5ee3a1 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/BanListScreen.kt @@ -0,0 +1,313 @@ +package eu.lixko.ts3j.client.android.ui + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ArrowDropDown +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilterChip +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import eu.lixko.ts3j.client.android.ServerController +import eu.lixko.ts3j.client.config.BanReasonPresets +import eu.lixko.ts3j.client.net.ban.BanEntry +import eu.lixko.ts3j.client.net.ban.BanPattern +import eu.lixko.ts3j.client.net.ban.BanRule +import kotlinx.coroutines.launch +import java.time.Instant +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.time.format.FormatStyle +import java.util.Locale + +/** What the ban list shows instead of itself: a ban's editor, a new or an existing ban's. */ +private sealed interface BanEdit { + data object New : BanEdit + data class Existing(val ban: BanEntry) : BanEdit +} + +/** The server's ban list, as TeamSpeak's Ban List window: searchable, own bans apart, add, edit and remove. */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun BanListScreen(server: ServerController, presets: BanReasonPresets, onBack: () -> Unit) { + val scope = rememberCoroutineScope() + val snackbar = remember { SnackbarHostState() } + var bans by remember { mutableStateOf?>(null) } + var status by remember { mutableStateOf("Loading…") } + /** Bumped to read the list again. */ + var generation by remember { mutableIntStateOf(0) } + var query by rememberSaveable { mutableStateOf("") } + var onlyOwn by rememberSaveable { mutableStateOf(false) } + var shown by remember { mutableStateOf(null) } + var edit by remember { mutableStateOf(null) } + + LaunchedEffect(generation) { + status = "Loading…" + server.banList() + .onSuccess { + bans = it + status = if (it.size == 1) "1 ban" else "${it.size} bans" + } + .onFailure { + bans = emptyList() + status = "Failed to request ban list: ${it.message}" + } + } + + /** Reports a failed change, or re-reads the list to show what the server now holds. */ + val change = { action: suspend () -> String?, failure: String -> + scope.launch { + val error = action() + if (error != null) snackbar.showSnackbar("$failure: $error") + generation++ + } + Unit + } + + edit?.let { e -> + val existing = (e as? BanEdit.Existing)?.ban + BanEditor(existing, presets, server.maxBanSeconds, onBack = { edit = null }) { rule -> + edit = null + if (existing == null) change({ server.addBan(rule) }, "Error adding ban") + else change({ server.replaceBan(existing.id, rule) }, "Error editing ban") + } + return + } + + SubScreen( + "Ban list", onBack, + actions = { + if (server.canCreateBans) IconButton(onClick = { edit = BanEdit.New }) { PackIcon("ADD", "Add") } + IconButton(onClick = { generation++ }) { PackIcon("REFRESH", "Reload") } + }, + snackbar = snackbar, + ) { padding -> + val needle = query.trim().lowercase(Locale.ROOT) + val filtered = remember(bans, needle, onlyOwn) { + bans.orEmpty().filter { ban -> + (!onlyOwn || server.isOwnBan(ban)) && (needle.isEmpty() || searchText(ban).contains(needle)) + } + } + Column(Modifier.padding(padding).imePadding().fillMaxSize()) { + Row(Modifier.padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField(query, { query = it }, Modifier.weight(1f), placeholder = { Text("Search") }, + singleLine = true, leadingIcon = { PackIcon("SEARCH", null) }) + FilterChip(onlyOwn, { onlyOwn = !onlyOwn }, label = { Text("Own") }) + } + Text(status, Modifier.padding(horizontal = 16.dp, vertical = 8.dp), + style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + LazyColumn(Modifier.weight(1f)) { + items(filtered, key = { it.id }) { ban -> + ListItem( + headlineContent = { Text(ban.targets(), maxLines = 2, overflow = TextOverflow.Ellipsis) }, + supportingContent = { + Column { + if (ban.reason.isNotEmpty()) Text(ban.reason, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text("${ban.invokerName} · ${expiry(ban)}", style = MaterialTheme.typography.bodySmall) + } + }, + modifier = Modifier.clickable { shown = ban }, + ) + HorizontalDivider() + } + } + } + } + + shown?.let { ban -> + BanSheet( + ban, + onDismiss = { shown = null }, + onEdit = if (server.canEditBan(ban)) ({ shown = null; edit = BanEdit.Existing(ban) }) else null, + onDelete = if (server.canDeleteBans(listOf(ban))) ({ + shown = null + change({ server.deleteBans(listOf(ban.id)) }, "Error deleting ban") + }) else null, + ) + } +} + +private fun searchText(ban: BanEntry): String = + listOf(ban.targets(), ban.reason, ban.invokerName, date(ban.createdEpochSeconds), expiry(ban)) + .joinToString("\n").lowercase(Locale.ROOT) + +private val DATE: DateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) + +private fun date(epochSeconds: Long): String = + if (epochSeconds <= 0) "" else DATE.format(Instant.ofEpochSecond(epochSeconds).atZone(ZoneId.systemDefault())) + +private fun expiry(ban: BanEntry): String = if (ban.isPermanent) "Never expires" else "Expires ${date(ban.expiresEpochSeconds())}" + +/** Everything about one ban, and what may be done with it. */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun BanSheet(ban: BanEntry, onDismiss: () -> Unit, onEdit: (() -> Unit)?, onDelete: (() -> Unit)?) { + var confirmDelete by remember { mutableStateOf(false) } + ModalBottomSheet(onDismissRequest = onDismiss) { + Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) { + Column(Modifier.padding(horizontal = 24.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Fact("Name", ban.name) + Fact("IP", ban.ip) + Fact("Unique ID", ban.uid) + Fact("Last nickname", ban.lastNickname) + Fact("myTeamSpeak ID", ban.mytsid) + Fact("Reason", ban.reason) + Fact("Creator", ban.invokerName) + Fact("Created", date(ban.createdEpochSeconds)) + Fact("Expires", if (ban.isPermanent) "Never" else date(ban.expiresEpochSeconds())) + Fact("Enforced", ban.enforcements.toString()) + } + onEdit?.let { Action("EDIT", "Edit", onClick = it) } + onDelete?.let { Action("DELETE", "Delete") { confirmDelete = true } } + } + } + if (confirmDelete && onDelete != null) { + AlertDialog( + onDismissRequest = { confirmDelete = false }, + title = { Text("Delete ban?") }, + text = { Text(ban.targets()) }, + confirmButton = { TextButton(onClick = { confirmDelete = false; onDelete() }) { Text("Delete") } }, + dismissButton = { TextButton(onClick = { confirmDelete = false }) { Text("Cancel") } }, + ) + } +} + +@Composable +private fun Fact(label: String, value: String) { + if (value.isEmpty()) return + Column { + Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(value, style = MaterialTheme.typography.bodyMedium) + } +} + +/** Adds a ban, or rewrites [existing]: what it matches, why, and for how long. */ +@Composable +private fun BanEditor( + existing: BanEntry?, + presets: BanReasonPresets, + maxSeconds: Long, + onBack: () -> Unit, + onSave: (BanRule) -> Unit, +) { + val decoded = remember { BanPattern.decode(existing?.ip, existing?.name) } + var ip by remember { mutableStateOf(decoded.ip) } + var name by remember { mutableStateOf(decoded.name) } + var pattern by remember { mutableStateOf(if (existing == null) BanPattern.WILDCARD_IPV4 else decoded.pattern) } + var uid by remember { mutableStateOf(existing?.uid.orEmpty()) } + var mytsid by remember { mutableStateOf(existing?.mytsid.orEmpty()) } + var reason by remember { mutableStateOf(existing?.reason.orEmpty()) } + val duration = remember { BanDurationState(existing?.durationSeconds ?: DEFAULT_BAN_SECONDS) } + + val rule = BanRule(pattern.ipToRegex(ip), pattern.nameToRegex(name), uid, mytsid, duration.seconds, reason) + val ipValid = BanPattern.isValidRegex(rule.ipRegex) + val nameValid = BanPattern.isValidRegex(rule.nameRegex) + val valid = rule.hasTarget() && ipValid && nameValid && duration.valid + + SubScreen( + if (existing == null) "Add ban" else "Edit ban", onBack, + actions = { TextButton(onClick = { onSave(rule) }, enabled = valid) { Text("Save") } }, + ) { padding -> + Column( + Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + OutlinedTextField(ip, { ip = it }, Modifier.fillMaxWidth(), label = { Text("IP") }, singleLine = true, + isError = !ipValid) + OutlinedTextField(name, { name = it }, Modifier.fillMaxWidth(), label = { Text("Name") }, singleLine = true, + isError = !nameValid) + PatternField(pattern) { pattern = it } + OutlinedTextField(uid, { uid = it }, Modifier.fillMaxWidth(), label = { Text("Unique ID") }, singleLine = true) + OutlinedTextField(mytsid, { mytsid = it }, Modifier.fillMaxWidth(), label = { Text("myTeamSpeak ID") }, + singleLine = true) + ReasonField(reason, { reason = it }, presets) + BanDurationField(duration, maxSeconds) + } + } +} + +/** How the IP and name are written: wildcards, fixed strings or regular expressions. */ +@Composable +private fun PatternField(pattern: BanPattern, onSelect: (BanPattern) -> Unit) { + var open by remember { mutableStateOf(false) } + Row(verticalAlignment = Alignment.CenterVertically) { + Text("Interpret as", Modifier.weight(1f)) + Box { + OutlinedButton(onClick = { open = true }) { Text(pattern.label()) } + DropdownMenu(open, { open = false }) { + for (p in BanPattern.entries) DropdownMenuItem({ Text(p.label()) }, onClick = { open = false; onSelect(p) }) + } + } + } +} + +/** The reason, with the saved presets to pick from and the reason typed to save as one. */ +@Composable +private fun ReasonField(reason: String, onChange: (String) -> Unit, presets: BanReasonPresets) { + var open by remember { mutableStateOf(false) } + var saved by remember { mutableStateOf(presets.all().toList()) } + Box { + Row(verticalAlignment = Alignment.Top) { + LimitedField(reason, onChange, "Reason", BanRule.REASON_LIMIT, Modifier.weight(1f)) + IconButton(onClick = { open = true }, Modifier.padding(top = 8.dp)) { Icon(Icons.Filled.ArrowDropDown, "Presets") } + } + DropdownMenu(open, { open = false }, Modifier.align(Alignment.TopEnd)) { + for (preset in saved) { + DropdownMenuItem({ Text(preset, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + onClick = { open = false; onChange(preset.take(BanRule.REASON_LIMIT)) }, + trailingIcon = { + IconButton(onClick = { + presets.remove(preset) + presets.save() + saved = presets.all().toList() + }) { PackIcon("DELETE", "Remove preset") } + }) + } + if (saved.isNotEmpty()) HorizontalDivider() + DropdownMenuItem({ Text("Save as preset") }, enabled = reason.isNotBlank(), onClick = { + open = false + presets.add(reason) + presets.save() + saved = presets.all().toList() + }) + } + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/BookmarkScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/BookmarkScreen.kt new file mode 100644 index 0000000..390e586 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/BookmarkScreen.kt @@ -0,0 +1,152 @@ +package eu.lixko.ts3j.client.android.ui + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.ExposedDropdownMenuAnchorType +import androidx.compose.material3.ExposedDropdownMenuBox +import androidx.compose.material3.ExposedDropdownMenuDefaults +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.listSaver +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import eu.lixko.ts3j.client.android.SessionController +import eu.lixko.ts3j.client.config.Bookmark + +/** A bookmark on the edit page: [index] among the saved ones, -1 for a new one. */ +class BookmarkEdit(val index: Int, val bookmark: Bookmark) + +val BookmarkEditSaver = listSaver( + save = { edit -> + val b = edit?.bookmark ?: return@listSaver emptyList() + listOf(edit.index, b.label.orEmpty(), b.address.orEmpty(), b.port, b.nickname.orEmpty(), b.password, + b.identityId, b.channel, b.channelPassword, b.connectOnStartup, b.iconId, b.id) + }, + restore = { saved -> + if (saved.isEmpty()) null + else BookmarkEdit(saved[0] as Int, Bookmark(saved[1] as String, saved[2] as String, saved[3] as Int, + saved[4] as String, saved[5] as String).apply { + identityId = saved[6] as String + channel = saved[7] as String + channelPassword = saved[8] as String + connectOnStartup = saved[9] as Boolean + iconId = saved[10] as Long + id = saved[11] as String + }) + }, +) + +/** Every setting of one bookmark, saved only on Save. */ +@Composable +fun BookmarkScreen(vm: SessionController, edit: BookmarkEdit, onDone: () -> Unit) { + val b = edit.bookmark + val identities by vm.identities.all.collectAsStateWithLifecycle() + var label by rememberSaveable { mutableStateOf(b.label.orEmpty()) } + var address by rememberSaveable { + mutableStateOf(if (b.port == SessionController.DEFAULT_PORT) b.address.orEmpty() else "${b.address}:${b.port}") + } + var nickname by rememberSaveable { mutableStateOf(b.nickname.orEmpty()) } + var password by rememberSaveable { mutableStateOf(b.password.orEmpty()) } + var identityId by rememberSaveable { mutableStateOf(b.identityId.orEmpty()) } + var channel by rememberSaveable { mutableStateOf(b.channel.orEmpty()) } + var channelPassword by rememberSaveable { mutableStateOf(b.channelPassword.orEmpty()) } + var connectOnStartup by rememberSaveable { mutableStateOf(b.connectOnStartup) } + + val save = { + val (host, port) = SessionController.parseAddress(address) + vm.saveBookmark(edit.index, b.copy().also { + it.label = label.trim().ifEmpty { host } + it.address = host + it.port = port + it.nickname = nickname.trim() + it.password = password + it.identityId = identityId + it.channel = channel.trim() + it.channelPassword = channelPassword + it.connectOnStartup = connectOnStartup + }) + onDone() + } + + SubScreen(if (edit.index < 0) "New bookmark" else "Edit bookmark", onBack = onDone, actions = { + TextButton(onClick = save, enabled = address.isNotBlank()) { Text("Save") } + }) { padding -> + Column( + Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + OutlinedTextField(label, { label = it }, Modifier.fillMaxWidth(), label = { Text("Name") }, singleLine = true) + OutlinedTextField(address, { address = it }, Modifier.fillMaxWidth(), label = { Text("Server address") }, + singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri)) + OutlinedTextField(password, { password = it }, Modifier.fillMaxWidth(), + label = { Text("Server password") }, singleLine = true, + visualTransformation = PasswordVisualTransformation(), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)) + IdentityField(identities, identityId) { identityId = it } + OutlinedTextField(nickname, { nickname = it }, Modifier.fillMaxWidth(), label = { Text("Nickname") }, + placeholder = { Text(vm.nicknameFor(identityId)) }, singleLine = true) + val paths = remember(address) { + SessionController.parseAddress(address).let { (host, port) -> vm.channelPathsAt(host, port) } + } + ChannelField(channel, paths) { channel = it } + OutlinedTextField(channelPassword, { channelPassword = it }, Modifier.fillMaxWidth(), + label = { Text("Channel password") }, singleLine = true, + visualTransformation = PasswordVisualTransformation(), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)) + Row(Modifier.fillMaxWidth().clickable { connectOnStartup = !connectOnStartup }, + verticalAlignment = Alignment.CenterVertically) { + Text("Connect on startup", Modifier.weight(1f)) + Switch(connectOnStartup, { connectOnStartup = it }) + } + } + } +} + +/** The channel to join, typed or picked among [paths] of the server when we are on it. */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun ChannelField(channel: String, paths: List, onChange: (String) -> Unit) { + var open by remember { mutableStateOf(false) } + // A channel already picked lists them all, for picking another. + val matches = if (channel in paths) paths else paths.filter { it.contains(channel.trim(), ignoreCase = true) } + val expanded = open && matches.isNotEmpty() + ExposedDropdownMenuBox(expanded, { open = it }) { + OutlinedTextField( + channel, { onChange(it); open = true }, singleLine = true, + label = { Text("Channel") }, + placeholder = { Text("Default") }, + trailingIcon = if (paths.isEmpty()) null else ({ ExposedDropdownMenuDefaults.TrailingIcon(expanded) }), + modifier = Modifier.fillMaxWidth().menuAnchor(ExposedDropdownMenuAnchorType.PrimaryEditable), + ) + ExposedDropdownMenu(expanded, { open = false }) { + for (path in matches) { + DropdownMenuItem({ Text(path) }, onClick = { + open = false + onChange(path) + }) + } + } + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChannelEditScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChannelEditScreen.kt new file mode 100644 index 0000000..8fbb3b5 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChannelEditScreen.kt @@ -0,0 +1,211 @@ +package eu.lixko.ts3j.client.android.ui + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.unit.dp +import eu.lixko.ts3j.client.android.ServerController +import eu.lixko.ts3j.client.net.ChannelCodec +import eu.lixko.ts3j.client.net.ChannelSettings +import kotlinx.coroutines.launch +import kotlin.math.roundToInt + +/** The channel being edited ([channelId] > 0), or one to create below [parentId] (0: the top level). */ +data class ChannelEdit(val channelId: Int, val parentId: Int = 0) + +/** + * TeamSpeak's channel editor on one page: name, password, topic and description, then the + * channel's type, sorting, audio and limits. Only what changed is sent, as the server refuses + * an edit carrying one property we may not change. + */ +@Composable +fun ChannelEditScreen(server: ServerController, edit: ChannelEdit, onDone: () -> Unit) { + val creating = edit.channelId <= 0 + val snackbar = remember { SnackbarHostState() } + val scope = rememberCoroutineScope() + /** The channel as the server described it, which changes are measured against. */ + var original by remember { mutableStateOf(null) } + var edited by remember { mutableStateOf(null) } + var passwordText by remember { mutableStateOf("") } + var saving by remember { mutableStateOf(false) } + + LaunchedEffect(edit) { + if (creating) { + // Made from a channel's sheet, a channel is usually a throwaway one, as in TeamSpeak; + // the server puts a new channel after its siblings. + val fresh = ChannelSettings().apply { + type = ChannelSettings.Type.TEMPORARY + parentId = edit.parentId + order = server.sortChoices(0, edit.parentId).lastOrNull()?.id ?: 0 + } + original = fresh + edited = fresh.copy() + } else { + server.channelSettings(edit.channelId) + .onSuccess { original = it; edited = it.copy() } + .onFailure { snackbar.showSnackbar("Could not read the channel: ${it.message}"); onDone() } + } + } + + val change = { f: ChannelSettings.() -> Unit -> edited = edited?.copy()?.apply(f) } + val save = save@{ + val e = edited ?: return@save + val o = original ?: return@save + if (e.name.isBlank()) { + scope.launch { snackbar.showSnackbar("The channel needs a name.") } + return@save + } + saving = true + scope.launch { + val trimmed = e.copy().apply { name = name.trim() } + val error = if (creating) server.createChannel(edit.parentId, trimmed) + else server.editChannel(edit.channelId, trimmed.changesFrom(o)) + saving = false + if (error == null) onDone() + else snackbar.showSnackbar((if (creating) "Could not create the channel: " else "Could not save the channel: ") + error) + } + } + + val title = when { + !creating -> "Edit channel" + edit.parentId > 0 -> "New sub-channel" + else -> "New channel" + } + SubScreen(title, onBack = onDone, snackbar = snackbar, actions = { + TextButton(onClick = save, enabled = edited != null && !saving) { Text(if (creating) "Create" else "Save") } + }) { padding -> + val e = edited + if (e == null) { + Box(Modifier.padding(padding).fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() } + return@SubScreen + } + Column(Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) { + Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField(e.name, { change { name = it } }, Modifier.fillMaxWidth(), label = { Text("Name") }, + singleLine = true) + OutlinedTextField(passwordText, { + passwordText = it + change { password = it } + }, Modifier.fillMaxWidth(), label = { Text("Password") }, singleLine = true, + placeholder = if (e.hasPassword && e.password == null) ({ Text("Unchanged") }) else null, + visualTransformation = PasswordVisualTransformation(), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)) + if (e.hasPassword && e.password == null) { + TextButton(onClick = { change { password = "" } }) { Text("Remove password") } + } + OutlinedTextField(e.topic, { change { topic = it } }, Modifier.fillMaxWidth(), label = { Text("Topic") }, + singleLine = true) + OutlinedTextField(e.description, { change { description = it } }, Modifier.fillMaxWidth(), + label = { Text("Description") }, minLines = 3, maxLines = 10) + } + + Section("Channel type") + Segments(listOf( + ChannelSettings.Type.TEMPORARY to "Temporary", + ChannelSettings.Type.SEMI_PERMANENT to "Semi-permanent", + ChannelSettings.Type.PERMANENT to "Permanent", + ), e.type) { change { type = it } } + // The default channel cannot stop being one; another has to take over. + if (original?.defaultChannel != true) { + Toggle("Default channel", e.defaultChannel) { change { defaultChannel = it } } + } + val siblings = remember(edit) { + server.sortChoices(edit.channelId, edit.parentId).filter { it.id != edit.channelId } + } + Picker("Sort after", listOf(0 to "(first)") + siblings.map { it.id to it.name }, + e.order.takeIf { o -> o == 0 || siblings.any { it.id == o } } ?: 0) { change { order = it } } + NumberField("Needed talk power", e.neededTalkPower, 0..9999) { change { neededTalkPower = it } } + + Section("Audio") + val preset = ChannelCodec.Preset.of(e.codec, e.codecQuality) + var custom by remember { mutableStateOf(preset == null) } + val presets: List> = + ChannelCodec.Preset.entries.map { it to it.label } + (null to "Custom") + Segments(presets, if (custom) null else preset) { picked -> + custom = picked == null + if (picked != null) change { codec = picked.codec; codecQuality = picked.quality } + } + if (custom) { + Picker("Codec", ChannelCodec.NAMES.indices.map { it to ChannelCodec.NAMES[it] }, + ChannelCodec.clampCodec(e.codec)) { change { codec = it } } + Level("Quality", e.codecQuality.toFloat(), 0f..ChannelCodec.MAX_QUALITY.toFloat(), + { it.roundToInt().toString() }, steps = ChannelCodec.MAX_QUALITY - 1) { + change { codecQuality = it.roundToInt() } + } + } + Hint("Bandwidth: ${ChannelCodec.bandwidthText(e.codec, e.codecQuality)} per talking client") + + Section("Advanced") + Column(Modifier.padding(horizontal = 16.dp)) { + OutlinedTextField(e.phoneticName, { change { phoneticName = it } }, Modifier.fillMaxWidth(), + label = { Text("Phonetic name") }, singleLine = true) + } + if (e.type == ChannelSettings.Type.TEMPORARY) { + NumberField("Delete delay (seconds)", e.deleteDelay, 0..ChannelSettings.MAX_DELETE_DELAY) { + change { deleteDelay = it } + } + } + Toggle("Voice encrypted", e.encrypted) { change { encrypted = it } } + Text("Max users", Modifier.padding(start = 16.dp, top = 8.dp), style = MaterialTheme.typography.bodyLarge) + Segments(listOf(true to "Unlimited", false to "Limited"), e.maxClientsUnlimited) { + change { maxClientsUnlimited = it } + } + if (!e.maxClientsUnlimited) NumberField("Users", e.maxClients, 0..65535) { change { maxClients = it } } + Text("Family max users", Modifier.padding(start = 16.dp, top = 8.dp), style = MaterialTheme.typography.bodyLarge) + val family = when { + e.familyInherited -> FamilyLimit.INHERITED + e.familyUnlimited -> FamilyLimit.UNLIMITED + else -> FamilyLimit.LIMITED + } + Segments(FamilyLimit.entries.map { it to it.label }, family) { + change { + familyInherited = it == FamilyLimit.INHERITED + familyUnlimited = it == FamilyLimit.UNLIMITED + } + } + if (family == FamilyLimit.LIMITED) { + NumberField("Users", e.maxFamilyClients, 0..65535) { change { maxFamilyClients = it } } + } + } + } +} + +private enum class FamilyLimit(val label: String) { INHERITED("Inherited"), UNLIMITED("Unlimited"), LIMITED("Limited") } + +/** A whole number within [range]; what does not parse leaves the value alone. */ +@Composable +private fun NumberField(label: String, value: Int, range: IntRange, onChange: (Int) -> Unit) { + var text by remember(value) { mutableStateOf(value.toString()) } + Row(Modifier.padding(horizontal = 16.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) { + OutlinedTextField(text, { + text = it.filter(Char::isDigit).take(7) + text.toIntOrNull()?.let { n -> onChange(n.coerceIn(range)) } + }, Modifier.fillMaxWidth(), label = { Text(label) }, singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)) + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChannelTree.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChannelTree.kt new file mode 100644 index 0000000..538746e --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChannelTree.kt @@ -0,0 +1,349 @@ +package eu.lixko.ts3j.client.android.ui + +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.slideInVertically +import androidx.compose.animation.slideOutVertically +import androidx.compose.foundation.layout.BoxScope +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.Surface +import androidx.compose.runtime.derivedStateOf +import androidx.compose.animation.core.tween +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.KeyboardArrowDown +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ProvideTextStyle +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.rotate +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import eu.lixko.ts3j.client.android.ChannelItem +import eu.lixko.ts3j.client.android.ClientItem +import eu.lixko.ts3j.client.android.ServerTree +import eu.lixko.ts3j.client.contacts.ContactType +import eu.lixko.ts3j.client.gfx.IconKeys +import eu.lixko.ts3j.client.net.ClientStatus +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.first + +/** A channel's or a client's row. */ +data class TreeRef(val channel: Boolean, val id: Int) + +/** One line of the tree as the list shows it. */ +private sealed interface TreeRow { + val ref: TreeRef + val key: String get() = (if (ref.channel) "c" else "u") + ref.id + + data class Channel(val channel: ChannelItem, val depth: Int, val expanded: Boolean, val current: Boolean) : TreeRow { + override val ref get() = TreeRef(true, channel.id) + val expandable get() = channel.clients.isNotEmpty() || channel.children.isNotEmpty() + } + + data class Client(val client: ClientItem, val depth: Int) : TreeRow { + override val ref get() = TreeRef(false, client.id) + } +} + +/** The tree's channels and clients in reading order, leaving out what sits in folded channels. */ +private fun flatten(tree: ServerTree, collapsed: Set, currentChannel: Int): List { + val rows = ArrayList() + fun add(channel: ChannelItem, depth: Int) { + val expanded = channel.id !in collapsed + rows += TreeRow.Channel(channel, depth, expanded, channel.id == currentChannel) + if (!expanded) return + channel.clients.forEach { rows += TreeRow.Client(it, depth + 1) } + channel.children.forEach { add(it, depth + 1) } + } + tree.channels.forEach { add(it, 0) } + return rows +} + +private fun ChannelItem.holdsSelf(): Boolean = clients.any { it.self } || children.any { it.holdsSelf() } + +/** Where the list shows our own client: its row, or the folded channel hiding it; -1 when it shows nowhere. */ +private fun selfAnchor(rows: List): Int = rows.indexOfFirst { row -> + when (row) { + is TreeRow.Client -> row.client.self + is TreeRow.Channel -> !row.expanded && row.channel.holdsSelf() + } +} + +/** Which way our own row lies off screen. */ +private enum class Offscreen { ABOVE, BELOW } + +/** Floats over the tree's edge on the side our own row went off. */ +@Composable +private fun BoxScope.ScrollToSelf(where: Offscreen?, onClick: () -> Unit) { + AnimatedVisibility(where == Offscreen.ABOVE, Modifier.align(Alignment.TopCenter).padding(top = 8.dp), + enter = slideInVertically { -it * 2 } + fadeIn(), exit = slideOutVertically { -it * 2 } + fadeOut()) { + ScrollToSelfChip(up = true, onClick) + } + AnimatedVisibility(where == Offscreen.BELOW, Modifier.align(Alignment.BottomCenter).padding(bottom = 8.dp), + enter = slideInVertically { it * 2 } + fadeIn(), exit = slideOutVertically { it * 2 } + fadeOut()) { + ScrollToSelfChip(up = false, onClick) + } +} + +@Composable +private fun ScrollToSelfChip(up: Boolean, onClick: () -> Unit) { + Surface(onClick = onClick, shape = CircleShape, color = MaterialTheme.colorScheme.secondaryContainer, + shadowElevation = 4.dp) { + Row(Modifier.padding(start = 10.dp, end = 14.dp, top = 6.dp, bottom = 6.dp), + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + Icon(Icons.Filled.KeyboardArrowDown, null, Modifier.size(18.dp).rotate(if (up) 180f else 0f)) + Text("Me", style = MaterialTheme.typography.labelLarge) + } + } +} + +@Composable +fun ChannelTree( + serverName: String, + tree: ServerTree, + collapsed: Set, + currentChannel: Int, + onToggle: (ChannelItem) -> Unit, + onChannel: (ChannelItem) -> Unit, + onChannelDoubleTap: (ChannelItem) -> Unit, + onClient: (ClientItem) -> Unit, + onServer: () -> Unit, + modifier: Modifier = Modifier, + /** A row to scroll to and flash, once the channels above it are expanded. */ + reveal: TreeRef? = null, + onRevealed: () -> Unit = {}, + /** The rows the find bar matched, and the one it is on, which a reveal does not flash. */ + found: Set = emptySet(), + foundCurrent: TreeRef? = null, + listState: LazyListState = rememberLazyListState(), + /** Brings our own client into view; its row may sit in folded channels. */ + onShowSelf: () -> Unit = {}, +) { + val rows = remember(tree, collapsed, currentChannel) { flatten(tree, collapsed, currentChannel) } + var flashing by remember { mutableStateOf(null) } + LaunchedEffect(reveal, rows) { + val ref = reveal ?: return@LaunchedEffect + val index = rows.indexOfFirst { it.ref == ref } + if (index < 0) return@LaunchedEffect + // Index 0 is the server's row. The row ends up in the middle of the list. + val middle = snapshotFlow { listState.layoutInfo.viewportSize.height }.first { it > 0 } / 2 + listState.animateScrollToItem(index + 1, -middle) + if (ref != foundCurrent) flashing = ref + onRevealed() + } + LaunchedEffect(flashing) { + if (flashing != null) { + delay(1500) + flashing = null + } + } + val anchor = remember(rows) { selfAnchor(rows) } + val offscreen by remember(anchor) { + derivedStateOf { + if (anchor < 0) return@derivedStateOf null + val info = listState.layoutInfo + val index = anchor + 1 // past the server's row + val item = info.visibleItemsInfo.firstOrNull { it.index == index } + when { + item != null && item.offset >= info.viewportStartOffset && + item.offset + item.size <= info.viewportEndOffset -> null + item != null -> if (item.offset < info.viewportStartOffset) Offscreen.ABOVE else Offscreen.BELOW + info.visibleItemsInfo.isEmpty() -> null + index < info.visibleItemsInfo.first().index -> Offscreen.ABOVE + else -> Offscreen.BELOW + } + } + } + Box(modifier.fillMaxSize()) { + LazyColumn(Modifier.fillMaxSize(), state = listState, contentPadding = PaddingValues(vertical = 4.dp)) { + item(key = "server") { + RowLayout(depth = 0, onClick = onServer) { + PackIcon("SERVER_GREEN", null, size = ICON) + Text(serverName, Modifier.weight(1f), fontWeight = FontWeight.Bold, maxLines = 1, + overflow = TextOverflow.Ellipsis) + ServerIcon(tree.serverIconId, size = ICON) + } + } + items(rows, key = { it.key }) { row -> + val background = rowBackground( + when (row.ref) { + flashing -> FLASH + foundCurrent -> findCurrentColor() + in found -> findMatchColor() + else -> Color.Transparent + }, + ) + when (row) { + is TreeRow.Channel -> ChannelRow(row, background, onToggle, onChannel, onChannelDoubleTap) + is TreeRow.Client -> ClientRow(row, tree.countryFlags, background, onClient) + } + } + } + ScrollToSelf(offscreen, onShowSelf) + } +} + +private val ICON = 16.dp +private val INDENT = 14.dp +private val ROW = 26.dp +/** Amber, see-through so the row's text keeps its own colour and contrast. */ +private val FLASH = Color(0x80FFB300) + +/** Fades in fast and out slowly, so a flash is seen. */ +@Composable +private fun rowBackground(target: Color): Color { + val color by animateColorAsState(target, tween(if (target == FLASH) 150 else 600), label = "row") + return color +} + +@Composable +private fun RowLayout( + depth: Int, + onClick: (() -> Unit)?, + background: Color = Color.Transparent, + /** The colour under [background], which a flash or find match goes over. */ + tint: Color = Color.Transparent, + onDoubleClick: (() -> Unit)? = null, + content: @Composable RowScope.() -> Unit, +) { + Row( + Modifier + .fillMaxWidth() + .background(tint) + .background(background) + .height(ROW) + .then(if (onClick != null) Modifier.combinedClickable(onDoubleClick = onDoubleClick, onClick = onClick) else Modifier) + .padding(start = 4.dp + INDENT * depth, end = 8.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + ProvideTextStyle(MaterialTheme.typography.bodyMedium, content = { content() }) + } +} + +@Composable +private fun ChannelRow( + row: TreeRow.Channel, + background: Color, + onToggle: (ChannelItem) -> Unit, + onChannel: (ChannelItem) -> Unit, + onDoubleTap: (ChannelItem) -> Unit, +) { + val channel = row.channel + val spacer = channel.spacer + RowLayout(row.depth, onClick = { onChannel(channel) }, background = background, + onDoubleClick = if (spacer == null) ({ onDoubleTap(channel) }) else null) { + Box( + Modifier.fillMaxHeight().width(ICON + 4.dp) + .then(if (row.expandable) Modifier.clickable { onToggle(channel) } else Modifier), + contentAlignment = Alignment.Center, + ) { + if (row.expandable) { + Icon(Icons.Filled.KeyboardArrowDown, if (row.expanded) "Collapse" else "Expand", + Modifier.size(ICON + 2.dp).rotate(if (row.expanded) 0f else -90f)) + } + } + if (spacer != null) { + SpacerLabel(spacer.align(), spacer.caption().orEmpty(), Modifier.weight(1f)) + } else { + PackIcon(IconKeys.channel(channel.locked, channel.full, channel.subscribed).asList(), null, size = ICON) + Text( + channel.name, + Modifier.weight(1f), + color = if (row.current) MaterialTheme.colorScheme.primary else Color.Unspecified, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + ServerIcon(channel.iconId, size = ICON) + } + } +} + +/** A spacer's caption, placed as its tag asks; a repeated one of dashes or the like becomes a rule. */ +@Composable +private fun SpacerLabel(align: Char, caption: String, modifier: Modifier) { + if (align == '*') { + if (caption.isNotEmpty() && caption.all { it in "-_=.~" }) { + HorizontalDivider(modifier) + } else { + Text(caption.repeat(200 / caption.length.coerceAtLeast(1)), modifier, maxLines = 1, overflow = TextOverflow.Clip) + } + return + } + val textAlign = when (align) { + 'c' -> TextAlign.Center + 'r' -> TextAlign.End + else -> TextAlign.Start + } + Text(caption, modifier, textAlign = textAlign, maxLines = 1, overflow = TextOverflow.Ellipsis, + color = MaterialTheme.colorScheme.onSurfaceVariant) +} + +@Composable +private fun ClientRow(row: TreeRow.Client, countryFlags: Boolean, background: Color, onClient: (ClientItem) -> Unit) { + val client = row.client + RowLayout(row.depth, onClick = { onClient(client) }, background = background, tint = Color(client.background)) { + Spacer(Modifier.width(ICON + 4.dp)) + StatusIcon(client.status) + Row(Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(4.dp)) { + Text( + client.name, + fontWeight = if (client.self) FontWeight.Bold else FontWeight.Normal, + color = when (client.highlight) { + ContactType.FRIEND -> StatusColors.friend + ContactType.BLOCKED -> StatusColors.blocked + else -> Color.Unspecified + }, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (client.awayMessage.isNotEmpty()) { + Text("[${client.awayMessage}]", Modifier.weight(1f, fill = false), + color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } + for (id in client.groupIconIds) ServerIcon(id, size = ICON) + // The country's flag comes last, at the row's edge. + if (countryFlags) CountryFlag(client.country) + } +} + +@Composable +fun StatusIcon(status: ClientStatus, modifier: Modifier = Modifier) { + PackIcon(IconKeys.client(status), status.name, modifier, size = ICON) +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChatPane.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChatPane.kt new file mode 100644 index 0000000..c94b066 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChatPane.kt @@ -0,0 +1,185 @@ +package eu.lixko.ts3j.client.android.ui + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyRow +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.Send +import androidx.compose.material.icons.filled.AttachFile +import androidx.compose.material.icons.filled.Close +import androidx.compose.material3.Badge +import androidx.compose.material3.FilterChip +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.snapshotFlow +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.saveable.Saver +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.snapshots.SnapshotStateMap +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.isShiftPressed +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.type +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import eu.lixko.ts3j.client.android.ChatKey +import eu.lixko.ts3j.client.android.ChatLine +import eu.lixko.ts3j.client.android.ChatMatch +import eu.lixko.ts3j.client.android.Chats +import eu.lixko.ts3j.client.android.Conversation +import eu.lixko.ts3j.client.text.TextQuery +import kotlinx.coroutines.flow.first + +@Composable +fun ChatPane( + chats: Chats, + selected: Conversation, + canSend: Boolean, + onSelect: (ChatKey) -> Unit, + onClose: (ChatKey.Private) -> Unit, + onSend: (String) -> Unit, + /** Picks a file to share in [selected]. */ + onAttach: () -> Unit, + onLink: (String) -> Unit, + modifier: Modifier = Modifier, + /** The lines to show, when not all of [selected]'s. */ + lines: List = selected.lines, + find: TextQuery = TextQuery.EMPTY, + /** The match the find bar is on. */ + current: ChatMatch? = null, + /** A line to scroll to. */ + reveal: Long? = null, + onRevealed: () -> Unit = {}, +) { + Column(modifier) { + LazyRow( + contentPadding = PaddingValues(horizontal = 8.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + items(chats.all, key = { it.key.toString() }) { conversation -> + ConversationChip(conversation, conversation.key == selected.key, onSelect, onClose) + } + } + // Each conversation opens at its newest line. + key(selected.key) { Lines(lines, onLink, Modifier.weight(1f), find, current, reveal, onRevealed) } + // One unsent message per conversation, kept while another one is on screen. + val drafts = rememberSaveable(saver = DraftsSaver) { mutableStateMapOf() } + val draftKey = selected.key.toString() + val draft = drafts[draftKey].orEmpty() + val send = { + if (draft.isNotBlank()) { + onSend(draft.trim()) + drafts.remove(draftKey) + } + } + Row(Modifier.padding(8.dp), verticalAlignment = Alignment.CenterVertically) { + IconButton(onClick = onAttach, enabled = canSend) { + Icon(Icons.Filled.AttachFile, "Share file") + } + OutlinedTextField( + draft, { drafts[draftKey] = it }, + Modifier.weight(1f).onPreviewKeyEvent { e -> + // A hardware keyboard's Enter sends, as on the desktop; Shift+Enter starts a new line. + val enter = e.key == Key.Enter && !e.isShiftPressed + if (enter && e.type == KeyEventType.KeyDown) send() + enter + }, + placeholder = { Text("Message ${selected.title}", maxLines = 1, overflow = TextOverflow.Ellipsis) }, + enabled = canSend, + maxLines = 4, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send), + keyboardActions = KeyboardActions(onSend = { send() }), + ) + IconButton(onClick = send, enabled = canSend && draft.isNotBlank()) { + Icon(Icons.AutoMirrored.Filled.Send, "Send") + } + } + } +} + +private val DraftsSaver = Saver, HashMap>( + save = { HashMap(it) }, + restore = { mutableStateMapOf().apply { putAll(it) } }, +) + +@Composable +private fun ConversationChip( + conversation: Conversation, + selected: Boolean, + onSelect: (ChatKey) -> Unit, + onClose: (ChatKey.Private) -> Unit, +) { + val key = conversation.key + FilterChip( + selected = selected, + onClick = { onSelect(key) }, + label = { Text(conversation.title, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + leadingIcon = if (conversation.unread) ({ Badge() }) else null, + trailingIcon = if (key is ChatKey.Private) ({ + Icon(Icons.Filled.Close, "Close", Modifier.size(18.dp).clickable { onClose(key) }) + }) else null, + ) +} + +/** The conversation's lines, following new ones while the newest is in view. */ +@Composable +private fun Lines( + lines: List, + onLink: (String) -> Unit, + modifier: Modifier, + find: TextQuery, + current: ChatMatch?, + reveal: Long?, + onRevealed: () -> Unit, +) { + val listState = rememberLazyListState(initialFirstVisibleItemIndex = (lines.size - 1).coerceAtLeast(0)) + val link by rememberUpdatedState(onLink) + LaunchedEffect(lines.lastOrNull()?.id) { + val info = listState.layoutInfo + val atEnd = info.visibleItemsInfo.lastOrNull()?.index?.let { it >= info.totalItemsCount - 2 } ?: true + if (atEnd && lines.isNotEmpty()) listState.scrollToItem(lines.size - 1) + } + LaunchedEffect(reveal, lines) { + val id = reveal ?: return@LaunchedEffect + val index = lines.indexOfFirst { it.id == id } + if (index < 0) return@LaunchedEffect + val info = listState.layoutInfo + if (info.visibleItemsInfo.none { it.index == index && it.offset >= 0 && it.offset + it.size <= info.viewportEndOffset }) { + // The line's top ends up in the middle of the list. + val middle = snapshotFlow { listState.layoutInfo.viewportSize.height }.first { it > 0 } / 2 + listState.animateScrollToItem(index, -middle) + } + onRevealed() + } + LazyColumn(modifier.fillMaxWidth(), state = listState, contentPadding = PaddingValues(horizontal = 12.dp, vertical = 4.dp)) { + items(lines, key = { it.id }) { line -> + RichText(line.html, { link(it) }, Modifier.padding(vertical = 2.dp), MaterialTheme.typography.bodyMedium, + find, if (current?.line == line.id) current.nth else -1) + } + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChatText.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChatText.kt new file mode 100644 index 0000000..e3ea555 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChatText.kt @@ -0,0 +1,318 @@ +package eu.lixko.ts3j.client.android.ui + +import androidx.compose.foundation.Image +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.LocalTextStyle +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.produceState +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.LinkAnnotation +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextLinkStyles +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.fromHtml +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import eu.lixko.ts3j.client.android.WebPictures +import eu.lixko.ts3j.client.myts.ChatAttachment +import eu.lixko.ts3j.client.text.BBCode +import eu.lixko.ts3j.client.text.ChatHtml +import eu.lixko.ts3j.client.text.TextQuery + +/** + * HTML as [BBCode][eu.lixko.ts3j.client.text.BBCode] and [ChatHtml] write it, with its rules as dividers + * and its pictures fetched from the web: Android's HTML parser shows neither, so the text is + * split at them. + */ +@Composable +fun RichText( + html: String, + onLink: (String) -> Unit, + modifier: Modifier = Modifier, + style: TextStyle = LocalTextStyle.current, + /** Matches to highlight: [current] is the index of the one the find bar is on, if it is here. */ + find: TextQuery = TextQuery.EMPTY, + current: Int = -1, +) { + val link by rememberUpdatedState(onLink) + val color = linkColor() + val parsed = remember(html, color) { split(html) { chatText(it, color) { href -> link(href) } } } + val match = findMatchColor() + val currentMatch = findCurrentColor() + val pieces = remember(parsed, find, current, match, currentMatch) { + if (find.isEmpty) parsed else highlight(parsed, find, current, match, currentMatch) + } + Column(modifier) { + for (piece in pieces) { + when (piece) { + Piece.Rule -> HorizontalDivider(Modifier.padding(vertical = 6.dp)) + is Piece.Image -> WebPicture(piece, style) { link(it) } + // As wide as there is room, for aligned paragraphs to have somewhere to go. + is Piece.Text -> if (piece.text.isNotEmpty()) Text(piece.text, Modifier.fillMaxWidth(), style = style) + } + } + } +} + +/** [pieces] with [find]'s matches behind [match], and the [current]th of them, counting across pieces, behind [currentMatch]. */ +private fun highlight(pieces: List, find: TextQuery, current: Int, match: Color, currentMatch: Color): List { + var n = 0 + return pieces.map { piece -> + if (piece !is Piece.Text) return@map piece + val m = find.matcher(piece.text.text) ?: return@map piece + val text = AnnotatedString.Builder(piece.text) + while (m.find()) { + if (m.end() == m.start()) continue + text.addStyle(SpanStyle(background = if (n == current) currentMatch else match), m.start(), m.end()) + n++ + } + Piece.Text(text.toAnnotatedString()) + } +} + +/** The web pictures descriptions show. */ +val LocalWebPictures = staticCompositionLocalOf { null } + +private sealed interface Piece { + data class Text(val text: AnnotatedString) : Piece + data object Rule : Piece + /** @param href where the picture links to, if it sits in a link */ + data class Image(val url: String, val href: String?, val align: Alignment.Horizontal) : Piece +} + +/** + * [html] cut at its rules and pictures. Each piece of text is closed where it is cut and the + * next reopens what it was in, so an aligned block or a link carries on past a picture. + */ +private fun split(html: String, text: (String) -> AnnotatedString): List { + val pieces = ArrayList() + val divs = ArrayList() + var anchor: String? = null + var href: String? = null + val current = StringBuilder() + fun cut() { + if (anchor != null) current.append("") + repeat(divs.size) { current.append("") } + pieces += Piece.Text(text(current.toString())) + current.setLength(0) + divs.forEach { current.append(it) } + anchor?.let { current.append(it) } + } + var last = 0 + for (m in CUT_TAG.findAll(html)) { + current.append(html, last, m.range.first) + last = m.range.last + 1 + val tag = m.value + when { + tag.startsWith(" { + cut() + pieces += Piece.Rule + } + tag.startsWith(" { + cut() + pieces += Piece.Image(unescape(m.groupValues[1]), href?.let(::unescape), alignment(divs)) + } + tag.startsWith(" { + divs += tag + current.append(tag) + } + tag.equals("", ignoreCase = true) -> { + divs.removeLastOrNull() + current.append(tag) + } + tag.startsWith(" { + anchor = tag + href = m.groupValues[2] + current.append(tag) + } + else -> { + anchor = null + href = null + current.append(tag) + } + } + } + current.append(html, last, html.length) + pieces += Piece.Text(text(current.toString())) + return pieces +} + +/** Where the innermost aligned block puts what is in it. */ +private fun alignment(divs: List): Alignment.Horizontal { + val align = divs.asReversed().firstNotNullOfOrNull { ALIGN.find(it)?.groupValues?.get(1) } + return when (align) { + "center" -> Alignment.CenterHorizontally + "right" -> Alignment.End + else -> Alignment.Start + } +} + +private fun unescape(s: String) = + s.replace("<", "<").replace(">", ">").replace(""", "\"").replace("&", "&") + +/** + * A picture at its own size, a pixel to a dp as TeamSpeak shows it, narrowed to fit. With + * pictures turned off, or when one cannot be had, its address as a link behind a picture icon. + */ +@Composable +private fun WebPicture(image: Piece.Image, style: TextStyle, onLink: (String) -> Unit) { + val pictures = LocalWebPictures.current + Column(Modifier.fillMaxWidth().padding(vertical = 2.dp), horizontalAlignment = image.align) { + if (pictures == null || !pictures.enabled) { + PictureLink("ICONVIEWER", image, style, onLink) + return@Column + } + val version by pictures.version.collectAsStateWithLifecycle() + val state by produceState(WebPictures.State.Loading, image.url, version) { + value = pictures.state(image.url) + } + when (val shown = state) { + WebPictures.State.Loading -> PackIcon("LOADING_IMAGE", "Loading picture", size = 16.dp) + WebPictures.State.Broken -> PictureLink("BROKEN_IMAGE", image, style, onLink) + is WebPictures.State.Shown -> { + val picture = shown.picture + val viewer = LocalPictureViewer.current + Image( + rememberPicturePainter(picture), + null, + Modifier + .widthIn(max = picture.width.dp) + .aspectRatio(picture.width.toFloat() / picture.height.coerceAtLeast(1)) + .then(if (viewer != null) Modifier.clickable { + viewer(viewedPicture(image, onLink) { pictures.data(image.url) }) + } else if (image.href != null) Modifier.clickable { onLink(image.href) } else Modifier), + ) + } + } + } +} + +/** [image] to open full size; a file shared in chat has no address to copy or link to follow but itself. */ +private fun viewedPicture(image: Piece.Image, onLink: (String) -> Unit, read: suspend () -> ByteArray?): ViewedPicture { + val attachment = ChatAttachment.Ref.parse(image.url) + if (attachment != null) return ViewedPicture(attachment.fileName.substringBeforeLast('.'), read = read) + val openLink = image.href?.let { href -> { onLink(href) } } + return ViewedPicture(pictureName(image.url), image.url, openLink, read = read) +} + +/** The picture's address as a link behind [iconKey], then the link it sat in, if any, so neither is lost. */ +@Composable +private fun PictureLink(iconKey: String, image: Piece.Image, style: TextStyle, onLink: (String) -> Unit) { + val color = linkColor() + val text = remember(image, color) { + val links = listOfNotNull(image.url, image.href?.takeIf { it != image.url }) + chatText(links.joinToString(" ") { "${BBCode.escape(linkText(it))}" }, color, onLink) + } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + PackIcon(iconKey, "Picture", size = 16.dp) + Text(text, style = style) + } +} + +/** A shared file goes by its name, anything else by its address. */ +private fun linkText(url: String): String = ChatAttachment.Ref.parse(url)?.fileName ?: BBCode.shortAddress(url) + +/** + * HTML without rules as styled text. Android's parser knows no stylesheets, tables, + * numbered lists, font sizes or `align`, so the classes [ChatHtml] marks lines with become + * inline colours, table rows lines of their cells, numbered items numbered lines, sizes + * ``/``, and alignment the style it does know. + */ +fun chatText(html: String, linkColor: Color, onLink: (String) -> Unit): AnnotatedString { + val styled = sizes(numbered(CLASS.replace(html) { m -> + CLASS_COLORS[m.groupValues[1]]?.let { "style=\"color:$it\"" } ?: "" + })) + .replace(ALIGN) { m -> "style=\"text-align:${ALIGNS.getValue(m.groupValues[1])}\"" } + .replace(CELL_END, " ") + .replace(ROW_END, "
") + val text = AnnotatedString.fromHtml( + styled, + TextLinkStyles(SpanStyle(color = linkColor, fontWeight = FontWeight.SemiBold)), + ) { link -> (link as? LinkAnnotation.Url)?.let { onLink(it.url) } } + // Block elements leave line breaks around the text. + val start = text.text.indexOfFirst { !it.isWhitespace() }.coerceAtLeast(0) + val end = text.text.indexOfLast { !it.isWhitespace() } + 1 + return if (end <= start) AnnotatedString("") else text.subSequence(start, end) +} + +/** Numbers the items of each `
    `, innermost first. */ +private fun numbered(html: String): String { + var out = html + while (true) { + val list = INNER_OL.find(out) ?: return out + val letters = list.groupValues[1].isNotEmpty() + var n = 0 + val items = LI.replace(list.groupValues[2]) { m -> + if (m.value.startsWith("" + (if (letters) ('a' + (n - 1) % 26).toString() else n.toString()) + ". " + } + } + out = out.replaceRange(list.range, "
    $items
    ") + } +} + +/** + * Turns each font-size span into ``s or `` (or a plain span), closing it alike. + * Sizes are TeamSpeak's, around its 11 px text. + */ +private fun sizes(html: String): String { + val closes = ArrayDeque() + return SPAN.replace(html) { m -> + if (m.value.startsWith(" listOf("span") + px >= BIGGER_PX -> listOf("big", "big") + px >= BIG_PX -> listOf("big") + px <= SMALL_PX -> listOf("small") + else -> listOf("span") + } + closes.addLast(tags.reversed().joinToString("") { "" }) + if (px == null) m.value else tags.joinToString("") { "<$it>" } + } + } +} + +private const val BIGGER_PX = 18 +private const val BIG_PX = 13 +private const val SMALL_PX = 9 + +private val INNER_OL = Regex("((?:(?!]).)*?)
", RegexOption.DOT_MATCHES_ALL) +private val LI = Regex("") +private val SPAN = Regex("|]*>|") +private val ALIGNS = mapOf("left" to "start", "justify" to "start", "center" to "center", "right" to "end") + +/** Where the text is cut, and what it has to carry across: aligned blocks and links. */ +private val CUT_TAG = Regex( + "||]*>||]*href=\"([^\"]*)\"[^>]*>|", + RegexOption.IGNORE_CASE, +) +private val CLASS = Regex("class=\"([a-z]+)\"") +private val ALIGN = Regex("align=\"(left|center|right|justify)\"") +private val CELL_END = Regex("") +private val ROW_END = Regex("") + +private val CLASS_COLORS = mapOf( + ChatHtml.MUTED_CLASS to "#8c8c8c", + ChatHtml.EVENT_CLASS to "#7a8fa6", +) diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ConnectScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ConnectScreen.kt new file mode 100644 index 0000000..827b221 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ConnectScreen.kt @@ -0,0 +1,231 @@ +package eu.lixko.ts3j.client.android.ui + +import android.graphics.BitmapFactory +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.Image +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.layout.Box +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material3.Button +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExposedDropdownMenuBox +import androidx.compose.material3.ExposedDropdownMenuDefaults +import androidx.compose.material3.ExposedDropdownMenuAnchorType +import androidx.compose.material3.Icon +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.IconButton +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.withStyle +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import eu.lixko.ts3j.client.android.IdentityInfo +import eu.lixko.ts3j.client.android.SessionController +import eu.lixko.ts3j.client.config.Bookmark +import eu.lixko.ts3j.client.net.IconRepository + +/** Where to connect to: an address typed in, or a bookmark. */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ConnectScreen( + vm: SessionController, + snackbar: SnackbarHostState, + onSettings: () -> Unit, + onConnect: (() -> Unit) -> Unit, + onEditBookmark: (BookmarkEdit) -> Unit, + /** Back to the servers already connected; null when there are none. */ + onBack: (() -> Unit)?, +) { + val lastEnd by vm.lastEnd.collectAsStateWithLifecycle() + val bookmarks by vm.bookmarks.collectAsStateWithLifecycle() + val identities by vm.identities.all.collectAsStateWithLifecycle() + var address by rememberSaveable { mutableStateOf(vm.lastAddress) } + var identityId by rememberSaveable { mutableStateOf("") } + var nickname by rememberSaveable { mutableStateOf(vm.nicknameFor("")) } + var password by rememberSaveable { mutableStateOf("") } + + if (onBack != null) BackHandler(onBack = onBack) + + Scaffold( + topBar = { + TopAppBar( + title = { Text("TeamSpeak") }, + navigationIcon = { + if (onBack != null) IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } + }, + actions = { + IconButton(onClick = onSettings) { PackIcon("SETTINGS", "Settings") } + }, + ) + }, + snackbarHost = { SnackbarHost(snackbar) }, + ) { padding -> + LazyColumn( + Modifier.padding(padding).imePadding(), + contentPadding = PaddingValues(16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + item { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField(address, { address = it }, Modifier.fillMaxWidth(), label = { Text("Server address") }, + singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri)) + OutlinedTextField(nickname, { nickname = it }, Modifier.fillMaxWidth(), label = { Text("Nickname") }, + singleLine = true) + OutlinedTextField(password, { password = it }, Modifier.fillMaxWidth(), + label = { Text("Server password") }, singleLine = true, + visualTransformation = PasswordVisualTransformation(), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)) + IdentityField(identities, identityId) { + identityId = it + nickname = vm.nicknameFor(it) + } + lastEnd?.let { + Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodyMedium) + } + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Button( + onClick = { onConnect { vm.connect(address.trim(), nickname.trim(), password, identityId) } }, + enabled = address.isNotBlank() && nickname.isNotBlank(), + ) { Text("Connect") } + TextButton(onClick = { + onEditBookmark(BookmarkEdit(-1, vm.newBookmark(address.trim(), nickname.trim(), password, identityId))) + }, enabled = address.isNotBlank()) { Text("Add bookmark") } + } + } + } + if (bookmarks.isNotEmpty()) { + item { + Text("Bookmarks", Modifier.padding(top = 16.dp), style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.primary) + } + } + itemsIndexed(bookmarks) { index, bookmark -> + BookmarkRow(bookmark, identities, { onConnect { vm.connect(bookmark) } }, + onEdit = { onEditBookmark(BookmarkEdit(index, bookmark)) }, + onPin = if (vm.canPinShortcuts) ({ vm.pinShortcut(bookmark) }) else null, + onRemove = { vm.removeBookmark(bookmark) }) + } + } + } +} + +/** The identities to connect with, the default one first as an empty id. */ +private fun identityChoices(identities: List): List> { + val default = identities.firstOrNull { it.isDefault }?.name + return listOf("" to (default?.let { "Default ($it)" } ?: "Default")) + identities.map { it.id to it.name } +} + +/** An id no longer among the identities connects with the default, and shows as such. */ +private fun shownId(identities: List, id: String) = id.takeIf { i -> identities.any { it.id == i } } ?: "" + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun IdentityField(identities: List, selected: String, onSelect: (String) -> Unit) { + val choices = identityChoices(identities) + val shown = shownId(identities, selected) + var open by remember { mutableStateOf(false) } + ExposedDropdownMenuBox(open, { open = it }) { + OutlinedTextField( + choices.first { it.first == shown }.second, {}, readOnly = true, singleLine = true, + label = { Text("Identity") }, + trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(open) }, + modifier = Modifier.fillMaxWidth().menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable), + ) + ExposedDropdownMenu(open, { open = false }) { + for ((id, name) in choices) { + DropdownMenuItem({ Text(name) }, onClick = { + open = false + onSelect(id) + }) + } + } + } +} + +/** The server's icon as last seen there, else the pack's bookmark icon. */ +@Composable +private fun BookmarkIcon(iconId: Long) { + val cached = remember(iconId) { + IconRepository.cached(iconId)?.let { BitmapFactory.decodeByteArray(it, 0, it.size)?.asImageBitmap() } + } + if (cached != null) Image(cached, null, Modifier.size(24.dp)) + else PackIcon("BOOKMARK_MANAGER", null) +} + +private val AUTOCONNECT = Color(0xFF3A9D4A) + +@Composable +private fun BookmarkRow( + bookmark: Bookmark, + identities: List, + onConnect: () -> Unit, + onEdit: () -> Unit, + /** Null when the launcher takes no shortcuts. */ + onPin: (() -> Unit)?, + onRemove: () -> Unit, +) { + val identity = identities.firstOrNull { it.id == bookmark.identityId } + var menu by remember { mutableStateOf(false) } + ListItem( + headlineContent = { + Text(buildAnnotatedString { + if (bookmark.connectOnStartup) { + withStyle(SpanStyle(color = AUTOCONNECT, fontWeight = FontWeight.Bold)) { append("AC") } + append(' ') + } + append(bookmark.displayName()) + }) + }, + supportingContent = { + Text(listOfNotNull("${bookmark.address}:${bookmark.port}", bookmark.channel.ifBlank { null }, identity?.name) + .joinToString(" · ")) + }, + leadingContent = { BookmarkIcon(bookmark.iconId) }, + trailingContent = { + Box { + IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "Bookmark options") } + DropdownMenu(menu, { menu = false }) { + DropdownMenuItem({ Text("Edit") }, onClick = { menu = false; onEdit() }) + onPin?.let { DropdownMenuItem({ Text("Add to home screen") }, onClick = { menu = false; it() }) } + DropdownMenuItem({ Text("Remove") }, onClick = { menu = false; onRemove() }) + } + } + }, + modifier = Modifier.clickable(onClick = onConnect), + ) +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ConnectionInfoScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ConnectionInfoScreen.kt new file mode 100644 index 0000000..cbbd3aa --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ConnectionInfoScreen.kt @@ -0,0 +1,150 @@ +package eu.lixko.ts3j.client.android.ui + +import android.content.ClipData +import android.content.ClipboardManager +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.PrimaryScrollableTabRow +import androidx.compose.material3.Tab +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.font.FontStyle +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import eu.lixko.ts3j.client.android.ClientItem +import eu.lixko.ts3j.client.android.ServerController +import eu.lixko.ts3j.client.net.ConnectionStats +import eu.lixko.ts3j.client.net.ConnectionStatsFormat +import kotlinx.coroutines.delay + +private const val REFRESH_MS = 1000L + +private val TABS = ConnectionStatsFormat.TRAFFIC_TABS.map { it.title() } + + listOf(ConnectionStatsFormat.QUOTA_TAB, ConnectionStatsFormat.VOICE_TAB) + +/** + * A client's connection figures, read again every second while shown, laid out as TeamSpeak's + * Connection Info window: name, times, ping and address beside the avatar, then a tab per + * traffic category with Total / In / Out columns, Quota, and what our playback made of their voice. + */ +@Composable +fun ConnectionInfoScreen(server: ServerController, clientId: Int, client: ClientItem?, onBack: () -> Unit) { + var stats by remember { mutableStateOf(null) } + LaunchedEffect(clientId) { + while (true) { + stats = server.connectionStats(clientId) ?: break + delay(REFRESH_MS) + } + } + var tab by rememberSaveable { mutableIntStateOf(0) } + val s = stats + SubScreen("Connection info", onBack) { padding -> + Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) { + Row(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) { + Summary(s, client?.nickname ?: "", Modifier.weight(1f)) + if (client != null && client.avatarFlag.isNotEmpty()) { + Avatar(client.uniqueId, client.avatarFlag, Modifier.padding(start = 12.dp), size = 72.dp) + } + } + PrimaryScrollableTabRow(selectedTabIndex = tab, edgePadding = 8.dp) { + TABS.forEachIndexed { i, title -> Tab(tab == i, onClick = { tab = i }, text = { Text(title) }) } + } + val traffic = ConnectionStatsFormat.TRAFFIC_TABS + Column(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) { + when { + tab < traffic.size -> TrafficTable(ConnectionStatsFormat.trafficRows(s, traffic[tab].kind())) + tab == traffic.size -> Figures(ConnectionStatsFormat.quotaGroups(s)) + else -> Figures(listOf(ConnectionStatsFormat.voiceRows(s?.voiceReceived))) + } + } + } + } +} + +@Composable +private fun Summary(s: ConnectionStats?, nickname: String, modifier: Modifier) { + val context = LocalContext.current + val address = ConnectionStatsFormat.copyableAddress(s) + val rows = ConnectionStatsFormat.summaryRows(s, nickname) + Column(modifier) { + rows.forEachIndexed { i, row -> + Row(Modifier.heightIn(min = 32.dp), verticalAlignment = Alignment.CenterVertically) { + Text(row.label, Modifier.weight(1f), color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(row.value, textAlign = TextAlign.End) + if (i == rows.lastIndex) { + IconButton( + onClick = { + // The system confirms the copy itself. + context.getSystemService(ClipboardManager::class.java) + .setPrimaryClip(ClipData.newPlainText("Client address", address)) + }, + enabled = address != null, + modifier = Modifier.size(32.dp), + ) { PackIcon("COPY", "Copy client address", size = 18.dp) } + } + } + } + } +} + +/** Labelled figures in groups set apart by a rule. */ +@Composable +private fun Figures(groups: List>) { + groups.forEachIndexed { g, rows -> + if (g > 0) HorizontalDivider(Modifier.padding(vertical = 8.dp)) + for (row in rows) { + Row(Modifier.padding(vertical = 4.dp)) { + Text(row.label, Modifier.weight(1f), color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(row.value, textAlign = TextAlign.End) + } + } + } +} + +@Composable +private fun TrafficTable(rows: List) { + Row(Modifier.padding(vertical = 4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp)) { + LabelCell("") + ConnectionStatsFormat.COLUMNS.forEachIndexed { i, column -> ValueCell(column, i == 0, FontStyle.Italic) } + } + for (row in rows) { + Row(Modifier.padding(vertical = 4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp), + verticalAlignment = Alignment.CenterVertically) { + LabelCell(row.label) + ValueCell(row.total, narrow = true) + ValueCell(row.`in`) + ValueCell(row.out) + } + } +} + +@Composable +private fun RowScope.LabelCell(text: String) = + Text(text, Modifier.weight(1.5f), color = MaterialTheme.colorScheme.onSurfaceVariant, + style = MaterialTheme.typography.bodySmall) + +/** The Total column only ever holds the loss percentage. */ +@Composable +private fun RowScope.ValueCell(text: String, narrow: Boolean = false, fontStyle: FontStyle? = null) = + Text(text, Modifier.weight(if (narrow) 0.7f else 1f), style = MaterialTheme.typography.bodySmall, fontStyle = fontStyle, + textAlign = TextAlign.End) diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ContactsScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ContactsScreen.kt new file mode 100644 index 0000000..0b5d057 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ContactsScreen.kt @@ -0,0 +1,271 @@ +package eu.lixko.ts3j.client.android.ui + +import android.content.ClipData +import android.content.ClipboardManager +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.ListItem +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.PrimaryTabRow +import androidx.compose.material3.Tab +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import eu.lixko.ts3j.client.android.SessionController +import eu.lixko.ts3j.client.contacts.Contact +import eu.lixko.ts3j.client.contacts.ContactDefaults +import eu.lixko.ts3j.client.contacts.ContactType +import eu.lixko.ts3j.client.contacts.NicknameDisplay +import kotlinx.coroutines.launch +import java.time.format.DateTimeFormatter +import kotlin.math.roundToInt + +private val SEEN = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm") + +private val DISPLAYS = listOf( + NicknameDisplay.ONLY_NICKNAME to "Nickname", + NicknameDisplay.ONLY_CUSTOM to "Custom name", + NicknameDisplay.BOTH to "Both", +) + +private val GROUPS = listOf( + ContactType.FRIEND to "Friends", + ContactType.BLOCKED to "Blocked", + ContactType.NEUTRAL to "Neutral", +) + +/** + * The contact list, grouped as TeamSpeak's Contacts window groups it, with each + * contact's own page and the defaults new contacts start out with. + * + * @param editing the unique id of the contact whose page is open, if any + */ +@Composable +fun ContactsScreen(vm: SessionController, editing: String?, onEdit: (String?) -> Unit, onBack: () -> Unit) { + var defaults by rememberSaveable { mutableStateOf(false) } + when { + editing != null -> return ContactScreen(vm, editing, onBack = { onEdit(null) }) + defaults -> return ContactDefaultsScreen(vm, onBack = { defaults = false }) + } + + val contacts by vm.contacts.collectAsStateWithLifecycle() + val scope = rememberCoroutineScope() + var menu by remember { mutableStateOf(false) } + var imported by remember { mutableStateOf(null) } + val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + if (uri != null) scope.launch { + imported = runCatching { vm.importContacts(uri) }.fold( + { (found, added) -> + if (found == 0) "That file holds no contacts." + else "Imported $found contacts, $added of them new." + }, + { "That file is not a TeamSpeak 3 settings.db." }, + ) + } + } + + SubScreen("Contacts", onBack, actions = { + Box { + IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "More") } + DropdownMenu(menu, { menu = false }) { + DropdownMenuItem({ Text("Defaults for new contacts") }, onClick = { menu = false; defaults = true }) + DropdownMenuItem({ Text("Import from TeamSpeak 3") }, onClick = { + menu = false + importer.launch(arrayOf("*/*")) + }) + } + } + }) { padding -> + LazyColumn(Modifier.padding(padding)) { + imported?.let { item { Hint(it) } } + if (contacts.isEmpty()) { + item { + Hint("No contacts yet. Tap a client on a server to add them as a friend or block them, " + + "or import the contacts of TeamSpeak 3 from its settings.db.") + } + } + for ((type, title) in GROUPS) { + val group = contacts.filter { it.type == type }.sortedBy { label(it).lowercase() } + if (group.isEmpty()) continue + item(key = type) { Section(title) } + items(group, key = { it.uniqueId }) { contact -> + ListItem( + headlineContent = { Text(label(contact), color = typeColor(contact.type)) }, + supportingContent = { Text(lastSeen(contact)) }, + modifier = Modifier.clickable { onEdit(contact.uniqueId) }, + ) + } + } + } + } +} + +/** One contact's settings; each is stored as it is changed, the names once the page is left. */ +@Composable +private fun ContactScreen(vm: SessionController, uniqueId: String, onBack: () -> Unit) { + val contacts by vm.contacts.collectAsStateWithLifecycle() + val contact = contacts.firstOrNull { it.uniqueId == uniqueId } + if (contact == null) { + LaunchedEffect(Unit) { onBack() } + return + } + // Starts from the stored entry, which may have been seen again since this page opened. + fun edit(change: Contact.() -> Unit) { + vm.contact(uniqueId)?.let { vm.saveContact(it.apply(change)) } + } + var customName by rememberSaveable(uniqueId) { mutableStateOf(contact.nickname) } + var phoneticName by rememberSaveable(uniqueId) { mutableStateOf(contact.phoneticNickname) } + var removing by remember { mutableStateOf(false) } + val leave = { + if (customName.trim() != contact.nickname || phoneticName.trim() != contact.phoneticNickname) { + edit { + nickname = customName.trim() + phoneticNickname = phoneticName.trim() + } + } + onBack() + } + + SubScreen(label(contact), leave, actions = { + IconButton(onClick = { removing = true }) { PackIcon(if (contact.type == ContactType.BLOCKED) "REMOVE_FOE" else "REMOVE_FRIEND", "Remove from contacts") } + }) { padding -> + Column(Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(vertical = 8.dp)) { + OutlinedTextField(customName, { customName = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp), + label = { Text("Custom nickname") }, singleLine = true) + OutlinedTextField(phoneticName, { phoneticName = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), + label = { Text("Phonetic nickname") }, singleLine = true) + + Section("Contact") + Segments(GROUPS.map { (type, _) -> type to type.label() }, contact.type) { edit { type = it } } + + Section("Show as") + Segments(DISPLAYS, contact.nicknameDisplay) { edit { nicknameDisplay = it } } + + Section("Ignore") + Toggle("Mute", contact.automute) { edit { automute = it } } + Toggle("Ignore server and channel chat", contact.ignorePublicMessages) { edit { ignorePublicMessages = it } } + Toggle("Ignore private chat", contact.ignorePrivateMessages) { edit { ignorePrivateMessages = it } } + Toggle("Ignore pokes", contact.ignorePokes) { edit { ignorePokes = it } } + Toggle("Hide avatar", contact.ignoreAvatar) { edit { ignoreAvatar = it } } + Toggle("Hide away message", contact.ignoreAwayMessage) { edit { ignoreAwayMessage = it } } + Toggle("Deny whisper", !contact.whisperAllowed) { edit { whisperAllowed = !it } } + + Section("Playback") + val volume = if (contact.hasVolumeModifier) contact.volumeModifier.toFloat() else 0f + Level("Volume", volume, -30f..20f, ::formatVolume) { db -> + val rounded = db.roundToInt().toDouble() + edit { + hasVolumeModifier = rounded != 0.0 + volumeModifier = rounded + } + } + + Section("Details") + val context = LocalContext.current + LinkRow("Unique ID", contact.uniqueId) { + // The system confirms the copy itself. + context.getSystemService(ClipboardManager::class.java) + .setPrimaryClip(ClipData.newPlainText("Unique ID", contact.uniqueId)) + } + ListItem(headlineContent = { Text(lastSeen(contact)) }) + } + } + + if (removing) { + AlertDialog( + onDismissRequest = { removing = false }, + title = { Text("Remove ${label(contact)}?") }, + text = { Text("Their settings here are forgotten; they show as anyone else again.") }, + confirmButton = { + TextButton(onClick = { + removing = false + vm.removeContact(uniqueId) + onBack() + }) { Text("Remove") } + }, + dismissButton = { TextButton(onClick = { removing = false }) { Text("Cancel") } }, + ) + } +} + +/** What a client starts out with when added as a friend, blocked or neutral. */ +@Composable +private fun ContactDefaultsScreen(vm: SessionController, onBack: () -> Unit) { + val defaults = vm.settings.contactDefaults + var tab by rememberSaveable { mutableStateOf(ContactType.FRIEND) } + var entry by remember(tab) { mutableStateOf(ContactDefaults.Entry().apply { copyFrom(defaults.of(tab)) }) } + fun edit(change: ContactDefaults.Entry.() -> Unit) { + val changed = ContactDefaults.Entry().apply { copyFrom(entry); change() } + defaults.of(tab).copyFrom(changed) + vm.settings.save() + entry = changed + } + + SubScreen("Defaults for new contacts", onBack) { padding -> + Column(Modifier.padding(padding)) { + PrimaryTabRow(selectedTabIndex = GROUPS.indexOfFirst { it.first == tab }) { + for ((type, title) in GROUPS) Tab(tab == type, onClick = { tab = type }, text = { Text(title) }) + } + Column(Modifier.verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { + Section("Show as") + Segments(DISPLAYS, entry.nicknameDisplay) { edit { nicknameDisplay = it } } + Section("Ignore") + Toggle("Mute", entry.automute) { edit { automute = it } } + Toggle("Ignore server and channel chat", entry.ignorePublicMessages) { edit { ignorePublicMessages = it } } + Toggle("Ignore private chat", entry.ignorePrivateMessages) { edit { ignorePrivateMessages = it } } + Toggle("Ignore pokes", entry.ignorePokes) { edit { ignorePokes = it } } + Toggle("Hide avatar", entry.ignoreAvatar) { edit { ignoreAvatar = it } } + Toggle("Hide away message", entry.ignoreAwayMessage) { edit { ignoreAwayMessage = it } } + Toggle("Deny whisper", entry.ignoreWhisper) { edit { ignoreWhisper = it } } + } + } + } +} + +private fun label(contact: Contact) = contact.nickname.ifBlank { contact.uniqueId } + +private fun lastSeen(contact: Contact): String { + val seen = contact.lastSeen ?: return "Never seen" + val where = contact.lastSeenServerName.ifBlank { contact.lastSeenServerAddress } + return "Last seen ${SEEN.format(seen)}" + if (where.isNotBlank()) " on $where" else "" +} + +private fun formatVolume(db: Float): String { + val rounded = db.roundToInt() + return if (rounded == 0) "Unchanged" else "${if (rounded > 0) "+" else ""}$rounded dB" +} + +private fun typeColor(type: ContactType): Color = when (type) { + ContactType.FRIEND -> StatusColors.friend + ContactType.BLOCKED -> StatusColors.blocked + ContactType.NEUTRAL -> Color.Unspecified +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/DetailsSection.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/DetailsSection.kt new file mode 100644 index 0000000..38cda95 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/DetailsSection.kt @@ -0,0 +1,137 @@ +package eu.lixko.ts3j.client.android.ui + +import androidx.compose.animation.animateContentSize +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clipToBounds +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.Layout +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Constraints +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import eu.lixko.ts3j.client.net.Details +import eu.lixko.ts3j.client.text.BBCode + +/** + * The facts of the server, a channel or a client, then its description, for the top of its sheet. + * The minor facts wait behind "more…". + */ +@Composable +fun DetailsSection(details: Details, onLink: (String) -> Unit, modifier: Modifier = Modifier) { + var all by rememberSaveable(details.title()) { mutableStateOf(false) } + val shown = if (all) details.fields() else details.fields().filterNot { it.minor() } + val more = !all && shown.size < details.fields().size + Column(modifier.padding(horizontal = 24.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + if (shown.isNotEmpty() || more) { + Column(Modifier.animateContentSize(), verticalArrangement = Arrangement.spacedBy(2.dp)) { + for (field in shown) Fact(field) + if (more) { + Text("more…", Modifier.clickable { all = true }.padding(vertical = 2.dp), + style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary) + } + } + } + when { + details.description().isNotBlank() -> Description(details.description(), onLink) + details.pending() -> Text("Loading description…", style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun Fact(field: Details.Field) { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text(field.label(), Modifier.width(96.dp), style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + if (field.groups().isEmpty()) { + Text(field.value(), style = MaterialTheme.typography.bodySmall) + } else { + // Each group with its icon, as TeamSpeak's info frame lists them. + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + // A nameless group shows only its icon, and takes no comma. + val lastNamed = field.groups().indexOfLast { it.name.isNotBlank() } + field.groups().forEachIndexed { i, group -> + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + ServerIcon(group.iconId, size = 14.dp) + if (group.name.isNotBlank()) { + Text(group.name.trim() + if (i < lastNamed) "," else "", style = MaterialTheme.typography.bodySmall) + } + } + } + } + } + } +} + +/** The description in a box that opens up, when there is more of it than fits folded. */ +@Composable +private fun Description(bbcode: String, onLink: (String) -> Unit) { + val html = remember(bbcode) { BBCode.toHtml(bbcode, true) } + var expanded by rememberSaveable(bbcode) { mutableStateOf(false) } + var overflows by remember(bbcode) { mutableStateOf(false) } + val expandable = overflows || expanded + val background = MaterialTheme.colorScheme.surfaceContainerHigh + Surface( + Modifier.fillMaxWidth().then(if (expandable) Modifier.clickable { expanded = !expanded } else Modifier), + shape = RoundedCornerShape(12.dp), + color = background, + ) { + Column(Modifier.animateContentSize().padding(12.dp)) { + Box { + Folded(FOLDED_HEIGHT, expanded, onOverflow = { overflows = it }) { + RichText(html, onLink, style = MaterialTheme.typography.bodyMedium) + } + if (overflows && !expanded) { + Box(Modifier.align(Alignment.BottomCenter).fillMaxWidth().height(24.dp) + .background(Brush.verticalGradient(listOf(Color.Transparent, background)))) + } + } + if (expandable) { + Text(if (expanded) "Less" else "More", Modifier.padding(top = 4.dp), + style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary) + } + } + } +} + +/** Its content cut to [height] unless [open], telling whether there is more of it than that. */ +@Composable +private fun Folded(height: Dp, open: Boolean, onOverflow: (Boolean) -> Unit, content: @Composable () -> Unit) { + val report by rememberUpdatedState(onOverflow) + Layout(content, Modifier.clipToBounds()) { measurables, constraints -> + val placeable = measurables.first().measure(constraints.copy(maxHeight = Constraints.Infinity)) + val limit = height.roundToPx() + report(placeable.height > limit) + val shown = if (open) placeable.height else minOf(placeable.height, limit) + layout(placeable.width, shown) { placeable.place(0, 0) } + } +} + +private val FOLDED_HEIGHT = 128.dp diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/FilesScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/FilesScreen.kt new file mode 100644 index 0000000..9c6ccb6 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/FilesScreen.kt @@ -0,0 +1,239 @@ +package eu.lixko.ts3j.client.android.ui + +import android.text.format.DateUtils +import android.text.format.Formatter +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import eu.lixko.ts3j.client.android.ServerController +import eu.lixko.ts3j.client.android.TransferRow +import eu.lixko.ts3j.client.net.filetransfer.FileTransfer +import eu.lixko.ts3j.client.net.filetransfer.RemoteFile +import kotlinx.coroutines.launch + +/** A channel's file repository: folders to walk, files to download, upload, rename and delete. */ +@Composable +fun FilesScreen(server: ServerController, channelId: Int, channelName: String, password: String, onBack: () -> Unit) { + val scope = rememberCoroutineScope() + val snackbar = remember { SnackbarHostState() } + var path by rememberSaveable { mutableStateOf("/") } + var files by remember { mutableStateOf?>(null) } + var failure by remember { mutableStateOf(null) } + var reloads by remember { mutableIntStateOf(0) } + val transfers by server.files.rows.collectAsStateWithLifecycle() + var downloading by remember { mutableStateOf(null) } + var creatingFolder by remember { mutableStateOf(false) } + var renaming by remember { mutableStateOf(null) } + var deleting by remember { mutableStateOf(null) } + + LaunchedEffect(path, reloads) { + failure = null + server.listFiles(channelId, password, path) + .onSuccess { list -> files = list.sortedWith(compareBy({ !it.isDirectory }, { it.name.lowercase() })) } + .onFailure { files = emptyList(); failure = it.message ?: "Could not list the files" } + } + // An upload into the folder on screen shows up once it is there. + val uploadedHere = transfers.count { it.upload && it.channelId == channelId && it.directory == path && it.state == FileTransfer.State.COMPLETED } + LaunchedEffect(uploadedHere) { if (uploadedHere > 0) reloads++ } + + val tell = { message: String -> scope.launch { snackbar.showSnackbar(message) }; Unit } + val act = { call: suspend () -> String? -> + scope.launch { + val error = call() + if (error != null) snackbar.showSnackbar(error) else reloads++ + } + Unit + } + + val saver = rememberLauncherForActivityResult(SaveAs) { uri -> + val file = downloading + downloading = null + if (uri != null && file != null) server.files.download(channelId, password, file, uri) + } + val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + if (uri != null) scope.launch { + runCatching { server.files.upload(channelId, password, path, uri) } + .onFailure { tell("Could not read the file: ${it.message}") } + } + } + + SubScreen(channelName, onBack = { if (path == "/") onBack() else path = parentOf(path) }, snackbar = snackbar, actions = { + IconButton(onClick = { creatingFolder = true }) { PackIcon("ADD_FOLDER", "New folder") } + IconButton(onClick = { picker.launch(arrayOf("*/*")) }) { PackIcon("UPLOAD", "Upload") } + IconButton(onClick = { reloads++ }) { PackIcon(listOf("FILE_REFRESH", "REFRESH"), "Refresh") } + }) { padding -> + Column(Modifier.padding(padding).fillMaxSize()) { + Row(Modifier.fillMaxWidth().padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically) { + IconButton(onClick = { path = parentOf(path) }, enabled = path != "/") { PackIcon("FILE_UP", "Up") } + Text(path, Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis, + style = MaterialTheme.typography.bodyMedium) + } + HorizontalDivider() + Box(Modifier.weight(1f).fillMaxWidth()) { + val list = files + when { + list == null -> CircularProgressIndicator(Modifier.align(Alignment.Center)) + list.isEmpty() -> Text(failure ?: "No files", Modifier.align(Alignment.Center).padding(24.dp), + color = if (failure != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant) + else -> LazyColumn { + items(list, key = { it.fullPath }) { file -> + FileRow(file, + onOpen = { + if (file.isDirectory) path = file.fullPath + "/" + else { downloading = file; saver.launch(file.name) } + }, + onRename = { renaming = file }, + onDelete = { deleting = file }) + } + } + } + } + if (transfers.isNotEmpty()) Transfers(transfers, server.files::cancel, server.files::clearFinished) + } + } + + if (creatingFolder) { + TextPrompt("New folder", "Name", "Create", onDismiss = { creatingFolder = false }, onConfirm = { name -> + creatingFolder = false + if (name.isNotBlank()) act { server.createDirectory(channelId, password, path + name.trim()) } + }) + } + renaming?.let { file -> + TextPrompt("Rename", "Name", "Rename", initial = file.name, onDismiss = { renaming = null }, onConfirm = { name -> + renaming = null + if (name.isNotBlank() && name != file.name) { + act { server.renameFile(channelId, password, file.fullPath, file.parentPath + name.trim()) } + } + }) + } + deleting?.let { file -> + AlertDialog( + onDismissRequest = { deleting = null }, + title = { Text("Delete ${file.name}?") }, + text = if (file.isDirectory) ({ Text("Everything in the folder goes with it.") }) else null, + confirmButton = { + TextButton(onClick = { + deleting = null + act { server.deleteFile(channelId, password, file.fullPath) } + }) { Text("Delete") } + }, + dismissButton = { TextButton(onClick = { deleting = null }) { Text("Cancel") } }, + ) + } +} + +private fun parentOf(path: String): String { + val trimmed = path.removeSuffix("/") + val slash = trimmed.lastIndexOf('/') + return if (slash <= 0) "/" else trimmed.substring(0, slash + 1) +} + +@Composable +private fun FileRow(file: RemoteFile, onOpen: () -> Unit, onRename: () -> Unit, onDelete: () -> Unit) { + val context = LocalContext.current + var menu by remember { mutableStateOf(false) } + val modified = if (file.lastModifiedEpochSec > 0) { + DateUtils.formatDateTime(context, file.lastModifiedEpochSec * 1000, + DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_ABBREV_MONTH) + } else null + ListItem( + headlineContent = { Text(file.name, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + supportingContent = { + Text(listOfNotNull(if (file.isDirectory) null else Formatter.formatShortFileSize(context, file.size), modified) + .joinToString(" · ")) + }, + leadingContent = { PackIcon(if (file.isDirectory) listOf("FOLDER") else listOf("FILE", "FILETRANSFER"), null) }, + trailingContent = { + Box { + IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "File options") } + DropdownMenu(menu, { menu = false }) { + if (!file.isDirectory) DropdownMenuItem({ Text("Download") }, onClick = { menu = false; onOpen() }) + DropdownMenuItem({ Text("Rename") }, onClick = { menu = false; onRename() }) + DropdownMenuItem({ Text("Delete") }, onClick = { menu = false; onDelete() }) + } + } + }, + modifier = Modifier.clickable(onClick = onOpen), + ) +} + +/** The transfers under way and done, newest last. */ +@Composable +private fun Transfers(rows: List, onCancel: (Long) -> Unit, onClear: () -> Unit) { + val context = LocalContext.current + Surface(tonalElevation = 3.dp) { + Column(Modifier.fillMaxWidth().heightIn(max = 220.dp)) { + Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) { + Text("Transfers", Modifier.weight(1f), style = MaterialTheme.typography.titleSmall) + if (rows.any { it.done }) TextButton(onClick = onClear) { Text("Clear finished") } + } + LazyColumn { + items(rows, key = { it.id }) { row -> + Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 4.dp, bottom = 4.dp), + verticalAlignment = Alignment.CenterVertically) { + PackIcon(if (row.upload) "UPLOAD" else "DOWNLOAD", null) + Column(Modifier.weight(1f).padding(horizontal = 12.dp)) { + Text(row.name, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium) + when (row.state) { + FileTransfer.State.PENDING, FileTransfer.State.ACTIVE -> + LinearProgressIndicator({ row.progress }, Modifier.fillMaxWidth().padding(vertical = 4.dp)) + else -> Text(status(row, context), style = MaterialTheme.typography.bodySmall, + color = if (row.state == FileTransfer.State.FAILED) MaterialTheme.colorScheme.error + else MaterialTheme.colorScheme.onSurfaceVariant) + } + } + if (!row.done) IconButton(onClick = { onCancel(row.id) }) { Icon(Icons.Default.Close, "Cancel") } + } + } + } + } + } +} + +private fun status(row: TransferRow, context: android.content.Context): String = when (row.state) { + FileTransfer.State.COMPLETED -> (if (row.upload) "Uploaded" else "Downloaded") + " · " + + Formatter.formatShortFileSize(context, row.total) + FileTransfer.State.CANCELLED -> "Cancelled" + else -> row.error ?: "Failed" +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/FindBar.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/FindBar.kt new file mode 100644 index 0000000..50febb9 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/FindBar.kt @@ -0,0 +1,190 @@ +package eu.lixko.ts3j.client.android.ui + +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.KeyboardArrowDown +import androidx.compose.material.icons.filled.KeyboardArrowUp +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material3.Checkbox +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextField +import androidx.compose.material3.TextFieldDefaults +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.Stable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.listSaver +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.isShiftPressed +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.type +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.TextFieldValue +import androidx.compose.ui.unit.dp +import eu.lixko.ts3j.client.gfx.IconKeys +import eu.lixko.ts3j.client.net.ClientStatus +import eu.lixko.ts3j.client.text.TextQuery + +/** What the find bar holds: the text, how to match it, and whether it is [open]. */ +@Stable +class FindState(text: String = "", flags: Int = 0) { + var open by mutableStateOf(false) + var input by mutableStateOf(TextFieldValue(text)) + var matchCase by mutableStateOf(flags and 1 != 0) + var wholeWord by mutableStateOf(flags and 2 != 0) + var regex by mutableStateOf(flags and 4 != 0) + /** Counts the times it was asked to show, for the field to take the focus each time. */ + var shown by mutableStateOf(0) + private set + /** Show only what matches. */ + var filter by mutableStateOf(flags and 8 != 0) + /** In the tree, find channels rather than clients. */ + var channels by mutableStateOf(flags and 16 != 0) + + /** What is typed, as it is to be matched; empty while the bar is closed. */ + val query: TextQuery + get() = if (open) TextQuery(input.text, matchCase, wholeWord, regex) else TextQuery.EMPTY + + /** [query], but nothing when it is not a valid regular expression. */ + val usable: TextQuery + get() = query.let { if (it.isInvalid) TextQuery.EMPTY else it } + + /** Opens the bar with what it holds selected, to be typed over. */ + fun show() { + input = input.copy(selection = TextRange(0, input.text.length)) + open = true + shown++ + } + + companion object { + val Saver = listSaver( + save = { + val flags = (if (it.matchCase) 1 else 0) or (if (it.wholeWord) 2 else 0) or (if (it.regex) 4 else 0) or + (if (it.filter) 8 else 0) or (if (it.channels) 16 else 0) + listOf(it.input.text, flags, it.open) + }, + restore = { FindState(it[0] as String, it[1] as Int).apply { open = it[2] as Boolean } }, + ) + } +} + +/** + * The find bar, in the place of the top bar: the field, where the view is among the matches, + * previous/next, and the options. Enter goes to the next match, Shift+Enter to the previous. + * + * @param inTree whether it finds in the tree, which offers finding channels instead of clients + * @param position the 1-based match the view is on, or 0 for none + * @param more whether there are more matches than [total] + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun FindBar(state: FindState, inTree: Boolean, position: Int, total: Int, more: Boolean, onStep: (Int) -> Unit) { + val focus = remember { FocusRequester() } + LaunchedEffect(state.shown) { focus.requestFocus() } + val query = state.query + TopAppBar( + expandedHeight = 48.dp, + navigationIcon = { IconButton(onClick = { state.open = false }) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Close") } }, + title = { + TextField( + state.input, { state.input = it }, + Modifier.focusRequester(focus).onPreviewKeyEvent { e -> + when { + e.key == Key.Enter -> { + if (e.type == KeyEventType.KeyDown) onStep(if (e.isShiftPressed) -1 else 1) + true + } + e.key == Key.Escape && e.type == KeyEventType.KeyDown -> { + state.open = false + true + } + else -> false + } + }, + placeholder = { + Text(if (!inTree) "Find" else if (state.channels) "Find channels" else "Find clients", maxLines = 1) + }, + leadingIcon = if (inTree) ({ + IconButton(onClick = { state.channels = !state.channels }) { + if (state.channels) PackIcon(IconKeys.channel(false, false, true).asList(), "Finding channels", size = 18.dp) + else PackIcon(IconKeys.client(ClientStatus.IDLE), "Finding clients", size = 18.dp) + } + }) else null, + trailingIcon = if (state.input.text.isNotEmpty()) ({ + IconButton(onClick = { state.input = TextFieldValue() }) { Icon(Icons.Filled.Close, "Clear", Modifier.size(18.dp)) } + }) else null, + isError = query.isInvalid, + singleLine = true, + textStyle = MaterialTheme.typography.bodyLarge, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), + keyboardActions = KeyboardActions(onSearch = { onStep(1) }), + colors = TextFieldDefaults.colors( + focusedContainerColor = Color.Transparent, + unfocusedContainerColor = Color.Transparent, + errorContainerColor = Color.Transparent, + focusedIndicatorColor = Color.Transparent, + unfocusedIndicatorColor = Color.Transparent, + ), + ) + }, + actions = { + Row(verticalAlignment = Alignment.CenterVertically) { + if (!query.isEmpty) { + Text( + if (query.isInvalid) "!" else "${if (position > 0) "$position/" else ""}$total${if (more) "+" else ""}", + Modifier.padding(horizontal = 4.dp), + color = if (query.isInvalid || total == 0) MaterialTheme.colorScheme.error + else MaterialTheme.colorScheme.onSurfaceVariant, + style = MaterialTheme.typography.labelMedium, + ) + } + val navigable = total > 1 || (total == 1 && position == 0) + IconButton(onClick = { onStep(-1) }, enabled = navigable) { Icon(Icons.Filled.KeyboardArrowUp, "Previous") } + IconButton(onClick = { onStep(1) }, enabled = navigable) { Icon(Icons.Filled.KeyboardArrowDown, "Next") } + FindOptions(state) + } + }, + ) +} + +@Composable +private fun FindOptions(state: FindState) { + var open by remember { mutableStateOf(false) } + IconButton(onClick = { open = true }) { Icon(Icons.Filled.MoreVert, "Options") } + DropdownMenu(open, onDismissRequest = { open = false }) { + @Composable + fun option(label: String, checked: Boolean, set: (Boolean) -> Unit) = DropdownMenuItem( + text = { Text(label) }, + onClick = { set(!checked) }, + leadingIcon = { Checkbox(checked, set) }, + ) + option("Only matches", state.filter) { state.filter = it } + option("Match case", state.matchCase) { state.matchCase = it } + option("Whole words", state.wholeWord) { state.wholeWord = it } + option("Regular expression", state.regex) { state.regex = it } + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/HostButton.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/HostButton.kt new file mode 100644 index 0000000..a40c504 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/HostButton.kt @@ -0,0 +1,64 @@ +package eu.lixko.ts3j.client.android.ui + +import androidx.compose.foundation.Image +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.produceState +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import eu.lixko.ts3j.client.android.Picture +import eu.lixko.ts3j.client.android.WebPictures +import eu.lixko.ts3j.client.net.HostButton + +/** + * The server's host button in the top bar: its own picture fitted to the bar's icons, or + * the pack's host button icon while there is none (yet). + */ +@Composable +fun HostButtonAction(button: HostButton, onOpen: (String) -> Unit) { + val label = button.tooltip.ifEmpty { button.url }.ifEmpty { null } + val picture = hostPicture(button.gfxUrl) + Box( + Modifier + .fillMaxHeight() + .clickable(enabled = button.url.isNotEmpty()) { onOpen(button.url) } + .padding(horizontal = 12.dp), + contentAlignment = Alignment.Center, + ) { + if (picture == null) { + PackIcon("HOSTER_BUTTON", label) + } else { + Image( + rememberPicturePainter(picture), + label, + Modifier + .widthIn(max = 24.dp * MAX_ASPECT) + .height(24.dp) + .aspectRatio(picture.width.toFloat() / picture.height.coerceAtLeast(1)), + ) + } + } +} + +@Composable +private fun hostPicture(url: String): Picture? { + val pictures = LocalWebPictures.current + if (pictures == null || url.isEmpty()) return null + val version by pictures.version.collectAsStateWithLifecycle() + val state by produceState(WebPictures.State.Loading, url, version) { + value = pictures.state(url) + } + return (state as? WebPictures.State.Shown)?.picture +} + +/** Keeps a banner-shaped picture from crowding out the server's name. */ +private const val MAX_ASPECT = 6 diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/IdentitiesScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/IdentitiesScreen.kt new file mode 100644 index 0000000..a0d1fc6 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/IdentitiesScreen.kt @@ -0,0 +1,282 @@ +package eu.lixko.ts3j.client.android.ui + +import android.content.ClipData +import android.content.ClipboardManager +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import eu.lixko.ts3j.client.android.IdentityInfo +import eu.lixko.ts3j.client.android.IdentityManager +import kotlinx.coroutines.launch + +/** Beyond this a search takes years; TeamSpeak's own dialog stops there too. */ +private const val MAX_SECURITY_LEVEL = 40 + +/** + * The identities a server knows this client by, as TeamSpeak's Tools → Identities + * manages them, with each identity's own page. + */ +@Composable +fun IdentitiesScreen(manager: IdentityManager, onBack: () -> Unit) { + var editing by rememberSaveable { mutableStateOf(null) } + editing?.let { id -> return IdentityScreen(manager, id, onBack = { editing = null }) } + + val identities by manager.all.collectAsStateWithLifecycle() + val scope = rememberCoroutineScope() + var menu by remember { mutableStateOf(false) } + var creating by remember { mutableStateOf(false) } + var busy by remember { mutableStateOf(false) } + var message by remember { mutableStateOf(null) } + + fun work(failure: String, block: suspend () -> String?) { + busy = true + scope.launch { + message = try { + block() + } catch (e: Exception) { + "$failure: ${e.message ?: e}" + } + busy = false + } + } + + val fileImporter = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + if (uri != null) work("That file is not a TeamSpeak identity") { + editing = manager.importFile(uri).id + null + } + } + val dbImporter = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + if (uri != null) work("That file is not a TeamSpeak 3 settings.db") { + val r = manager.importFromTeamSpeak(uri) + if (r.identities() == 0) "That file holds no identities." + else "Imported ${r.identitiesAdded()} of ${r.identities()} identities." + } + } + + SubScreen("Identities", onBack, actions = { + IconButton(onClick = { creating = true }, enabled = !busy) { PackIcon("IDENTITY_ADD", "New identity") } + Box { + IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "More") } + DropdownMenu(menu, { menu = false }) { + DropdownMenuItem({ Text("Import identity file") }, onClick = { + menu = false + fileImporter.launch(arrayOf("*/*")) + }) + DropdownMenuItem({ Text("Import from TeamSpeak 3") }, onClick = { + menu = false + dbImporter.launch(arrayOf("*/*")) + }) + } + } + }) { padding -> + LazyColumn(Modifier.padding(padding)) { + if (busy) item { LinearProgressIndicator(Modifier.fillMaxWidth().padding(horizontal = 16.dp)) } + message?.let { item { Hint(it) } } + if (identities.isEmpty()) { + item { + Hint("No identities. One is created on the first connect.") + } + } + items(identities, key = { it.id }) { identity -> + ListItem( + headlineContent = { Text(identity.name, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + supportingContent = { + Text("Security level ${identity.securityLevel}", maxLines = 1) + }, + trailingContent = if (identity.isDefault) ({ PackIcon("IDENTITY_DEFAULT", "Default") }) else null, + modifier = Modifier.clickable { editing = identity.id }, + ) + } + } + } + + if (creating) { + NewIdentityDialog(onDismiss = { creating = false }) { name -> + creating = false + work("Could not create the identity") { + editing = manager.generate(name).id + null + } + } + } +} + +/** One identity: its name, whether it is the default, its security level and unique ID. */ +@Composable +private fun IdentityScreen(manager: IdentityManager, id: String, onBack: () -> Unit) { + val identities by manager.all.collectAsStateWithLifecycle() + val improving by manager.improving.collectAsStateWithLifecycle() + val identity = identities.firstOrNull { it.id == id } + if (identity == null) { + LaunchedEffect(Unit) { onBack() } + return + } + val scope = rememberCoroutineScope() + var name by rememberSaveable(id) { mutableStateOf(identity.name) } + var nickname by rememberSaveable(id) { mutableStateOf(identity.nickname) } + var phonetic by rememberSaveable(id) { mutableStateOf(identity.phoneticNickname) } + var removing by remember { mutableStateOf(false) } + var raising by remember { mutableStateOf(false) } + var message by remember { mutableStateOf(null) } + val leave = { + val trimmed = name.trim() + if (trimmed.isNotEmpty() && trimmed != identity.name) manager.rename(id, trimmed) + if (nickname.trim() != identity.nickname || phonetic.trim() != identity.phoneticNickname) { + manager.setNicknames(id, nickname.trim(), phonetic.trim()) + } + onBack() + } + val exporter = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/octet-stream")) { uri -> + if (uri != null) scope.launch { + message = runCatching { manager.export(id, uri) }.fold( + { "Exported." }, + { "Could not export: ${it.message ?: it}" }, + ) + } + } + val mine = improving?.takeIf { it.id == id } + + SubScreen(identity.name, leave, actions = { + IconButton(onClick = { exporter.launch(fileName(name.ifBlank { identity.name })) }) { + PackIcon("IDENTITY_EXPORT", "Export") + } + IconButton(onClick = { removing = true }) { PackIcon("DELETE", "Remove") } + }) { padding -> + Column(Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(vertical = 8.dp)) { + OutlinedTextField(name, { name = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp), + label = { Text("Name") }, singleLine = true, isError = name.isBlank()) + OutlinedTextField(nickname, { nickname = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(top = 8.dp), + label = { Text("Nickname") }, placeholder = { Text("Global nickname") }, singleLine = true) + OutlinedTextField(phonetic, { phonetic = it }, Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), + label = { Text("Phonetic nickname") }, singleLine = true) + message?.let { Hint(it) } + + Section("Use") + if (identity.isDefault) { + Hint("Default identity") + } else { + LinkRow("Make default", null, "IDENTITY_DEFAULT") { + manager.setDefault(id) + } + } + + Section("Security level") + if (mine != null) { + ListItem( + headlineContent = { Text("Improving to ${mine.target}: reached ${mine.reached}") }, + supportingContent = { LinearProgressIndicator(Modifier.fillMaxWidth().padding(top = 8.dp)) }, + trailingContent = { TextButton(onClick = manager::stopImproving) { Text("Stop") } }, + ) + } else { + LinkRow("Level ${identity.securityLevel}", + if (improving != null) "Another identity is being improved" else "Improve", + "SECURITY") { if (improving == null) raising = true } + } + + Section("Details") + val context = LocalContext.current + LinkRow("Unique ID", identity.uniqueId) { + // The system confirms the copy itself. + context.getSystemService(ClipboardManager::class.java) + .setPrimaryClip(ClipData.newPlainText("Unique ID", identity.uniqueId)) + } + } + } + + if (raising) { + LevelDialog(identity, onDismiss = { raising = false }) { target -> + raising = false + manager.improve(id, target) + } + } + if (removing) { + AlertDialog( + onDismissRequest = { removing = false }, + title = { Text("Remove ${identity.name}?") }, + text = { + Text("Server groups and permissions tied to it are lost. Export it first to keep it.") + }, + confirmButton = { + TextButton(onClick = { + removing = false + manager.remove(id) + }) { Text("Remove") } + }, + dismissButton = { TextButton(onClick = { removing = false }) { Text("Cancel") } }, + ) + } +} + +@Composable +private fun NewIdentityDialog(onDismiss: () -> Unit, onConfirm: (String) -> Unit) { + var name by remember { mutableStateOf("") } + AlertDialog( + onDismissRequest = onDismiss, + title = { Text("New identity") }, + text = { + OutlinedTextField(name, { name = it }, Modifier.fillMaxWidth(), label = { Text("Name") }, singleLine = true) + }, + confirmButton = { TextButton(onClick = { onConfirm(name.trim()) }, enabled = name.isNotBlank()) { Text("Create") } }, + dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + ) +} + +@Composable +private fun LevelDialog(identity: IdentityInfo, onDismiss: () -> Unit, onConfirm: (Int) -> Unit) { + var text by remember { mutableStateOf((identity.securityLevel + 1).toString()) } + val level = text.trim().toIntOrNull()?.takeIf { it in identity.securityLevel + 1..MAX_SECURITY_LEVEL } + AlertDialog( + onDismissRequest = onDismiss, + title = { Text("Improve security level") }, + text = { + Column { + Text("Current level: ${identity.securityLevel}", style = MaterialTheme.typography.bodyMedium) + OutlinedTextField(text, { text = it }, Modifier.fillMaxWidth().padding(top = 8.dp), + label = { Text("Target level") }, singleLine = true, isError = level == null, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)) + } + }, + confirmButton = { TextButton(onClick = { level?.let(onConfirm) }, enabled = level != null) { Text("Start") } }, + dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + ) +} + +private fun fileName(name: String) = name.replace(Regex("[^\\w.-]+"), "_") + ".ini" diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Moderation.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Moderation.kt new file mode 100644 index 0000000..d732ec9 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Moderation.kt @@ -0,0 +1,225 @@ +package eu.lixko.ts3j.client.android.ui + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Checkbox +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import eu.lixko.ts3j.client.android.ClientItem +import eu.lixko.ts3j.client.android.ServerController +import eu.lixko.ts3j.client.net.GroupChoice +import eu.lixko.ts3j.client.net.TeamspeakConnection +import eu.lixko.ts3j.client.net.ban.BanRule +import eu.lixko.ts3j.client.net.ban.BanUnit + +/** Asks to confirm a kick, with an optional reason. */ +@Composable +fun KickPrompt(title: String, onDismiss: () -> Unit, onKick: (String) -> Unit) { + var reason by remember { mutableStateOf("") } + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(title) }, + text = { LimitedField(reason, { reason = it }, "Reason", TeamspeakConnection.KICK_REASON_LIMIT) }, + confirmButton = { TextButton(onClick = { onKick(reason.trim()) }) { Text("Kick") } }, + dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + ) +} + +/** Asks for a ban's reason and length. */ +@Composable +fun BanPrompt(name: String, maxSeconds: Long, onDismiss: () -> Unit, onBan: (seconds: Long, reason: String) -> Unit) { + var reason by remember { mutableStateOf("") } + val duration = remember { BanDurationState(DEFAULT_BAN_SECONDS) } + AlertDialog( + onDismissRequest = onDismiss, + title = { Text("Ban $name") }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + LimitedField(reason, { reason = it }, "Reason", BanRule.REASON_LIMIT) + BanDurationField(duration, maxSeconds) + } + }, + confirmButton = { + TextButton(onClick = { onBan(duration.seconds, reason.trim()) }, enabled = duration.valid) { Text("Ban") } + }, + dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + ) +} + +/** Thirty minutes, as the official client starts its ban dialog. */ +internal const val DEFAULT_BAN_SECONDS = 30 * 60L + +/** A one-line field that takes no more than [limit] characters, counting them as they come. */ +@Composable +internal fun LimitedField(value: String, onChange: (String) -> Unit, label: String, limit: Int, modifier: Modifier = Modifier) { + OutlinedTextField( + value, { onChange(it.take(limit)) }, + modifier.fillMaxWidth(), + label = { Text(label) }, + singleLine = true, + supportingText = { Text("${value.length}/$limit", Modifier.fillMaxWidth(), textAlign = TextAlign.End) }, + ) +} + +/** A ban's length as typed: an amount of a [BanUnit]. */ +internal class BanDurationState(seconds: Long) { + var unit by mutableStateOf(BanUnit.largestFor(seconds)) + var amount by mutableStateOf(BanUnit.largestFor(seconds).amountOf(seconds).takeIf { it > 0 }?.toString() ?: "30") + + val valid: Boolean get() = unit == BanUnit.PERMANENT || (amount.toLongOrNull() ?: 0) > 0 + + /** The length in seconds; 0 for permanent. */ + val seconds: Long get() = unit.toSeconds(amount.toLongOrNull() ?: 0) + + fun set(seconds: Long) { + unit = BanUnit.largestFor(seconds) + if (unit != BanUnit.PERMANENT) amount = unit.amountOf(seconds).toString() + } +} + +/** The amount, its unit, and a jump to the longest ban the server lets us hand out. */ +@Composable +internal fun BanDurationField(state: BanDurationState, maxSeconds: Long, modifier: Modifier = Modifier) { + var units by remember { mutableStateOf(false) } + Row(modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField( + if (state.unit == BanUnit.PERMANENT) "" else state.amount, + { text -> state.amount = text.filter(Char::isDigit).take(9) }, + Modifier.width(120.dp), + enabled = state.unit != BanUnit.PERMANENT, + label = { Text("Duration") }, + singleLine = true, + isError = !state.valid, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + ) + Box(Modifier.weight(1f)) { + OutlinedButton(onClick = { units = true }, Modifier.fillMaxWidth()) { Text(state.unit.label()) } + DropdownMenu(units, { units = false }) { + for (unit in BanUnit.entries) { + DropdownMenuItem({ Text(unit.label()) }, onClick = { units = false; state.unit = unit }) + } + } + } + if (maxSeconds != 0L) TextButton(onClick = { state.set(maxSeconds) }) { Text("Max") } + } +} + +/** + * A client's groups to tick: several server groups, or with [single] the one channel group. + * Groups we have no power over show greyed out; a change shows once the server made it. + */ +@Composable +fun GroupsDialog( + title: String, + choices: List, + single: Boolean, + onDismiss: () -> Unit, + onChange: (groupId: Int, assign: Boolean) -> Unit, +) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(title) }, + text = { + LazyColumn { + items(choices, key = { it.group().id }) { choice -> + val group = choice.group() + // A client always has one channel group: picking another is the only change. + val changeable = choice.allowed() && !(single && choice.assigned()) + val toggle = { if (changeable) onChange(group.id, !choice.assigned()) } + Row( + Modifier.fillMaxWidth() + .clickable(enabled = changeable, onClick = toggle) + .alpha(if (choice.allowed()) 1f else 0.38f) + .padding(vertical = 2.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + if (single) { + RadioButton(choice.assigned(), onClick = toggle, enabled = choice.allowed()) + } else { + Checkbox(choice.assigned(), onCheckedChange = { toggle() }, enabled = choice.allowed()) + } + Box(Modifier.width(24.dp), contentAlignment = Alignment.Center) { + if (group.iconId != 0L) ServerIcon(group.iconId) + } + Text(group.name, Modifier.padding(start = 8.dp)) + } + } + } + }, + confirmButton = { TextButton(onClick = onDismiss) { Text("Close") } }, + ) +} + +/** The kicks, the ban and the groups of [client], as far as we may use them; [onDone] once one went out. */ +@Composable +fun ClientModeration(server: ServerController, client: ClientItem, onDone: () -> Unit) { + var kick by remember { mutableStateOf(null) } + var banning by remember { mutableStateOf(false) } + var groups by remember { mutableStateOf(null) } + val serverGroups = remember(client) { server.serverGroupChoices(client.id) } + val channelGroups = remember(client) { server.channelGroupChoices(client.id) } + + if (!client.self) { + if (server.canKickFromChannel) Action("KICK_FROM_CHANNEL", "Kick from channel") { kick = false } + if (server.canKickFromServer) Action("KICK_FROM_SERVER", "Kick from server") { kick = true } + if (server.canBanClients) Action("BAN_CLIENT", "Ban") { banning = true } + } + if (serverGroups.any { it.allowed() }) Action("PERMISSIONS_SERVER_GROUPS", "Server groups") { groups = true } + if (channelGroups.any { it.allowed() && !it.assigned() }) { + Action("PERMISSIONS_CHANNEL_GROUPS", "Channel group") { groups = false } + } + + kick?.let { fromServer -> + KickPrompt( + if (fromServer) "Kick ${client.name} from the server?" else "Kick ${client.name} from the channel?", + onDismiss = { kick = null }, + ) { reason -> + kick = null + if (fromServer) server.kickFromServer(client.id, reason) else server.kickFromChannel(client.id, reason) + onDone() + } + } + if (banning) { + BanPrompt(client.name, server.maxBanSeconds, onDismiss = { banning = false }) { seconds, reason -> + banning = false + server.ban(client.id, seconds, reason) + onDone() + } + } + groups?.let { ofServer -> + GroupsDialog( + if (ofServer) "Server groups" else "Channel group", + if (ofServer) serverGroups else channelGroups, + single = !ofServer, + onDismiss = { groups = null }, + ) { groupId, assign -> + if (ofServer) server.setServerGroup(client.id, groupId, assign) else server.setChannelGroup(client.id, groupId) + } + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/MyTeamSpeakScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/MyTeamSpeakScreen.kt new file mode 100644 index 0000000..da73fac --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/MyTeamSpeakScreen.kt @@ -0,0 +1,247 @@ +package eu.lixko.ts3j.client.android.ui + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material3.Button +import androidx.compose.material3.Checkbox +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import eu.lixko.ts3j.client.android.SessionController +import eu.lixko.ts3j.client.myts.AccountInfo +import eu.lixko.ts3j.client.myts.MyTeamSpeak +import eu.lixko.ts3j.client.myts.MyTsException +import eu.lixko.ts3j.client.teamspeak.SyncItem +import kotlinx.coroutines.launch +import java.io.IOException +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.time.format.FormatStyle + +private data class ItemRow(val item: SyncItem, val imported: Boolean, val selected: Boolean) + +/** + * The myTeamSpeak account: sign in and out, and pick what the account synchronises to + * import. Signing in lasts until signing out; the password itself is not kept. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) { + val login = vm.myTeamSpeak + val scope = rememberCoroutineScope() + var signedIn by remember { mutableStateOf(login.isSignedIn) } + var busy by remember { mutableStateOf(false) } + var message by remember { mutableStateOf(null) } + var error by remember { mutableStateOf(false) } + var email by remember { mutableStateOf("") } + var password by remember { mutableStateOf("") } + var info by remember { mutableStateOf(null) } + var all by remember { mutableStateOf(emptyList()) } + var rows by remember { mutableStateOf(emptyList()) } + BackHandler(onBack = onBack) + + fun show(account: MyTeamSpeak.Account) { + info = account.info() + all = account.items() + rows = all.filter { it !is SyncItem.Folder }.map { + val imported = vm.isImported(it) + ItemRow(it, imported, !imported) + } + message = if (rows.isEmpty()) "The account holds no bookmarks or identities." else null + error = false + } + + fun work(block: suspend () -> Unit) { + busy = true + message = null + scope.launch { + try { + block() + } catch (e: MyTsException) { + message = e.message + error = true + } catch (e: IOException) { + message = "Could not reach myTeamSpeak: ${e.message}" + error = true + } + // A sign-in the server no longer takes has signed out. + signedIn = login.isSignedIn + busy = false + } + } + + LaunchedEffect(Unit) { + if (signedIn) work { show(vm.fetchMyTeamSpeak()) } + } + + Scaffold( + topBar = { + TopAppBar( + title = { Text("myTeamSpeak") }, + navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } }, + actions = { + if (signedIn) { + IconButton(onClick = { work { show(vm.fetchMyTeamSpeak()) } }, enabled = !busy) { + PackIcon("REFRESH", "Refresh") + } + } + }, + ) + }, + ) { padding -> + LazyColumn( + Modifier.padding(padding).imePadding(), + contentPadding = PaddingValues(vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + if (busy) item { LinearProgressIndicator(Modifier.fillMaxWidth().padding(horizontal = 16.dp)) } + if (!signedIn) { + item { + Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text("Sign in to bring over the bookmarks and identities your account synchronises. " + + "The app stays signed in; your password itself is not kept.") + OutlinedTextField(email, { email = it }, Modifier.fillMaxWidth(), label = { Text("Email") }, + singleLine = true, enabled = !busy, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email)) + OutlinedTextField(password, { password = it }, Modifier.fillMaxWidth(), label = { Text("Password") }, + singleLine = true, enabled = !busy, visualTransformation = PasswordVisualTransformation(), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)) + Button( + onClick = { + work { + show(vm.signInMyTeamSpeak(email.trim(), password)) + password = "" + } + }, + enabled = !busy && email.isNotBlank() && password.isNotEmpty(), + ) { Text("Sign in") } + } + } + } else { + item { + Row(Modifier.padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text("Signed in as ${login.username()}", style = MaterialTheme.typography.titleMedium) + Text(login.email(), style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant) + } + OutlinedButton(onClick = { + scope.launch { vm.signOutMyTeamSpeak() } + signedIn = false + rows = emptyList() + all = emptyList() + info = null + message = null + }) { Text("Sign out") } + } + } + info?.let { details -> + item { + Column(Modifier.padding(horizontal = 16.dp)) { + if (details.userId().isNotEmpty()) Detail("ID", details.userId()) + if (details.uuid().isNotEmpty()) Detail("UUID", details.uuid()) + details.created()?.let { Detail("Created", dateFormat.format(it)) } + } + } + } + if (rows.isNotEmpty()) { + item { + Text("Synchronised by the account", Modifier.padding(start = 16.dp, top = 16.dp), + style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary) + } + } + items(rows, key = { it.item.uuid() }) { row -> + val toggle = { rows = rows.map { if (it === row) it.copy(selected = !it.selected) else it } } + ListItem( + headlineContent = { Text(name(row.item), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + supportingContent = { Text(details(row.item), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + leadingContent = { Checkbox(row.selected, { toggle() }) }, + trailingContent = if (row.imported) ({ Text("Imported", style = MaterialTheme.typography.labelMedium) }) else null, + modifier = Modifier.clickable(onClick = toggle), + ) + } + if (rows.isNotEmpty()) { + item { + Button( + onClick = { + work { + val r = vm.importMyTeamSpeak(all, rows.filter { it.selected }.map { it.item }) + rows = rows.map { it.copy(imported = vm.isImported(it.item), selected = false) } + message = "Imported ${count(r.identitiesAdded(), "identity", "identities")} and " + + "${count(r.bookmarksAdded(), "bookmark", "bookmarks")}." + } + }, + enabled = !busy && rows.any { it.selected }, + modifier = Modifier.padding(horizontal = 16.dp), + ) { Text("Import selected") } + } + } + } + message?.let { text -> + item { + Text(text, Modifier.padding(horizontal = 16.dp), + color = if (error) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurface) + } + } + } + } +} + +private val dateFormat = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withZone(ZoneId.systemDefault()) + +/** A labelled value that can be selected and copied. */ +@Composable +private fun Detail(label: String, value: String) { + Column(Modifier.padding(top = 8.dp)) { + Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + SelectionContainer { Text(value, style = MaterialTheme.typography.bodyMedium) } + } +} + +private fun name(item: SyncItem) = when (item) { + is SyncItem.Bookmark -> item.name().ifBlank { item.address() } + is SyncItem.Identity -> "Identity: ${item.name()}" + else -> "" +} + +private fun details(item: SyncItem) = when (item) { + is SyncItem.Bookmark -> "${item.address()}:${item.port()}" + is SyncItem.Identity -> item.nickname() + else -> "" +} + +private fun count(n: Int, one: String, many: String) = "$n ${if (n == 1) one else many}" diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/NetworkSettingsScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/NetworkSettingsScreen.kt new file mode 100644 index 0000000..6163510 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/NetworkSettingsScreen.kt @@ -0,0 +1,88 @@ +package eu.lixko.ts3j.client.android.ui + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import eu.lixko.ts3j.client.android.SessionController +import eu.lixko.ts3j.client.config.Settings +import kotlin.math.abs +import kotlin.math.roundToInt + +private const val MIN_BITRATE_KBITS = 8f +private const val MAX_BITRATE_KBITS = 160f + +/** What voice costs and survives on the wire: the encoder, duplicate packets and receive buffering. */ +@Composable +fun NetworkSettingsScreen(vm: SessionController, onBack: () -> Unit) { + val settings = vm.settings + fun change(edit: Settings.() -> Unit) { + settings.edit() + vm.applySettings() + } + var vbr by remember { mutableStateOf(settings.vbr) } + var fec by remember { mutableStateOf(settings.fec) } + var music by remember { mutableStateOf(settings.music) } + var redundancy by remember { mutableStateOf(settings.redundancyDelay) } + var copies by remember { mutableStateOf(settings.redundancyCopies) } + var receiveBuffer by remember { mutableStateOf(settings.receiveBuffer) } + + SubScreen("Network", onBack) { padding -> + Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { + Section("Encoder") + Level("Bitrate", settings.bitrate / 1000f, MIN_BITRATE_KBITS..MAX_BITRATE_KBITS, { "${it.roundToInt()} kbit/s" }) { + change { bitrate = it.roundToInt() * 1000 } + } + Toggle("Variable bitrate (VBR)", vbr) { + vbr = it + change { this.vbr = it } + } + Toggle("Forward error correction (FEC)", fec) { + fec = it + change { this.fec = it } + } + Level("Complexity", settings.complexity.toFloat(), 0f..10f, { "${it.roundToInt()}" }, steps = 9) { + change { complexity = it.roundToInt() } + } + Toggle("Music codec (stereo, higher fidelity)", music) { + music = it + change { this.music = it } + } + + Section("Redundancy") + ChoiceLevel("Delay", Settings.REDUNDANCY_DELAYS, redundancy) { + redundancy = it + change { redundancyDelay = it } + } + if (redundancy > 0) { + Level("Copies", copies.toFloat(), 1f..Settings.MAX_REDUNDANCY_COPIES.toFloat(), { "${it.roundToInt()}" }, + steps = Settings.MAX_REDUNDANCY_COPIES - 2) { + copies = it.roundToInt() + change { redundancyCopies = copies } + } + } + + Section("Receive") + ChoiceLevel("Extra buffering", Settings.RECEIVE_BUFFERS, receiveBuffer) { + receiveBuffer = it + change { this.receiveBuffer = it } + } + } + } +} + +/** A slider stepping through the millisecond [choices], starting at the one nearest [ms]. */ +@Composable +private fun ChoiceLevel(label: String, choices: IntArray, ms: Int, onDone: (Int) -> Unit) { + val index = choices.indices.minBy { abs(choices[it] - ms) } + fun at(position: Float) = choices[position.roundToInt()] + Level(label, index.toFloat(), 0f..(choices.size - 1).toFloat(), { at(it).let { v -> if (v == 0) "Off" else "$v ms" } }, + steps = choices.size - 2) { onDone(at(it)) } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/PackIcon.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/PackIcon.kt new file mode 100644 index 0000000..2e1c70d --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/PackIcon.kt @@ -0,0 +1,42 @@ +package eu.lixko.ts3j.client.android.ui + +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.size +import androidx.compose.material3.LocalContentColor +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import eu.lixko.ts3j.client.android.IconTheme + +val LocalIconTheme = staticCompositionLocalOf { error("No icon theme provided") } + +/** An icon of the active pack, named by its TeamSpeak key; art in the text colour takes [LocalContentColor]. */ +@Composable +fun PackIcon(key: String, contentDescription: String?, modifier: Modifier = Modifier, size: Dp = 24.dp) = + PackIcon(listOf(key), contentDescription, modifier, size) + +/** The first of [keys] the pack has, for icons packs need not ship in every variant. */ +@Composable +fun PackIcon(keys: List, contentDescription: String?, modifier: Modifier = Modifier, size: Dp = 24.dp) { + val theme = LocalIconTheme.current + val active by theme.active.collectAsStateWithLifecycle() + val pixels = with(LocalDensity.current) { size.roundToPx() } + val color = LocalContentColor.current + val rgb = color.copy(alpha = 1f).toArgb() + val bitmap = remember(keys, pixels, rgb, active) { theme.render(keys, pixels, rgb)?.asImageBitmap() } + if (bitmap == null) { + Spacer(modifier.size(size)) + } else { + // Disabled controls fade their content colour; the pack's own colours fade with it. + Image(bitmap, contentDescription, modifier.size(size), alpha = color.alpha) + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/PictureViewer.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/PictureViewer.kt new file mode 100644 index 0000000..0728a70 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/PictureViewer.kt @@ -0,0 +1,220 @@ +package eu.lixko.ts3j.client.android.ui + +import android.content.ClipData +import android.content.ClipboardManager +import android.widget.Toast +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.gestures.detectTransformGestures +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.produceState +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import eu.lixko.ts3j.client.android.Picture +import eu.lixko.ts3j.client.android.SavedPictures +import eu.lixko.ts3j.client.android.ServerController +import eu.lixko.ts3j.client.android.decodePicture +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** A picture to open full size. */ +class ViewedPicture( + /** What to call it when saved, without an extension. */ + val name: String, + /** Where it is on the web; null for an avatar. */ + val url: String? = null, + /** Follows the link it sits in; null when it sits in none. */ + val openLink: (() -> Unit)? = null, + /** Our own avatar, which there is no taking. */ + val ownAvatar: Boolean = false, + /** Its file; null when it is not there. */ + val read: suspend () -> ByteArray?, +) + +/** Opens a picture full size; null where nothing can. */ +val LocalPictureViewer = staticCompositionLocalOf<((ViewedPicture) -> Unit)?> { null } + +/** Lets [content] open pictures full size, over everything, with [server] to take one as our avatar on. */ +@Composable +fun PictureViewerHost(server: ServerController, content: @Composable () -> Unit) { + var viewed by remember { mutableStateOf(null) } + CompositionLocalProvider(LocalPictureViewer provides { viewed = it }, content = content) + val context = LocalContext.current + viewed?.let { picture -> + PictureViewer( + picture, + onSteal = if (picture.ownAvatar) null else { data -> + val error = server.setAvatar(data) + Toast.makeText(context, error ?: "Avatar set.", Toast.LENGTH_SHORT).show() + }, + onDismiss = { viewed = null }, + ) + } +} + +/** A name to save the picture at [url] under: its file's, or "picture" when it has none. */ +fun pictureName(url: String): String = + url.substringBefore('?').substringBefore('#').trimEnd('/').substringAfterLast('/') + .substringBeforeLast('.').ifBlank { "picture" } + +/** The picture on black, filling the screen; pinch or double-tap to zoom, tap to hide the bar. */ +@Composable +private fun PictureViewer( + picture: ViewedPicture, + /** Takes the picture as our avatar; null when it cannot be. */ + onSteal: (suspend (ByteArray) -> Unit)?, + onDismiss: () -> Unit, +) { + val state by produceState(null, picture) { + val data = picture.read() + value = Shown(data, data?.let { withContext(Dispatchers.Default) { decodePicture(it, MAX_PX) } }) + } + val data = state?.data + var bar by remember { mutableStateOf(true) } + var scale by remember { mutableFloatStateOf(1f) } + var offset by remember { mutableStateOf(Offset.Zero) } + var size by remember { mutableStateOf(IntSize.Zero) } + fun panTo(target: Offset) { + val maxX = size.width * (scale - 1) / 2 + val maxY = size.height * (scale - 1) / 2 + offset = Offset(target.x.coerceIn(-maxX, maxX), target.y.coerceIn(-maxY, maxY)) + } + + Dialog(onDismiss, DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) { + Box( + Modifier.fillMaxSize().background(Color.Black).onSizeChanged { size = it } + .pointerInput(Unit) { + detectTapGestures( + onTap = { bar = !bar }, + onDoubleTap = { scale = if (scale > 1f) 1f else DOUBLE_TAP_SCALE; panTo(Offset.Zero) }, + ) + } + .pointerInput(Unit) { + detectTransformGestures { _, pan, zoom, _ -> + scale = (scale * zoom).coerceIn(1f, MAX_SCALE) + panTo(offset + pan) + } + }, + contentAlignment = Alignment.Center, + ) { + val shown = state?.picture + when { + state == null -> PackIcon("LOADING_IMAGE", "Loading picture") + shown == null -> PackIcon("BROKEN_IMAGE", "Broken picture") + else -> Image( + rememberPicturePainter(shown), null, + Modifier.fillMaxSize().graphicsLayer { + scaleX = scale + scaleY = scale + translationX = offset.x + translationY = offset.y + }, + contentScale = ContentScale.Fit, + ) + } + if (bar) { + CompositionLocalProvider(LocalContentColor provides Color.White) { + Bar(picture, data, onSteal, onDismiss, Modifier.align(Alignment.TopCenter)) + } + } + } + } +} + +@Composable +private fun Bar( + picture: ViewedPicture, + data: ByteArray?, + onSteal: (suspend (ByteArray) -> Unit)?, + onDismiss: () -> Unit, + modifier: Modifier, +) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + var menu by remember { mutableStateOf(false) } + Row( + modifier.fillMaxWidth() + .background(Brush.verticalGradient(listOf(Color.Black.copy(alpha = 0.6f), Color.Transparent))) + .statusBarsPadding(), + verticalAlignment = Alignment.CenterVertically, + ) { + IconButton(onClick = onDismiss) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } + Box(Modifier.weight(1f)) + Box { + IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "Picture options") } + DropdownMenu(menu, onDismissRequest = { menu = false }) { + DropdownMenuItem({ Text("Save") }, enabled = data != null, onClick = { + menu = false + val bytes = data ?: return@DropdownMenuItem + scope.launch { + val saved = SavedPictures.save(context, picture.name, bytes) + Toast.makeText(context, if (saved) "Saved." else "Could not save.", Toast.LENGTH_SHORT).show() + } + }) + if (onSteal != null) { + DropdownMenuItem({ Text("Steal for avatar") }, enabled = data != null, onClick = { + menu = false + val bytes = data ?: return@DropdownMenuItem + scope.launch { onSteal(bytes) } + }) + } + picture.url?.let { url -> + DropdownMenuItem({ Text("Copy URL") }, onClick = { + menu = false + context.getSystemService(ClipboardManager::class.java) + .setPrimaryClip(ClipData.newPlainText("URL", url)) + }) + } + picture.openLink?.let { open -> + DropdownMenuItem({ Text("Open link") }, onClick = { + menu = false + onDismiss() + open() + }) + } + } + } + } +} + +/** The picture's file, and the picture when the file is one; both null when it is not there. */ +private class Shown(val data: ByteArray?, val picture: Picture?) + +private const val MAX_PX = 4096 +private const val MAX_SCALE = 8f +private const val DOUBLE_TAP_SCALE = 2.5f diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/PushToTalk.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/PushToTalk.kt new file mode 100644 index 0000000..86ef61d --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/PushToTalk.kt @@ -0,0 +1,95 @@ +package eu.lixko.ts3j.client.android.ui + +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import eu.lixko.ts3j.client.android.ServerController +import eu.lixko.ts3j.client.android.ServerTree +import eu.lixko.ts3j.client.android.SessionController +import eu.lixko.ts3j.client.android.SessionState +import eu.lixko.ts3j.client.net.ClientStatus +import kotlinx.coroutines.flow.MutableStateFlow + +/** What push-to-talk would talk on: the server holding the microphone, which need not be the one on screen. */ +internal class PttTarget(val owner: ServerController?, val state: SessionState, val talking: Boolean) + +@Composable +internal fun rememberPttTarget(vm: SessionController): PttTarget { + val owner by vm.micOwner.collectAsStateWithLifecycle() + val state by remember(owner) { owner?.state ?: MutableStateFlow(SessionState()) }.collectAsStateWithLifecycle() + val tree by remember(owner) { owner?.tree ?: MutableStateFlow(ServerTree()) }.collectAsStateWithLifecycle() + val self = tree.client(state.selfClientId) + val talking = self?.status == ClientStatus.TALKING || self?.status == ClientStatus.COMMANDER_TALKING + return PttTarget(owner, state, talking) +} + +/** Talks while held. */ +@Composable +internal fun PushToTalk( + talking: Boolean, + onPressed: (Boolean) -> Unit, + modifier: Modifier, + shape: Shape = RoundedCornerShape(24.dp), + textStyle: TextStyle = MaterialTheme.typography.titleMedium, +) { + val colors = MaterialTheme.colorScheme + Surface( + modifier.pointerInput(Unit) { + // Held until the finger lifts, wherever it wanders; a tap gesture would end once it left the button. + awaitEachGesture { + awaitFirstDown() + onPressed(true) + try { + do { + val event = awaitPointerEvent() + event.changes.forEach { it.consume() } + } while (event.changes.any { it.pressed }) + } finally { + onPressed(false) + } + } + }, + shape = shape, + color = if (talking) StatusColors.talking else colors.primaryContainer, + contentColor = if (talking) Color.White else colors.onPrimaryContainer, + ) { + Box(contentAlignment = Alignment.Center) { + Text(if (talking) "Talking…" else "Hold to talk", style = textStyle) + } + } +} + +/** Nothing but a push-to-talk button, as big as the screen; it talks in any input mode. */ +@Composable +fun GiantPttScreen(vm: SessionController, onBack: () -> Unit) { + val target = rememberPttTarget(vm) + SubScreen("Giant PTT", onBack) { padding -> + val fill = Modifier.padding(padding).fillMaxSize().padding(16.dp) + if (target.owner != null && target.state.connected) { + PushToTalk(target.talking, vm::setForceTransmit, fill, RoundedCornerShape(32.dp), + MaterialTheme.typography.displaySmall) + } else { + Box(fill, contentAlignment = Alignment.Center) { + Text("Not connected", + style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/RowColorPicker.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/RowColorPicker.kt new file mode 100644 index 0000000..03f4d1f --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/RowColorPicker.kt @@ -0,0 +1,120 @@ +package eu.lixko.ts3j.client.android.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Slider +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import eu.lixko.ts3j.client.config.ClientRowColors + +/** A row background: none, a preset, or a custom colour. [argb] is 0 for none. */ +@Composable +internal fun RowColorPicker(label: String, argb: Int, onChange: (Int) -> Unit) { + var open by remember { mutableStateOf(false) } + var custom by remember { mutableStateOf(false) } + Box { + Row(Modifier.fillMaxWidth().clickable { open = true }.padding(horizontal = 16.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text(label) + Text(nameOf(argb), style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant) + } + Swatch(argb, 28.dp) + } + DropdownMenu(open, { open = false }) { + DropdownMenuItem({ Text("None") }, leadingIcon = { Swatch(0) }, onClick = { + open = false + onChange(0) + }) + for (p in ClientRowColors.PRESETS) { + DropdownMenuItem({ Text(p.name()) }, leadingIcon = { Swatch(p.argb()) }, onClick = { + open = false + onChange(p.argb()) + }) + } + DropdownMenuItem({ Text("Custom…") }, onClick = { + open = false + custom = true + }) + } + } + if (custom) { + CustomColorDialog(if (argb != 0) argb else 0x59808080, onDismiss = { custom = false }) { + custom = false + onChange(it) + } + } +} + +private fun nameOf(argb: Int): String = + if (argb == 0) "None" else ClientRowColors.presetOf(argb)?.name() ?: "Custom" + +@Composable +private fun CustomColorDialog(initial: Int, onDismiss: () -> Unit, onPick: (Int) -> Unit) { + var alpha by remember { mutableIntStateOf(initial ushr 24) } + var red by remember { mutableIntStateOf(initial shr 16 and 0xFF) } + var green by remember { mutableIntStateOf(initial shr 8 and 0xFF) } + var blue by remember { mutableIntStateOf(initial and 0xFF) } + val argb = (alpha shl 24) or (red shl 16) or (green shl 8) or blue + AlertDialog( + onDismissRequest = onDismiss, + title = { Text("Custom colour") }, + text = { + Column { + Box(Modifier.fillMaxWidth().height(40.dp).clip(RoundedCornerShape(6.dp)) + .background(MaterialTheme.colorScheme.surface)) { + Box(Modifier.fillMaxWidth().height(40.dp).background(Color(argb))) + } + Channel("Red", red) { red = it } + Channel("Green", green) { green = it } + Channel("Blue", blue) { blue = it } + Channel("Opacity", alpha) { alpha = it } + } + }, + confirmButton = { TextButton({ onPick(argb) }, enabled = argb != 0) { Text("OK") } }, + dismissButton = { TextButton(onDismiss) { Text("Cancel") } }, + ) +} + +@Composable +private fun Channel(label: String, value: Int, onChange: (Int) -> Unit) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text(label, Modifier.width(64.dp), style = MaterialTheme.typography.bodySmall) + Slider(value.toFloat(), { onChange(it.toInt()) }, Modifier.weight(1f), valueRange = 0f..255f) + } +} + +/** The colour over the screen's background, as a row would show it; outlined so "none" shows too. */ +@Composable +private fun Swatch(argb: Int, size: Dp = 20.dp) { + val shape = RoundedCornerShape(4.dp) + Box(Modifier.size(size).clip(shape).background(MaterialTheme.colorScheme.surface).background(Color(argb)) + .border(1.dp, MaterialTheme.colorScheme.outline, shape)) +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerImage.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerImage.kt new file mode 100644 index 0000000..9b25c5a --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerImage.kt @@ -0,0 +1,140 @@ +package eu.lixko.ts3j.client.android.ui + +import android.graphics.BitmapFactory +import android.graphics.drawable.AnimatedImageDrawable +import android.graphics.drawable.Drawable +import android.os.Handler +import android.os.Looper +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.LocalContentColor +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.drawIntoCanvas +import androidx.compose.ui.graphics.nativeCanvas +import androidx.compose.ui.graphics.painter.BitmapPainter +import androidx.compose.ui.graphics.painter.Painter +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import eu.lixko.ts3j.client.android.Picture +import eu.lixko.ts3j.client.android.ServerImages +import eu.lixko.ts3j.client.gfx.CountryFlags +import eu.lixko.ts3j.client.net.IconRepository +import java.util.Optional +import java.util.concurrent.ConcurrentHashMap +import kotlin.math.roundToInt + +/** The images of the server on screen. */ +val LocalServerImages = staticCompositionLocalOf { null } + +/** + * A group, channel or server icon; nothing while it has none or it is still downloading. + * TeamSpeak's default group icons are the pack's, drawn in its style, as on the desktop. + */ +@Composable +fun ServerIcon(id: Long, modifier: Modifier = Modifier, size: Dp = 16.dp) { + if (id == 0L) return + if (id in 1..IconRepository.MAX_BUNDLED_ID) { + val theme = LocalIconTheme.current + val active by theme.active.collectAsStateWithLifecycle() + val pixels = with(LocalDensity.current) { size.roundToPx() } + val rgb = LocalContentColor.current.copy(alpha = 1f).toArgb() + val themed = remember(id, pixels, rgb, active) { theme.render(listOf("GROUP_$id"), pixels, rgb)?.asImageBitmap() } + if (themed != null) { + Image(themed, null, modifier.size(size)) + return + } + } + val images = LocalServerImages.current ?: return + val version by images.version.collectAsStateWithLifecycle() + val bitmap = remember(id, version) { images.icon(id) } ?: return + Image(bitmap, null, modifier.size(size)) +} + +/** A client's avatar, moving if it is an animated GIF; nothing while they have none or it is still downloading. */ +@Composable +fun Avatar(uniqueId: String, flag: String, modifier: Modifier = Modifier, size: Dp = 64.dp) { + val images = LocalServerImages.current ?: return + val version by images.version.collectAsStateWithLifecycle() + val picture = remember(flag, version) { images.avatar(uniqueId, flag) } ?: return + Image(rememberPicturePainter(picture), "Avatar", modifier.size(size).clip(RoundedCornerShape(8.dp))) +} + +/** Draws [picture], playing it while on screen if it moves. */ +@Composable +fun rememberPicturePainter(picture: Picture): Painter = when (picture) { + is Picture.Still -> remember(picture) { BitmapPainter(picture.bitmap) } + is Picture.Moving -> rememberMovingPainter(picture.drawable) +} + +@Composable +private fun rememberMovingPainter(drawable: AnimatedImageDrawable): Painter { + val painter = remember(drawable) { MovingPainter(drawable) } + DisposableEffect(drawable) { + drawable.callback = painter + drawable.start() + onDispose { + drawable.stop() + if (drawable.callback === painter) drawable.callback = null + } + } + return painter +} + +private class MovingPainter(private val drawable: AnimatedImageDrawable) : Painter(), Drawable.Callback { + /** Read while drawing, so that each new frame draws again. */ + private var frame by mutableIntStateOf(0) + private val main = Handler(Looper.getMainLooper()) + + override val intrinsicSize = Size(drawable.intrinsicWidth.toFloat(), drawable.intrinsicHeight.toFloat()) + + override fun DrawScope.onDraw() { + frame + drawIntoCanvas { canvas -> + drawable.setBounds(0, 0, size.width.roundToInt(), size.height.roundToInt()) + drawable.draw(canvas.nativeCanvas) + } + } + + override fun invalidateDrawable(who: Drawable) { + frame++ + } + + override fun scheduleDrawable(who: Drawable, what: Runnable, `when`: Long) { + main.postAtTime(what, `when`) + } + + override fun unscheduleDrawable(who: Drawable, what: Runnable) { + main.removeCallbacks(what) + } +} + +private val flags = ConcurrentHashMap>() + +/** The flag of a country, at TeamSpeak's 16×11; nothing for no country or one without a flag. */ +@Composable +fun CountryFlag(code: String, modifier: Modifier = Modifier) { + if (code.isEmpty()) return + val bitmap = remember(code) { + flags.getOrPut(code) { + Optional.ofNullable(CountryFlags.png(code)?.let { BitmapFactory.decodeByteArray(it, 0, it.size)?.asImageBitmap() }) + }.orElse(null) + } ?: return + Image(bitmap, CountryFlags.name(code), modifier.size(16.dp, 11.dp)) +} + diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt new file mode 100644 index 0000000..5db2782 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt @@ -0,0 +1,686 @@ +package eu.lixko.ts3j.client.android.ui + +import android.widget.Toast +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.Image +import androidx.compose.foundation.clickable +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.consumeWindowInsets +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ArrowDropDown +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Badge +import androidx.compose.material3.BadgedBox +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.IconToggleButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.MenuDefaults +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.minimumInteractiveComponentSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.Saver +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.isCtrlPressed +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.type +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalUriHandler +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.LifecycleResumeEffect +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import eu.lixko.ts3j.client.android.ChannelItem +import eu.lixko.ts3j.client.android.ChatKey +import eu.lixko.ts3j.client.android.ChatMatch +import eu.lixko.ts3j.client.android.ServerController +import eu.lixko.ts3j.client.android.SessionController +import eu.lixko.ts3j.client.android.SessionState +import eu.lixko.ts3j.client.android.TreeFind +import eu.lixko.ts3j.client.android.findIn +import eu.lixko.ts3j.client.config.Settings +import eu.lixko.ts3j.client.config.WhisperList +import eu.lixko.ts3j.client.myts.ChatAttachment +import eu.lixko.ts3j.client.session.ServerLink +import eu.lixko.ts3j.client.text.TsLink +import kotlinx.coroutines.launch + +private val ChatKeySaver = Saver( + save = { key -> + when (key) { + ChatKey.Server -> "server" + ChatKey.Channel -> "channel" + is ChatKey.Private -> "private:${key.clientId}" + } + }, + restore = { saved -> + when { + saved == "server" -> ChatKey.Server + saved.startsWith("private:") -> ChatKey.Private(saved.substringAfter(':').toInt()) + else -> ChatKey.Channel + } + }, +) + +private val ChannelEditSaver = Saver( + save = { edit -> edit?.let { intArrayOf(it.channelId, it.parentId) } }, + restore = { ChannelEdit(it[0], it[1]) }, +) + +/** A channel whose files are browsed, with the password they take. */ +private data class FilesOf(val channelId: Int, val name: String, val password: String) + +private val FilesOfSaver = Saver>( + save = { f -> f?.let { listOf(it.channelId, it.name, it.password) } }, + restore = { FilesOf(it[0] as Int, it[1] as String, it[2] as String) }, +) + +/** A connection: the channel tree and the chat, with the voice controls underneath. */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ServerScreen( + vm: SessionController, + server: ServerController, + snackbar: SnackbarHostState, + onSettings: () -> Unit, + /** Opens the given client's contact page. */ + onEditContact: (String) -> Unit, + onEnableMicrophone: () -> Unit, + onConnectOther: () -> Unit, + onEditBookmark: (BookmarkEdit) -> Unit, +) { + val state by server.state.collectAsStateWithLifecycle() + val tree by server.tree.collectAsStateWithLifecycle() + val chats by server.chats.collectAsStateWithLifecycle() + val collapsed by server.collapsed.collectAsStateWithLifecycle() + + var showChat by rememberSaveable { mutableStateOf(false) } + // Out here, so the tree keeps its place while the chat or another screen replaces it. + val treeList = rememberLazyListState() + var chatKey by rememberSaveable(stateSaver = ChatKeySaver) { mutableStateOf(ChatKey.Channel) } + val conversation = chats[chatKey] ?: chats.channel + var clientSheet by remember { mutableStateOf(null) } + var clientSheetFromTree by remember { mutableStateOf(false) } + /** A row to show in the tree. */ + var reveal by remember { mutableStateOf(null) } + var channelSheet by remember { mutableStateOf(null) } + /** A locked channel being joined, while its password is asked for. */ + var joinLocked by remember { mutableStateOf(null) } + val join = { channel: ChannelItem -> + if (channel.locked) joinLocked = channel.id else server.joinChannel(channel.id) + } + var serverSheet by remember { mutableStateOf(false) } + val bookmarkHere = { channelId: Int -> server.bookmark(channelId)?.let { onEditBookmark(BookmarkEdit(-1, it)) } } + var banList by rememberSaveable { mutableStateOf(false) } + var channelEdit by rememberSaveable(stateSaver = ChannelEditSaver) { mutableStateOf(null) } + var files by rememberSaveable(stateSaver = FilesOfSaver) { mutableStateOf(null) } + /** A locked channel whose files are wanted, while its password is asked for. */ + var filesLocked by remember { mutableStateOf(null) } + var deletingChannel by remember { mutableStateOf(null) } + var whisperLists by rememberSaveable { mutableStateOf(false) } + /** What is being added to a whisper list, while the list is picked: its name and how to add it. */ + var toWhisperList by remember { mutableStateOf Unit>?>(null) } + var connectionInfo by rememberSaveable { mutableStateOf(null) } + /** The client to move, while a channel for them is being picked. */ + var moving by remember { mutableStateOf(null) } + val infoUpdates by server.infoUpdates.collectAsStateWithLifecycle() + + val chatRequest by server.chatRequest.collectAsStateWithLifecycle() + LaunchedEffect(chatRequest) { + val key = chatRequest ?: return@LaunchedEffect + chatKey = if (chats[key] != null) key else server.openPrivateChat(key.clientId) + showChat = true + server.chatRequestHandled() + } + + val viewing = if (showChat) conversation.key else null + LifecycleResumeEffect(viewing) { + server.viewing = viewing + onPauseOrDispose { server.viewing = null } + } + + val uriHandler = LocalUriHandler.current + val attachments = rememberAttachmentActions(vm, server, snackbar, conversation.key) + val onLink: (String) -> Unit = { href -> + val ref = TsLink.parse(href) + when { + ChatAttachment.isHref(href) -> attachments.open(href) + ServerLink.isLink(href) -> ServerLink.parse(href)?.let { vm.open(it) } + ref == null -> runCatching { uriHandler.openUri(href) } + ref.client -> { clientSheet = ref.id; clientSheetFromTree = false } + else -> channelSheet = ref.id + } + } + + // Find: in the tree, clients or channels; in the chat, the conversation on screen. + val find = rememberSaveable(saver = FindState.Saver) { FindState() } + val treeFind = TreeFind(find.usable, find.channels) + val treeHits = remember(tree, treeFind) { tree.hits(treeFind) } + val treeFiltering = find.filter && !treeFind.query.isEmpty + val shownTree = remember(tree, treeFind, treeFiltering) { if (treeFiltering) tree.only(treeFind) else tree } + // While the tree is filtered every channel opens, so every match shows; folding one then lasts as long as the filter. + var filterCollapsed by remember(treeFiltering, treeFind) { mutableStateOf(emptySet()) } + /** The match the tree is on. */ + var treeAt by remember { mutableStateOf(null) } + // Lambdas, not local functions: Compose remembers a reference to a local function with what it first captured. + val showTreeHit = { id: Int? -> + if (id != null) { + treeAt = id + val path = (if (treeFind.channels) tree.parentsOf(id) else tree.pathTo(id)).orEmpty() + if (treeFiltering) filterCollapsed = filterCollapsed - path.toSet() else server.expand(path) + reveal = TreeRef(treeFind.channels, id) + } + } + LaunchedEffect(treeFind, showChat) { + treeAt = null + if (!showChat) showTreeHit(treeHits.firstOrNull()) + } + + val chatQuery = find.usable + val chatLines = remember(conversation.lines, chatQuery, find.filter) { + if (find.filter && !chatQuery.isEmpty) conversation.lines.filter { chatQuery.matches(it.plain) } else conversation.lines + } + val chatHits = remember(chatLines, chatQuery) { findIn(chatLines, chatQuery, MAX_CHAT_MATCHES) } + /** The match the chat is on; a new search starts from the newest. */ + var chatAt by remember { mutableStateOf(null) } + var chatReveal by remember { mutableStateOf(null) } + LaunchedEffect(chatQuery, conversation.key, find.filter, showChat) { + chatAt = if (showChat) chatHits.lastOrNull() else null + chatReveal = chatAt?.line + } + + val step = { delta: Int -> + if (showChat && chatHits.isNotEmpty()) { + chatAt = chatHits[next(chatHits.indexOf(chatAt), delta, chatHits.size)] + chatReveal = chatAt?.line + } else if (!showChat && treeHits.isNotEmpty()) { + showTreeHit(treeHits[next(treeHits.indexOf(treeAt), delta, treeHits.size)]) + } + } + + if (banList) { + BanListScreen(server, vm.banReasons, onBack = { banList = false }) + return + } + channelEdit?.let { + ChannelEditScreen(server, it, onDone = { channelEdit = null }) + return + } + files?.let { + FilesScreen(server, it.channelId, it.name, it.password, onBack = { files = null }) + return + } + if (whisperLists) { + WhisperListsScreen(vm, server, onBack = { whisperLists = false }) + return + } + connectionInfo?.let { id -> + ConnectionInfoScreen(server, id, tree.client(id), onBack = { connectionInfo = null }) + return + } + + BackHandler(showChat) { showChat = false } + BackHandler(moving != null && !showChat) { moving = null } + BackHandler(find.open) { find.open = false } + + Scaffold( + // A hardware keyboard's Ctrl+F, as on the desktop. + modifier = Modifier.onPreviewKeyEvent { e -> + val ctrlF = e.isCtrlPressed && e.key == Key.F + if (ctrlF && e.type == KeyEventType.KeyDown) find.show() + ctrlF + }, + topBar = { + if (find.open) { + if (showChat) { + FindBar(find, inTree = false, chatHits.indexOf(chatAt) + 1, chatHits.size, + chatHits.size == MAX_CHAT_MATCHES, step) + } else { + FindBar(find, inTree = true, treeHits.indexOf(treeAt) + 1, treeHits.size, false, step) + } + } else { + TopAppBar( + title = { ServerSwitcher(vm, server, state, onConnectOther) }, + expandedHeight = 48.dp, + actions = { + state.hostButton?.let { HostButtonAction(it) { url -> runCatching { uriHandler.openUri(url) } } } + if (state.connected) WhisperMenu(vm, server, state) { whisperLists = true } + IconButton(onClick = find::show) { PackIcon("FIND", "Find") } + IconButton(onClick = onSettings) { PackIcon("SETTINGS", "Settings") } + }, + ) + } + }, + bottomBar = { + Column { + val ptt = rememberPttTarget(vm) + WhisperBanner(state) { server.setWhisper(null) } + VoiceBar(state, ptt.owner != null, ptt.talking, vm, server, onEnableMicrophone, showChat, chats.anyUnread) { + showChat = !showChat + } + } + }, + snackbarHost = { SnackbarHost(snackbar) }, + ) { padding -> + Column(Modifier.padding(padding).consumeWindowInsets(padding).imePadding()) { + if (!showChat) { + moving?.let { id -> + val client = tree.client(id) + if (client == null) { + LaunchedEffect(id) { moving = null } + } else { + MovePrompt(client.name) { moving = null } + } + } + ChannelTree( + serverName = state.title, + tree = shownTree, + collapsed = if (treeFiltering) filterCollapsed else collapsed, + currentChannel = state.channelId, + onToggle = { + if (!treeFiltering) server.toggleCollapsed(it.id) + else if (it.id in filterCollapsed) filterCollapsed -= it.id + else filterCollapsed += it.id + }, + onChannel = { channel -> + val client = moving + when { + channel.spacer != null -> {} + client != null -> { server.moveClient(client, channel.id); moving = null } + else -> channelSheet = channel.id + } + }, + onChannelDoubleTap = { channel -> + val client = moving + when { + client != null -> { server.moveClient(client, channel.id); moving = null } + channel.id == state.channelId -> {} + else -> join(channel) + } + }, + onClient = { clientSheet = it.id; clientSheetFromTree = true }, + onServer = { serverSheet = true }, + modifier = Modifier.weight(1f), + reveal = reveal, + onRevealed = { reveal = null }, + found = remember(treeHits) { treeHits.mapTo(HashSet()) { TreeRef(treeFind.channels, it) } }, + foundCurrent = treeAt?.takeIf { it in treeHits }?.let { TreeRef(treeFind.channels, it) }, + listState = treeList, + onShowSelf = { + val path = tree.pathTo(state.selfClientId).orEmpty() + if (treeFiltering) filterCollapsed = filterCollapsed - path.toSet() else server.expand(path) + reveal = TreeRef(false, state.selfClientId) + }, + ) + } else { + ChatPane( + chats = chats, + selected = conversation, + canSend = state.connected, + onSelect = { chatKey = it }, + onClose = { key -> + if (chatKey == key) chatKey = ChatKey.Channel + server.closePrivateChat(key) + }, + onSend = { server.send(conversation.key, it) }, + onAttach = attachments.share, + onLink = onLink, + modifier = Modifier.weight(1f), + lines = chatLines, + find = chatQuery, + current = chatAt, + reveal = chatReveal, + onRevealed = { chatReveal = null }, + ) + } + } + } + + // A sheet goes with its client or channel when that leaves the tree. + clientSheet?.let { id -> + LaunchedEffect(id) { server.requestClientDetails(id) } + tree.client(id)?.let { client -> + ClientSheet( + client = client, + details = remember(id, tree, infoUpdates) { server.clientDetails(id) }, + onLink = onLink, + away = state.away, + initialVolume = remember(id) { server.clientVolume(id) }, + onDismiss = { clientSheet = null }, + onMessage = { + clientSheet = null + chatKey = server.openPrivateChat(id) + showChat = true + }, + onPoke = { server.poke(id, it); clientSheet = null }, + onVolume = { server.setClientVolume(id, it) }, + onAway = { server.setAway(it); clientSheet = null }, + onAddContact = { server.addContact(id, it) }, + onEditContact = { clientSheet = null; onEditContact(client.uniqueId) }, + onConnectionInfo = { clientSheet = null; connectionInfo = id }, + onWhisper = { clientSheet = null; server.whisperToClient(id) }, + onAddToWhisperList = { + clientSheet = null + server.clientRef(id)?.let { ref -> toWhisperList = client.name to { it.clients.add(ref) } } + }, + onMove = if (server.canMoveClients) ({ clientSheet = null; moving = id }) else null, + onMoveToOwnChannel = if (server.canMoveClients && tree.channel(state.channelId)?.clients?.none { it.id == id } == true) { + { server.moveClient(id, state.channelId); clientSheet = null } + } else null, + onFindInTree = if (clientSheetFromTree) null else ({ + clientSheet = null + tree.pathTo(id)?.let { server.expand(it) } + showChat = false + reveal = TreeRef(false, id) + }), + moderation = { ClientModeration(server, client) { clientSheet = null } }, + ) + } + } + channelSheet?.let { id -> + LaunchedEffect(id) { server.requestChannelDetails(id) } + tree.channel(id)?.let { channel -> + ChannelSheet( + channel = channel, + details = remember(id, tree, infoUpdates) { server.channelDetails(id) }, + onLink = onLink, + current = id == state.channelId, + onDismiss = { channelSheet = null }, + onJoin = { join(channel); channelSheet = null }, + onSubscribe = { server.setSubscribed(id, it); channelSheet = null }, + onBookmark = { channelSheet = null; bookmarkHere(id) }, + onWhisper = { channelSheet = null; server.whisperToChannel(id) }, + onAddToWhisperList = { + channelSheet = null + server.channelRef(id)?.let { ref -> toWhisperList = channel.name to { it.channels.add(ref) } } + }, + onFiles = { + channelSheet = null + if (channel.locked) filesLocked = id else files = FilesOf(id, channel.name, "") + }, + onCreateSub = if (server.canCreateChannels) ({ channelSheet = null; channelEdit = ChannelEdit(0, id) }) else null, + onEdit = if (server.canEditChannels) ({ channelSheet = null; channelEdit = ChannelEdit(id) }) else null, + onDelete = if (server.canDeleteChannels) ({ channelSheet = null; deletingChannel = id }) else null, + ) + } + } + joinLocked?.let { id -> + TextPrompt( + title = "Join ${tree.channel(id)?.name.orEmpty()}", + label = "Channel password", + confirm = "Join", + password = true, + onDismiss = { joinLocked = null }, + onConfirm = { joinLocked = null; server.joinChannel(id, it) }, + ) + } + filesLocked?.let { id -> + TextPrompt( + title = "Files of ${tree.channel(id)?.name.orEmpty()}", + label = "Channel password", + confirm = "Open", + password = true, + onDismiss = { filesLocked = null }, + onConfirm = { filesLocked = null; files = FilesOf(id, tree.channel(id)?.name.orEmpty(), it) }, + ) + } + deletingChannel?.let { id -> + val channel = tree.channel(id) + val scope = rememberCoroutineScope() + AlertDialog( + onDismissRequest = { deletingChannel = null }, + title = { Text("Delete ${channel?.name.orEmpty()}?") }, + text = if (channel != null && (channel.children.isNotEmpty() || channel.clients.isNotEmpty())) { + { Text("Its sub-channels go with it, and whoever is in it is moved out.") } + } else null, + confirmButton = { + TextButton(onClick = { + deletingChannel = null + scope.launch { server.deleteChannel(id)?.let { snackbar.showSnackbar("Could not delete the channel: $it") } } + }) { Text("Delete") } + }, + dismissButton = { TextButton(onClick = { deletingChannel = null }) { Text("Cancel") } }, + ) + } + toWhisperList?.let { (name, add) -> + AddToWhisperListDialog(vm, name, onDismiss = { toWhisperList = null }) { index, newName -> + toWhisperList = null + vm.addToWhisperList(index, newName, add) + } + } + if (serverSheet) { + remember(tree, infoUpdates) { server.serverDetails() }?.let { + ServerSheet(it, onLink, onDismiss = { serverSheet = false }, + onBookmark = { serverSheet = false; bookmarkHere(state.channelId) }, + onBanList = if (server.canViewBanList) ({ serverSheet = false; banList = true }) else null, + onCreateChannel = if (server.canCreateChannels) ({ serverSheet = false; channelEdit = ChannelEdit(0, 0) }) else null) + } + } +} + +/** More matches than this nobody steps through one by one. */ +private const val MAX_CHAT_MATCHES = 5000 + +/** The index [delta] on from [at] among [size], wrapping around; from none, the first or the last. */ +private fun next(at: Int, delta: Int, size: Int): Int = + if (at < 0) (if (delta > 0) 0 else size - 1) else Math.floorMod(at + delta, size) + +/** Says a channel is being picked for [name] to move to, until it is or [onCancel]. */ +@Composable +private fun MovePrompt(name: String, onCancel: () -> Unit) { + Surface(color = MaterialTheme.colorScheme.secondaryContainer) { + Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) { + PackIcon("CHANNEL_SWITCH", null) + Text("Move $name to…", Modifier.weight(1f).padding(horizontal = 12.dp), maxLines = 1, + overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium) + TextButton(onClick = onCancel) { Text("Cancel") } + } + } +} + +/** + * Mute, deafen, away and the chat, around the push-to-talk button when that is how the + * microphone is used. Holding the mute button switches between push to talk and voice activation. + */ +@Composable +private fun VoiceBar( + state: SessionState, + /** Whether some server holds the microphone, for push-to-talk to talk on. */ + captured: Boolean, + talking: Boolean, + vm: SessionController, + server: ServerController, + onEnableMicrophone: () -> Unit, + showChat: Boolean, + unread: Boolean, + onChat: () -> Unit, +) { + val context = LocalContext.current + val ptt = state.connected && captured && state.inputMode == Settings.InputMode.PUSH_TO_TALK + val mic = @Composable { + BarButton( + onClick = { server.setMicMuted(!state.micMuted) }, + onLongClick = { + val mode = vm.toggleInputMode() + val text = if (mode == Settings.InputMode.PUSH_TO_TALK) "Switched to push-to-talk mode." + else "Switched to voice activation mode." + Toast.makeText(context, text, Toast.LENGTH_SHORT).show() + }, + enabled = state.connected, + ) { + if (state.micMuted) PackIcon("INPUT_MUTED", "Unmute microphone") + else PackIcon("CAPTURE", "Mute microphone") + } + } + val deafen = @Composable { + IconToggleButton(state.deafened, { server.setDeafened(it) }, enabled = state.connected) { + if (state.deafened) PackIcon("OUTPUT_MUTED", "Undeafen") + else PackIcon("PLAYBACK", "Deafen") + } + } + // Another server holds the microphone. + val activate = @Composable { + if (state.connected && state.micPermission && !state.micActive) { + IconButton(onClick = onEnableMicrophone) { PackIcon("ACTIVATE_MICROPHONE", "Speak on this server") } + } + } + val middle = @Composable { + when { + ptt -> PushToTalk(talking, vm::setPushToTalk, Modifier.fillMaxWidth().height(48.dp)) + !state.micPermission -> FilledTonalButton(onClick = onEnableMicrophone) { + PackIcon("CAPTURE", null) + Text("Use microphone", Modifier.padding(start = 8.dp), maxLines = 1) + } + } + } + val away = @Composable { + IconToggleButton(state.away, { server.setAway(it) }, enabled = state.connected) { + PackIcon("AWAY", if (state.away) "Back" else "Away", Modifier.alpha(if (state.away) 1f else 0.5f)) + } + } + val chat = @Composable { + IconToggleButton(showChat, { onChat() }) { + BadgedBox(badge = { if (unread && !showChat) Badge() }) { + PackIcon(listOf("MESSAGES", "CHANNEL_CHAT"), if (showChat) "Channels" else "Chat", + Modifier.alpha(if (showChat) 1f else 0.7f)) + } + } + } + Surface(tonalElevation = 3.dp) { + // The same places whatever shows: sides of three buttons each keep the talk button centred. + Row(Modifier.fillMaxWidth().navigationBarsPadding().padding(horizontal = 8.dp, vertical = 4.dp), + horizontalArrangement = Arrangement.spacedBy(4.dp), + verticalAlignment = Alignment.CenterVertically) { + Row(Modifier.width(SIDE), verticalAlignment = Alignment.CenterVertically) { + Slot { mic() }; Slot { deafen() }; Slot { activate() } + } + Box(Modifier.weight(1f).height(48.dp), contentAlignment = Alignment.Center) { middle() } + Row(Modifier.width(SIDE), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) { + Slot { away() }; Slot { chat() } + } + } + } +} + +private val SLOT = 48.dp +private val SIDE = SLOT * 3 + +/** One button's place in the bar, kept whether or not the button shows. */ +@Composable +private fun Slot(content: @Composable () -> Unit) { + Box(Modifier.size(SLOT), contentAlignment = Alignment.Center) { content() } +} + +/** An icon button that also answers a long press. */ +@Composable +private fun BarButton(onClick: () -> Unit, onLongClick: () -> Unit, enabled: Boolean, content: @Composable () -> Unit) { + Box( + Modifier + .minimumInteractiveComponentSize() + .size(40.dp) + .clip(CircleShape) + .combinedClickable(enabled = enabled, role = Role.Button, onLongClick = onLongClick, onClick = onClick) + .alpha(if (enabled) 1f else 0.38f), + contentAlignment = Alignment.Center, + ) { content() } +} + +/** The server's own icon, else the pack's server icon. */ +@Composable +private fun ServerLogo(server: ServerController, modifier: Modifier = Modifier) { + val tree by server.tree.collectAsStateWithLifecycle() + val version by server.images.version.collectAsStateWithLifecycle() + val icon = remember(tree.serverIconId, version) { server.images.icon(tree.serverIconId) } + if (icon != null) Image(icon, null, modifier.size(24.dp)) + else PackIcon("SERVER_GREEN", null, modifier) +} + +/** The server on screen, opening onto the others and connecting to another. */ +@Composable +private fun ServerSwitcher(vm: SessionController, server: ServerController, state: SessionState, onConnectOther: () -> Unit) { + val servers by vm.servers.collectAsStateWithLifecycle() + var open by remember { mutableStateOf(false) } + Box(Modifier.fillMaxWidth()) { + Row(Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable { open = true }, + verticalAlignment = Alignment.CenterVertically) { + ServerLogo(server, Modifier.padding(end = 12.dp)) + Column(Modifier.weight(1f)) { + Text(state.title, maxLines = 1, overflow = TextOverflow.Ellipsis) + if (!state.connected) { + Text(state.status, style = MaterialTheme.typography.bodySmall, maxLines = 1, + overflow = TextOverflow.Ellipsis) + } + } + Icon(Icons.Filled.ArrowDropDown, "Servers") + } + DropdownMenu(open, onDismissRequest = { open = false }) { + for (other in servers) { + key(other.id) { + val otherState by other.state.collectAsStateWithLifecycle() + DropdownMenuItem( + text = { Text(otherState.title, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + onClick = { open = false; vm.select(other) }, + leadingIcon = { + ServerLogo(other, Modifier.alpha(if (otherState.connected) 1f else 0.5f)) + }, + trailingIcon = if (otherState.micActive) ({ PackIcon("ACTIVATE_MICROPHONE", "Microphone") }) else null, + colors = if (other == server) MenuDefaults.itemColors(textColor = MaterialTheme.colorScheme.primary) + else MenuDefaults.itemColors(), + ) + } + } + HorizontalDivider() + DropdownMenuItem( + text = { Text("Connect…") }, + onClick = { open = false; onConnectOther() }, + leadingIcon = { PackIcon("CONNECT", null) }, + ) + DropdownMenuItem( + text = { Text("Disconnect from current") }, + onClick = { open = false; server.disconnect() }, + leadingIcon = { PackIcon("DISCONNECT", null) }, + ) + } + } +} + diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SettingsScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SettingsScreen.kt new file mode 100644 index 0000000..fc85d0a --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SettingsScreen.kt @@ -0,0 +1,127 @@ +package eu.lixko.ts3j.client.android.ui + +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import eu.lixko.ts3j.client.android.IconTheme +import eu.lixko.ts3j.client.android.SessionController +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +private enum class SettingsPage { SOUND, NETWORK, GIANT_PTT, DESIGN, IDENTITIES, MY_TEAMSPEAK } + +/** + * The settings, by category. Every change is saved and put into effect at once, + * as there is no dialog to confirm. + */ +@Composable +fun SettingsScreen(vm: SessionController, onContacts: () -> Unit, onBack: () -> Unit) { + var page by rememberSaveable { mutableStateOf(null) } + when (page) { + SettingsPage.SOUND -> return SoundSettingsScreen(vm, onBack = { page = null }) + SettingsPage.NETWORK -> return NetworkSettingsScreen(vm, onBack = { page = null }) + SettingsPage.GIANT_PTT -> return GiantPttScreen(vm, onBack = { page = null }) + SettingsPage.DESIGN -> return DesignScreen(vm, onBack = { page = null }) + SettingsPage.IDENTITIES -> return IdentitiesScreen(vm.identities, onBack = { page = null }) + SettingsPage.MY_TEAMSPEAK -> return MyTeamSpeakScreen(vm, onBack = { page = null }) + null -> {} + } + + SubScreen("Settings", onBack) { padding -> + Column(Modifier.padding(padding).verticalScroll(rememberScrollState())) { + LinkRow("Contacts", "Friends and blocked users", "CONTACT", onContacts) + LinkRow("Sound Settings", "Devices, transmission, voice activation, processing, volume", "PLAYBACK") { + page = SettingsPage.SOUND + } + LinkRow("Network", "Bitrate, error correction, redundancy, buffering", "PING_4") { + page = SettingsPage.NETWORK + } + LinkRow("Giant PTT", "A push-to-talk button filling the screen", "CAPTURE") { + page = SettingsPage.GIANT_PTT + } + LinkRow("Design", "Icon pack, country flags, client colours, description pictures", "GUISETUP") { + page = SettingsPage.DESIGN + } + LinkRow("Identities", "Create, import, export, security level", + "IDENTITY_MANAGER") { page = SettingsPage.IDENTITIES } + LinkRow("myTeamSpeak", + if (vm.myTeamSpeak.isSignedIn) "Signed in as ${vm.myTeamSpeak.username()}" + else "Sign in to bring over your synchronised bookmarks and identities", + "MYTS_ACCOUNT") { page = SettingsPage.MY_TEAMSPEAK } + } + } +} + +@Composable +private fun DesignScreen(vm: SessionController, onBack: () -> Unit) { + SubScreen("Design", onBack) { padding -> + Column(Modifier.padding(padding).verticalScroll(rememberScrollState())) { + IconPackPicker(vm.icons) + var pictures by remember { mutableStateOf(vm.settings.descriptionPictures) } + Toggle("Show pictures in descriptions", pictures) { + pictures = it + vm.setDescriptionPictures(it) + } + Section("Channel tree") + var flags by remember { mutableStateOf(vm.settings.countryFlags) } + Toggle("Show country flags in the channel tree", flags) { + flags = it + vm.setCountryFlags(it) + } + val colors = vm.settings.clientRowColors + var any by remember { mutableIntStateOf(colors.any) } + var talking by remember { mutableIntStateOf(colors.talking) } + var mutedAway by remember { mutableIntStateOf(colors.mutedAway) } + RowColorPicker("Client background", any) { + any = it + colors.any = it + vm.clientRowColorsChanged() + } + RowColorPicker("While talking", talking) { + talking = it + colors.talking = it + vm.clientRowColorsChanged() + } + RowColorPicker("Muted / away", mutedAway) { + mutedAway = it + colors.mutedAway = it + vm.clientRowColorsChanged() + } + } + } +} + +/** Chooses the icon pack, and brings in TeamSpeak packs from a file. */ +@Composable +private fun IconPackPicker(theme: IconTheme) { + val packs by theme.packs.collectAsStateWithLifecycle() + val active by theme.active.collectAsStateWithLifecycle() + val scope = rememberCoroutineScope() + var failed by remember { mutableStateOf(null) } + val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + if (uri != null) scope.launch { + val pack = withContext(Dispatchers.IO) { runCatching { theme.import(uri) }.getOrNull() } + failed = if (pack == null) "That file is not an icon pack." else null + } + } + Picker("Icon pack", packs.map { it to it.name() }, active) { theme.select(it) } + LinkRow("Import icon pack", "A TeamSpeak 3 pack (.zip), such as those in the gfx folder of a TeamSpeak 3 install") { + importer.launch(arrayOf("application/zip", "application/octet-stream")) + } + failed?.let { Hint(it) } +} + diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SettingsWidgets.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SettingsWidgets.kt new file mode 100644 index 0000000..9a27815 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SettingsWidgets.kt @@ -0,0 +1,175 @@ +package eu.lixko.ts3j.client.android.ui + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SegmentedButton +import androidx.compose.material3.SegmentedButtonDefaults +import androidx.compose.material3.SingleChoiceSegmentedButtonRow +import androidx.compose.material3.Slider +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp + +/** The width a segment needs for a label of a word or two; narrower screens get a list instead. */ +private val SEGMENT_WIDTH = 110.dp + +/** A full-screen page with a back arrow; the system back gesture leaves it the same way. */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun SubScreen( + title: String, + onBack: () -> Unit, + actions: @Composable RowScope.() -> Unit = {}, + snackbar: SnackbarHostState? = null, + content: @Composable (PaddingValues) -> Unit, +) { + BackHandler(onBack = onBack) + Scaffold( + snackbarHost = { snackbar?.let { SnackbarHost(it) } }, + topBar = { + TopAppBar( + title = { Text(title, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } }, + actions = actions, + ) + }, + content = content, + ) +} + +/** A row that opens another page, or does one thing when tapped. */ +@Composable +internal fun LinkRow(title: String, summary: String?, iconKey: String? = null, onClick: () -> Unit) { + ListItem( + headlineContent = { Text(title) }, + supportingContent = summary?.let { { Text(it) } }, + leadingContent = iconKey?.let { { PackIcon(it, null) } }, + modifier = Modifier.clickable(onClick = onClick), + ) +} + +@Composable +internal fun Section(title: String) { + Text(title, Modifier.padding(start = 16.dp, top = 24.dp, bottom = 4.dp), + style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary) +} + +@Composable +internal fun Choice(label: String, selected: Boolean, onSelect: () -> Unit) { + Row(Modifier.fillMaxWidth().clickable(onClick = onSelect).padding(horizontal = 16.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically) { + RadioButton(selected, onClick = onSelect) + Text(label, Modifier.padding(start = 8.dp)) + } +} + +/** One of [options] as a row of segments, or as radio buttons where the segments would not fit. */ +@Composable +internal fun Segments(options: List>, selected: T, onSelect: (T) -> Unit) { + BoxWithConstraints(Modifier.fillMaxWidth()) { + if (maxWidth - 32.dp < SEGMENT_WIDTH * options.size) { + Column { for ((value, label) in options) Choice(label, value == selected) { onSelect(value) } } + return@BoxWithConstraints + } + SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp)) { + options.forEachIndexed { index, (value, label) -> + SegmentedButton( + selected = value == selected, + onClick = { onSelect(value) }, + shape = SegmentedButtonDefaults.itemShape(index, options.size), + ) { Text(label, maxLines = 1, overflow = TextOverflow.Ellipsis) } + } + } + } +} + +@Composable +internal fun Toggle(label: String, checked: Boolean, onChange: (Boolean) -> Unit) { + Row(Modifier.fillMaxWidth().clickable { onChange(!checked) }.padding(horizontal = 16.dp, vertical = 2.dp), + verticalAlignment = Alignment.CenterVertically) { + Text(label, Modifier.weight(1f)) + Switch(checked, onChange) + } +} + +@Composable +internal fun Hint(text: String) { + Text(text, Modifier.padding(horizontal = 16.dp, vertical = 2.dp), + style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) +} + +/** One of [options], shown as its label and picked from a menu. */ +@Composable +internal fun Picker(label: String, options: List>, selected: T, onSelect: (T) -> Unit) { + var open by remember { mutableStateOf(false) } + Box { + Column(Modifier.fillMaxWidth().clickable { open = true }.padding(horizontal = 16.dp, vertical = 8.dp)) { + Text(label) + Text(options.firstOrNull { it.first == selected }?.second ?: "", style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant) + } + DropdownMenu(open, { open = false }) { + for ((value, text) in options) { + DropdownMenuItem({ Text(text) }, onClick = { + open = false + onSelect(value) + }) + } + } + } +} + +/** A slider that applies its value once let go of. */ +@Composable +internal fun Level( + label: String, + value: Float, + range: ClosedFloatingPointRange, + format: (Float) -> String, + steps: Int = 0, + onChange: (Float) -> Unit = {}, + onDone: (Float) -> Unit, +) { + var current by remember(value) { mutableFloatStateOf(value) } + Column(Modifier.padding(horizontal = 16.dp, vertical = 4.dp)) { + Row { + Text(label, Modifier.weight(1f)) + Text(format(current), color = MaterialTheme.colorScheme.onSurfaceVariant) + } + Slider(current, { + current = it + onChange(it) + }, valueRange = range, steps = steps, onValueChangeFinished = { onDone(current) }) + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Sheets.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Sheets.kt new file mode 100644 index 0000000..9e9e98f --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Sheets.kt @@ -0,0 +1,238 @@ +package eu.lixko.ts3j.client.android.ui + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.ListItem +import androidx.compose.material3.ListItemDefaults +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Slider +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.text.input.VisualTransformation +import androidx.compose.ui.unit.dp +import androidx.compose.foundation.clickable +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import eu.lixko.ts3j.client.android.ChannelItem +import eu.lixko.ts3j.client.android.ClientItem +import eu.lixko.ts3j.client.contacts.ContactType +import eu.lixko.ts3j.client.net.Details +import kotlin.math.roundToInt + +/** What can be done with a client: the private chat, a poke, a move, their volume, filing them as a contact. */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ClientSheet( + client: ClientItem, + details: Details?, + onLink: (String) -> Unit, + away: Boolean, + initialVolume: Double, + onDismiss: () -> Unit, + onMessage: () -> Unit, + onPoke: (String) -> Unit, + onVolume: (Double) -> Unit, + onAway: (Boolean) -> Unit, + onAddContact: (ContactType) -> Unit, + onEditContact: () -> Unit, + onConnectionInfo: () -> Unit, + onWhisper: () -> Unit, + onAddToWhisperList: () -> Unit, + /** Null when the client cannot be moved. */ + onMove: (() -> Unit)?, + /** Null when the client cannot be moved, or is in our channel already. */ + onMoveToOwnChannel: (() -> Unit)?, + /** Null when the sheet was opened from the tree. */ + onFindInTree: (() -> Unit)?, + /** Kicks, bans and groups, as far as we may use them. */ + moderation: @Composable () -> Unit = {}, +) { + var poking by remember { mutableStateOf(false) } + ModalBottomSheet(onDismissRequest = onDismiss) { + Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) { + Row(Modifier.padding(horizontal = 24.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp)) { + StatusIcon(client.status) + Column(Modifier.weight(1f)) { + // The country's flag goes before the name, as in TeamSpeak's info frame. + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + CountryFlag(client.country) + Text(client.name, style = MaterialTheme.typography.titleLarge) + } + if (client.name != client.nickname) Text(client.nickname, style = MaterialTheme.typography.bodyMedium) + if (client.awayMessage.isNotEmpty()) Text(client.awayMessage, style = MaterialTheme.typography.bodyMedium) + } + val viewer = LocalPictureViewer.current + val images = LocalServerImages.current + Avatar(client.uniqueId, client.avatarFlag, Modifier.clickable(enabled = viewer != null && images != null) { + viewer?.invoke(ViewedPicture("avatar_${client.nickname}", ownAvatar = client.self) { + images?.avatarData(client.uniqueId, client.avatarFlag) + }) + }) + } + details?.let { DetailsSection(it, onLink, Modifier.padding(bottom = 8.dp)) } + onFindInTree?.let { Action("CHANNEL_SWITCH", "Find client in channel tree", onClick = it) } + Action("INFO", "Connection info", onClick = onConnectionInfo) + if (client.self) { + Action("AWAY", if (away) "Back" else "Away") { onAway(!away) } + moderation() + } else { + Action("PLAYER_CHAT", "Send message", onClick = onMessage) + Action("POKE", "Poke") { poking = true } + Action("PLAYER_WHISPER", "Whisper", onClick = onWhisper) + Action("ON_WHISPERLIST", "Add to whisper list…", onClick = onAddToWhisperList) + onMove?.let { Action("CHANNEL_SWITCH", "Move to channel…", onClick = it) } + onMoveToOwnChannel?.let { Action("MOVE_CLIENT_TO_OWN_CHANNEL", "Move to own channel", onClick = it) } + moderation() + if (client.contactType == null) { + Row { + Action("ADD_FRIEND", "Add as friend", Modifier.weight(1f)) { onAddContact(ContactType.FRIEND) } + Action("ADD_FOE", "Block", Modifier.weight(1f)) { onAddContact(ContactType.BLOCKED) } + } + } else { + Action("EDIT_FRIEND_FOE_STATUS", "Edit contact", onClick = onEditContact) + } + var volume by remember { mutableFloatStateOf(initialVolume.toFloat()) } + Text("Volume: ${if (volume > 0) "+" else ""}${volume.roundToInt()} dB", + Modifier.padding(start = 24.dp, top = 8.dp), style = MaterialTheme.typography.bodyMedium) + Slider( + volume, { volume = it.roundToInt().toFloat() }, + Modifier.padding(horizontal = 24.dp), + valueRange = -30f..20f, + onValueChangeFinished = { onVolume(volume.toDouble()) }, + ) + } + } + } + if (poking) { + TextPrompt( + title = "Poke ${client.name}", + label = "Message", + confirm = "Poke", + onDismiss = { poking = false }, + onConfirm = { poking = false; onPoke(it) }, + ) + } +} + +/** What can be done with a channel: join it, whether to hear who is in it, whisper to it, its files, and editing it. */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ChannelSheet( + channel: ChannelItem, + details: Details?, + onLink: (String) -> Unit, + current: Boolean, + onDismiss: () -> Unit, + onJoin: () -> Unit, + onSubscribe: (Boolean) -> Unit, + onBookmark: () -> Unit, + onWhisper: () -> Unit, + onAddToWhisperList: () -> Unit, + onFiles: () -> Unit, + /** Each null when we may not. */ + onCreateSub: (() -> Unit)?, + onEdit: (() -> Unit)?, + onDelete: (() -> Unit)?, +) { + ModalBottomSheet(onDismissRequest = onDismiss) { + Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) { + Text(channel.name, Modifier.padding(horizontal = 24.dp, vertical = 8.dp), + style = MaterialTheme.typography.titleLarge) + details?.let { DetailsSection(it, onLink, Modifier.padding(bottom = 8.dp)) } + if (!current) { + Action("CHANNEL_SWITCH", "Join", onClick = onJoin) + } + if (channel.subscribed) { + Action("UNSUBSCRIBE_FROM_CHANNEL", "Unsubscribe") { onSubscribe(false) } + } else { + Action("SUBSCRIBE_TO_CHANNEL", "Subscribe") { onSubscribe(true) } + } + Action("WHISPER", "Whisper", onClick = onWhisper) + Action("ON_WHISPERLIST", "Add to whisper list…", onClick = onAddToWhisperList) + Action("FILETRANSFER", "Browse files", onClick = onFiles) + Action("BOOKMARK_ADD", "Add to bookmarks", onClick = onBookmark) + onCreateSub?.let { Action("CHANNEL_CREATE_SUB", "Create sub-channel", onClick = it) } + onEdit?.let { Action("CHANNEL_EDIT", "Edit channel", onClick = it) } + onDelete?.let { Action("CHANNEL_DELETE", "Delete channel", onClick = it) } + } + } +} + +/** The server's details: its version, who is on it, its welcome message. */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ServerSheet( + details: Details, + onLink: (String) -> Unit, + onDismiss: () -> Unit, + onBookmark: () -> Unit, + onBanList: (() -> Unit)?, + onCreateChannel: (() -> Unit)?, +) { + ModalBottomSheet(onDismissRequest = onDismiss) { + Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) { + Row(Modifier.padding(horizontal = 24.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp)) { + PackIcon("SERVER_GREEN", null) + Text(details.title(), style = MaterialTheme.typography.titleLarge) + } + DetailsSection(details, onLink) + Action("BOOKMARK_ADD", "Add to bookmarks", onClick = onBookmark) + onCreateChannel?.let { Action("CHANNEL_CREATE", "Create channel", onClick = it) } + onBanList?.let { Action("BAN_LIST", "Ban list", onClick = it) } + } + } +} + +@Composable +internal fun Action(iconKey: String, label: String, modifier: Modifier = Modifier.fillMaxWidth(), onClick: () -> Unit) { + ListItem( + headlineContent = { Text(label) }, + leadingContent = { PackIcon(iconKey, null) }, + colors = ListItemDefaults.colors(containerColor = Color.Transparent), + modifier = modifier.clickable(onClick = onClick).padding(horizontal = 8.dp), + ) +} + +/** Asks for one line of text. */ +@Composable +fun TextPrompt( + title: String, + label: String, + confirm: String, + onDismiss: () -> Unit, + onConfirm: (String) -> Unit, + initial: String = "", + password: Boolean = false, +) { + var text by remember { mutableStateOf(initial) } + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(title) }, + text = { + OutlinedTextField(text, { text = it }, label = { Text(label) }, singleLine = true, + visualTransformation = if (password) PasswordVisualTransformation() else VisualTransformation.None) + }, + confirmButton = { TextButton(onClick = { onConfirm(text) }) { Text(confirm) } }, + dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + ) +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SoundSettingsScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SoundSettingsScreen.kt new file mode 100644 index 0000000..7ad0e3a --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SoundSettingsScreen.kt @@ -0,0 +1,260 @@ +package eu.lixko.ts3j.client.android.ui + +import android.content.Intent +import android.net.Uri +import android.provider.Settings.ACTION_MANAGE_OVERLAY_PERMISSION +import android.provider.Settings.canDrawOverlays +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.LifecycleStartEffect +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import eu.lixko.ts3j.client.android.MicLevel +import eu.lixko.ts3j.client.android.SessionController +import eu.lixko.ts3j.client.android.audio.AudioRoute +import eu.lixko.ts3j.client.audio.AudioDevice +import eu.lixko.ts3j.client.audio.InputLevel +import eu.lixko.ts3j.client.config.Settings +import kotlin.math.roundToInt + +private val DENOISE_LEVELS = listOf("Off", "6 dB", "12 dB", "18 dB", "21 dB") + +/** Audio devices, transmission, voice activation, processing and playback. */ +@Composable +fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) { + val settings = vm.settings + fun change(edit: Settings.() -> Unit) { + settings.edit() + vm.applySettings() + } + var inputMode by remember { mutableStateOf(settings.inputMode) } + var vadMode by remember { mutableStateOf(settings.vadMode) } + var agc by remember { mutableStateOf(settings.agc) } + var mutedTalkWarning by remember { mutableStateOf(settings.mutedTalkWarning) } + var threshold by remember { mutableFloatStateOf(settings.vadThresholdDb.toFloat()) } + var inputDevice by remember { mutableStateOf(settings.inputDevice) } + var outputDevice by remember { mutableStateOf(settings.outputDevice) } + val inputs by vm.inputDevices.collectAsStateWithLifecycle() + val outputs by vm.outputDevices.collectAsStateWithLifecycle() + val route by vm.route.collectAsStateWithLifecycle() + val level by vm.micLevel.collectAsStateWithLifecycle() + val packs by vm.soundPacks.collectAsStateWithLifecycle() + var pack by remember { mutableStateOf(vm.soundPack?.id()) } + LifecycleStartEffect(Unit) { + vm.watchLevel(true) + onStopOrDispose { vm.watchLevel(false) } + } + + SubScreen("Sound Settings", onBack) { padding -> + Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { + Section("Devices") + DevicePicker("Microphone", inputs, inputDevice) { + inputDevice = it + change { this.inputDevice = it } + } + DevicePicker("Speaker", outputs, outputDevice) { + outputDevice = it + change { this.outputDevice = it } + } + Picker( + "Microphone preset", + INPUT_PRESETS.map { (preset, label) -> + val unsupported = preset == AudioRoute.InputPreset.UNPROCESSED && !vm.unprocessedSupported + preset to if (unsupported) "$label (not supported here)" else label + }, + route.inputPreset(), + ) { vm.setRoute(AudioRoute(it, route.usage())) } + Hint(PRESET_HINTS.getValue(route.inputPreset())) + Text("Play voices", Modifier.padding(start = 16.dp, top = 8.dp)) + for ((usage, label) in USAGES) { + Choice(label, route.usage() == usage) { vm.setRoute(AudioRoute(route.inputPreset(), usage)) } + } + + Section("Transmission") + for ((mode, label) in INPUT_MODES) { + Choice(label, inputMode == mode) { + inputMode = mode + change { this.inputMode = mode } + } + } + if (inputMode == Settings.InputMode.PUSH_TO_TALK) FloatingButtonToggle(vm) + val gated = inputMode == Settings.InputMode.VOICE_ACTIVATION && vadMode != Settings.VadMode.AUTOMATIC + LevelMeter(level, threshold.takeIf { gated }) + if (!level.live) { + Hint(if (vm.hasMicPermission()) "The microphone is not available right now." else "Allow the microphone to see its level.") + } + + if (inputMode == Settings.InputMode.VOICE_ACTIVATION) { + Section("Voice activation") + for ((mode, label) in VAD_MODES) { + Choice(label, vadMode == mode) { + vadMode = mode + change { this.vadMode = mode } + } + } + if (vadMode != Settings.VadMode.AUTOMATIC) { + Level("Volume threshold", settings.vadThresholdDb.toFloat(), -50f..50f, { "${it.roundToInt()}" }, + onChange = { threshold = it }) { + change { vadThresholdDb = it.roundToInt().toDouble() } + } + } + if (vadMode != Settings.VadMode.VOLUME_GATE) { + Level("Speech likelihood", settings.speechThreshold.toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) { + change { speechThreshold = it.toDouble() } + } + } + } + + Section("Processing") + val suppression = if (settings.denoise) settings.denoiserLevel + 1 else 0 + Level("Noise suppression", suppression.toFloat(), 0f..DENOISE_LEVELS.lastIndex.toFloat(), + { DENOISE_LEVELS[it.roundToInt()] }, steps = DENOISE_LEVELS.lastIndex - 1) { + val step = it.roundToInt() + change { + denoise = step > 0 + if (step > 0) denoiserLevel = step - 1 + } + } + Toggle("Automatic gain control", agc) { + agc = it + change { this.agc = it } + } + if (agc) { + Level("Boost quiet speech", settings.agcBoostDb.toFloat(), 0f..Settings.MAX_AGC_BOOST_DB.toFloat(), + { "+${it.roundToInt()} dB" }, steps = Settings.MAX_AGC_BOOST_DB - 1) { + change { agcBoostDb = it.roundToInt() } + } + } + + Section("Playback") + Level("Volume", settings.outputVolume.toFloat(), 0f..2f, { "${(it * 100).roundToInt()} %" }) { + change { outputVolume = it.toDouble() } + } + + Section("Notification sounds") + if (packs.isEmpty()) { + Hint("This build of the app came without sound packs.") + } else { + Picker("Sound pack", packs.map { it.id() to it.name() }, pack) { id -> + packs.firstOrNull { it.id() == id }?.let(vm::setSoundPack) + pack = id + } + } + Level("Volume", settings.soundVolume.toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) { + change { soundVolume = it.toDouble() } + } + Toggle("Beep when talking while muted", mutedTalkWarning) { + mutedTalkWarning = it + change { this.mutedTalkWarning = it } + } + } + } +} + +private val INPUT_MODES = listOf( + Settings.InputMode.VOICE_ACTIVATION to "Voice activation", + Settings.InputMode.PUSH_TO_TALK to "Push to talk", + Settings.InputMode.CONTINUOUS to "Continuous", +) + +private val INPUT_PRESETS = listOf( + AudioRoute.InputPreset.VOICE_RECOGNITION to "Voice recognition", + AudioRoute.InputPreset.VOICE_COMMUNICATION to "Voice communication", + AudioRoute.InputPreset.UNPROCESSED to "Unprocessed", + AudioRoute.InputPreset.VOICE_PERFORMANCE to "Voice performance", + AudioRoute.InputPreset.GENERIC to "Generic", + AudioRoute.InputPreset.CAMCORDER to "Camcorder", +) + +private val PRESET_HINTS = mapOf( + AudioRoute.InputPreset.VOICE_RECOGNITION to "Little or no processing by the phone; the client's own does the rest.", + AudioRoute.InputPreset.VOICE_COMMUNICATION to + "The phone's call processing: echo cancellation, noise suppression and gain. Works best with voices played as a call.", + AudioRoute.InputPreset.UNPROCESSED to "The raw microphone signal.", + AudioRoute.InputPreset.VOICE_PERFORMANCE to "Low latency and no processing, meant for live performance.", + AudioRoute.InputPreset.GENERIC to "The phone's default microphone source, with whatever it applies to it.", + AudioRoute.InputPreset.CAMCORDER to "Tuned for recording video, often with the rear microphone.", +) + +private val USAGES = listOf( + AudioRoute.Usage.MEDIA to "As media (Bluetooth stays in high quality)", + AudioRoute.Usage.VOICE_COMMUNICATION to "As a call (lets the phone cancel echo)", +) + +private val VAD_MODES = listOf( + Settings.VadMode.AUTOMATIC to "Automatic", + Settings.VadMode.VOLUME_GATE to "Volume gate", + Settings.VadMode.HYBRID to "Hybrid", +) + +/** The push-to-talk button over other apps, which first needs the user to allow the app to draw there. */ +@Composable +private fun FloatingButtonToggle(vm: SessionController) { + val context = LocalContext.current + val enabled by vm.pttOverlay.collectAsStateWithLifecycle() + val allow = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { + if (canDrawOverlays(context)) vm.setPttOverlay(true) + } + Toggle("Floating button over other apps", enabled && canDrawOverlays(context)) { on -> + if (!on || canDrawOverlays(context)) vm.setPttOverlay(on) + else allow.launch(Intent(ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:${context.packageName}"))) + } + Hint("Hold it to talk. Double-tap and keep holding to drag it elsewhere.") +} + +/** Picks a device by its settings id; one that is not plugged in now still shows as chosen. */ +@Composable +private fun DevicePicker(label: String, devices: List, selected: String, onSelect: (String) -> Unit) { + val options = devices.map { it.id() to it.label() }.let { list -> + if (list.any { it.first == selected }) list else list + (selected to "Not connected") + } + Picker(label, options, selected, onSelect) +} + +/** The microphone level, lit while it would be sent, with the volume gate's threshold marked. */ +@Composable +private fun LevelMeter(level: MicLevel, thresholdDb: Float?) { + val track = MaterialTheme.colorScheme.surfaceVariant + val fill = if (level.transmitting) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline + val marker = MaterialTheme.colorScheme.onSurface + fun fraction(db: Double) = + ((db - InputLevel.MIN_DB) / (InputLevel.MAX_DB - InputLevel.MIN_DB)).toFloat().coerceIn(0f, 1f) + Column(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) { + Row { + Text("Microphone level", Modifier.weight(1f)) + if (level.live) Text("${level.db.roundToInt()}", color = MaterialTheme.colorScheme.onSurfaceVariant) + } + Canvas(Modifier.fillMaxWidth().padding(top = 6.dp).height(12.dp)) { + val radius = CornerRadius(size.height / 2) + drawRoundRect(track, cornerRadius = radius) + if (level.live) { + drawRoundRect(fill, size = Size(size.width * fraction(level.db), size.height), cornerRadius = radius) + } + if (thresholdDb != null) { + val x = size.width * fraction(thresholdDb.toDouble()) + drawLine(marker, Offset(x, -2.dp.toPx()), Offset(x, size.height + 2.dp.toPx()), strokeWidth = 2.dp.toPx()) + } + } + } +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Theme.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Theme.kt new file mode 100644 index 0000000..ef8f508 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Theme.kt @@ -0,0 +1,38 @@ +package eu.lixko.ts3j.client.android.ui + +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.dynamicDarkColorScheme +import androidx.compose.material3.dynamicLightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext + +/** Colours that mean the same in either theme, as TeamSpeak uses them. */ +object StatusColors { + val talking = Color(0xFF2E9BF0) + val muted = Color(0xFFD9443A) + val away = Color(0xFF9E8A2E) + val friend = Color(0xFF3A9D4A) + val blocked = Color(0xFFD9443A) +} + +/** Links in chat and descriptions: blue, as links are, whatever the wallpaper's colours. */ +@Composable +fun linkColor(): Color = if (isSystemInDarkTheme()) Color(0xFF7AB4FF) else Color(0xFF1A62D0) + +/** Behind every match of the find bar's query, as on the desktop. */ +@Composable +fun findMatchColor(): Color = if (isSystemInDarkTheme()) Color(0xFF5C4E1A) else Color(0xFFFFEBA3) + +/** Behind the match the find bar is on. */ +@Composable +fun findCurrentColor(): Color = if (isSystemInDarkTheme()) Color(0xFF9C6A12) else Color(0xFFFFB84D) + +/** The system's own (wallpaper) colours, which every supported Android version offers. */ +@Composable +fun Ts3Theme(content: @Composable () -> Unit) { + val context = LocalContext.current + val colors = if (isSystemInDarkTheme()) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) + MaterialTheme(colorScheme = colors, content = content) +} diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Whisper.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Whisper.kt new file mode 100644 index 0000000..cfd1904 --- /dev/null +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Whisper.kt @@ -0,0 +1,254 @@ +package eu.lixko.ts3j.client.android.ui + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import eu.lixko.ts3j.client.android.ServerController +import eu.lixko.ts3j.client.android.SessionController +import eu.lixko.ts3j.client.android.SessionState +import eu.lixko.ts3j.client.config.WhisperList +import eu.lixko.ts3j.client.net.Whisper + +/** Says the microphone whispers instead of talking in the channel, until stopped. */ +@Composable +fun WhisperBanner(state: SessionState, onStop: () -> Unit) { + val target = state.whisper ?: return + Surface(color = MaterialTheme.colorScheme.tertiaryContainer) { + Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) { + PackIcon("WHISPER", null) + Column(Modifier.weight(1f).padding(horizontal = 12.dp)) { + Text("Whispering to $target", maxLines = 1, overflow = TextOverflow.Ellipsis, + style = MaterialTheme.typography.bodyMedium) + if (state.whisperNobody) { + Text("Nobody there", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) + } + } + TextButton(onClick = onStop) { Text("Stop") } + } + } +} + +/** The top bar's whisper button: a list to whisper to, a reply to the last whisper, the lists' editor. */ +@Composable +fun WhisperMenu(vm: SessionController, server: ServerController, state: SessionState, onManage: () -> Unit) { + val lists by vm.whisperLists.collectAsStateWithLifecycle() + var open by remember { mutableStateOf(false) } + Box { + IconButton(onClick = { open = true }) { PackIcon("WHISPER", "Whisper") } + DropdownMenu(open, { open = false }) { + val replyTo = remember(open) { server.lastWhisperer() } + replyTo?.let { client -> + DropdownMenuItem({ Text("Reply to ${client.nickname}") }, leadingIcon = { PackIcon("PLAYER_WHISPER", null) }, + onClick = { open = false; server.whisperToClient(client.id) }) + } + for (list in lists) { + DropdownMenuItem({ Text(list.name.ifBlank { "Unnamed" }) }, + leadingIcon = { PackIcon("ON_WHISPERLIST", null) }, + enabled = !list.isEmpty, + onClick = { open = false; server.setWhisper(Whisper.of(list)) }) + } + if (state.whisper != null) { + DropdownMenuItem({ Text("Stop whispering") }, leadingIcon = { PackIcon("WHISPER", null) }, + onClick = { open = false; server.setWhisper(null) }) + } + if (replyTo != null || lists.isNotEmpty() || state.whisper != null) HorizontalDivider() + DropdownMenuItem({ Text("Whisper lists…") }, leadingIcon = { PackIcon("WHISPERLISTS", null) }, + onClick = { open = false; onManage() }) + } + } +} + +/** Picks the whisper list to add something to, or names a new one. */ +@Composable +fun AddToWhisperListDialog(vm: SessionController, what: String, onDismiss: () -> Unit, onPick: (index: Int, newName: String) -> Unit) { + val lists by vm.whisperLists.collectAsStateWithLifecycle() + var naming by remember { mutableStateOf(false) } + if (naming) { + TextPrompt("New whisper list", "Name", "Add", onDismiss = onDismiss, onConfirm = { + if (it.isNotBlank()) onPick(-1, it.trim()) else onDismiss() + }) + return + } + AlertDialog( + onDismissRequest = onDismiss, + title = { Text("Add $what to") }, + text = { + Column(Modifier.verticalScroll(rememberScrollState())) { + lists.forEachIndexed { index, list -> + ListItem(headlineContent = { Text(list.name.ifBlank { "Unnamed" }) }, + modifier = Modifier.clickable { onPick(index, "") }) + } + ListItem(headlineContent = { Text("New list…") }, modifier = Modifier.clickable { naming = true }) + } + }, + confirmButton = {}, + dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + ) +} + +/** The saved whisper lists, each opening onto its channels and clients. */ +@Composable +fun WhisperListsScreen(vm: SessionController, server: ServerController, onBack: () -> Unit) { + val lists by vm.whisperLists.collectAsStateWithLifecycle() + /** The list being edited: its index, -1 for a new one; null on the overview. */ + var editing by rememberSaveable { mutableStateOf(null) } + editing?.let { index -> + WhisperListScreen(vm, server, index, lists.getOrNull(index) ?: WhisperList(), onBack = { editing = null }) + return + } + SubScreen("Whisper lists", onBack = onBack, actions = { + TextButton(onClick = { editing = -1 }) { Text("New") } + }) { padding -> + if (lists.isEmpty()) { + Box(Modifier.padding(padding).fillMaxWidth().padding(24.dp)) { + Text("No whisper lists", color = MaterialTheme.colorScheme.onSurfaceVariant) + } + return@SubScreen + } + LazyColumn(Modifier.padding(padding)) { + itemsIndexed(lists) { index, list -> + var menu by remember { mutableStateOf(false) } + ListItem( + headlineContent = { Text(list.name.ifBlank { "Unnamed" }) }, + supportingContent = { Text(summary(list)) }, + leadingContent = { PackIcon("ON_WHISPERLIST", null) }, + trailingContent = { + Box { + IconButton(onClick = { menu = true }) { Icon(Icons.Default.MoreVert, "List options") } + DropdownMenu(menu, { menu = false }) { + DropdownMenuItem({ Text("Whisper") }, enabled = !list.isEmpty, onClick = { + menu = false + server.setWhisper(Whisper.of(list)) + onBack() + }) + DropdownMenuItem({ Text("Remove") }, onClick = { menu = false; vm.removeWhisperList(index) }) + } + } + }, + modifier = Modifier.clickable { editing = index }, + ) + } + } + } +} + +private fun summary(list: WhisperList): String { + val parts = listOfNotNull( + list.channels.size.takeIf { it > 0 }?.let { if (it == 1) "1 channel" else "$it channels" }, + list.clients.size.takeIf { it > 0 }?.let { if (it == 1) "1 client" else "$it clients" }, + ) + return parts.joinToString(", ").ifEmpty { "Empty" } +} + +/** One whisper list: its name, channels and clients, saved on Save. */ +@Composable +private fun WhisperListScreen(vm: SessionController, server: ServerController, index: Int, saved: WhisperList, onBack: () -> Unit) { + var name by rememberSaveable { mutableStateOf(saved.name) } + var list by remember { mutableStateOf(saved.copy()) } + val change = { f: WhisperList.() -> Unit -> list = list.copy().apply(f) } + var addingChannel by remember { mutableStateOf(false) } + var addingClient by remember { mutableStateOf(false) } + + SubScreen(if (index < 0) "New whisper list" else "Edit whisper list", onBack = onBack, actions = { + TextButton(onClick = { + vm.saveWhisperList(index, list.copy().apply { this.name = name.trim() }) + onBack() + }, enabled = name.isNotBlank()) { Text("Save") } + }) { padding -> + LazyColumn(Modifier.padding(padding)) { + item { + OutlinedTextField(name, { name = it }, Modifier.fillMaxWidth().padding(16.dp), label = { Text("Name") }, + singleLine = true) + } + item { Section("Channels") } + items(list.channels) { channel -> + RemovableRow("CHANNEL_GREEN", channel) { change { channels.remove(channel) } } + } + item { LinkRow("Add channel…", null, "CHANNEL_CREATE") { addingChannel = true } } + item { Section("Clients") } + items(list.clients) { client -> + RemovableRow("PLAYER_WHISPER", client.nickname.ifBlank { client.uniqueId }) { change { clients.remove(client) } } + } + item { LinkRow("Add client…", null, "ADD_FRIEND") { addingClient = true } } + } + } + + if (addingChannel) { + val paths = remember { server.channelPaths().filter { it !in list.channels } } + ChoiceDialog("Add channel", paths, { it }, onDismiss = { addingChannel = false }) { + addingChannel = false + change { channels.add(it) } + } + } + if (addingClient) { + val online = remember { server.clientRefs().filter { c -> list.clients.none { it.uniqueId == c.uniqueId } } } + ChoiceDialog("Add client", online, { it.nickname }, onDismiss = { addingClient = false }) { + addingClient = false + change { clients.add(it) } + } + } +} + +@Composable +private fun RemovableRow(iconKey: String, label: String, onRemove: () -> Unit) { + ListItem( + headlineContent = { Text(label, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + leadingContent = { PackIcon(iconKey, null) }, + trailingContent = { IconButton(onClick = onRemove) { Icon(Icons.Default.Close, "Remove") } }, + ) +} + +/** Picks one of [choices], of the server on screen; says so when it has none. */ +@Composable +private fun ChoiceDialog(title: String, choices: List, label: (T) -> String, onDismiss: () -> Unit, onPick: (T) -> Unit) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(title) }, + text = { + if (choices.isEmpty()) Text("Nothing to add on this server") + else LazyColumn(Modifier.heightIn(max = 400.dp)) { + items(choices) { choice -> + ListItem(headlineContent = { Text(label(choice), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + modifier = Modifier.clickable { onPick(choice) }) + } + } + }, + confirmButton = {}, + dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + ) +} diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index aaf8773..9b0b2d8 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -1,6 +1,6 @@ - TS3J + TeamSpook TS3j Connection Private messages Pokes diff --git a/android/audio/build.gradle.kts b/android/audio/build.gradle.kts index cd013cc..407fa86 100644 --- a/android/audio/build.gradle.kts +++ b/android/audio/build.gradle.kts @@ -3,7 +3,7 @@ plugins { } android { - namespace = "com.ts3client.android.audio" + namespace = "eu.lixko.ts3j.client.android.audio" compileSdk = 37 ndkVersion = "30.0.16248370" diff --git a/android/audio/src/main/cpp/audio_line.cpp b/android/audio/src/main/cpp/audio_line.cpp index 76dd2b4..2b5cb59 100644 --- a/android/audio/src/main/cpp/audio_line.cpp +++ b/android/audio/src/main/cpp/audio_line.cpp @@ -206,7 +206,7 @@ thread_local std::vector scratch; extern "C" { JNIEXPORT jlong JNICALL -Java_com_ts3client_android_audio_OboeLine_nativeOpen(JNIEnv *env, jclass, jboolean input, jint deviceId, +Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeOpen(JNIEnv *env, jclass, jboolean input, jint deviceId, jint channels, jint preset, jint usage) { auto *created = new AudioLine(input, deviceId, channels, preset, usage); oboe::Result result = created->open(); @@ -219,12 +219,12 @@ Java_com_ts3client_android_audio_OboeLine_nativeOpen(JNIEnv *env, jclass, jboole } JNIEXPORT jint JNICALL -Java_com_ts3client_android_audio_OboeLine_nativeChannels(JNIEnv *, jclass, jlong handle) { +Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeChannels(JNIEnv *, jclass, jlong handle) { return line(handle)->channels(); } JNIEXPORT void JNICALL -Java_com_ts3client_android_audio_OboeLine_nativeStart(JNIEnv *env, jclass, jlong handle) { +Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeStart(JNIEnv *env, jclass, jlong handle) { oboe::Result result = line(handle)->start(); if (result != oboe::Result::OK) { env->ThrowNew(env->FindClass("java/lang/IllegalStateException"), oboe::convertToText(result)); @@ -232,7 +232,7 @@ Java_com_ts3client_android_audio_OboeLine_nativeStart(JNIEnv *env, jclass, jlong } JNIEXPORT void JNICALL -Java_com_ts3client_android_audio_OboeLine_nativeReopen(JNIEnv *env, jclass, jlong handle, jint deviceId, +Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeReopen(JNIEnv *env, jclass, jlong handle, jint deviceId, jint preset, jint usage) { oboe::Result result = line(handle)->reopen(deviceId, preset, usage); if (result != oboe::Result::OK && result != oboe::Result::ErrorClosed) { @@ -241,7 +241,7 @@ Java_com_ts3client_android_audio_OboeLine_nativeReopen(JNIEnv *env, jclass, jlon } JNIEXPORT jint JNICALL -Java_com_ts3client_android_audio_OboeLine_nativeRead(JNIEnv *env, jclass, jlong handle, jbyteArray buffer, +Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeRead(JNIEnv *env, jclass, jlong handle, jbyteArray buffer, jint offset, jint length) { size_t samples = static_cast(length) / sizeof(int16_t); scratch.resize(samples); @@ -252,7 +252,7 @@ Java_com_ts3client_android_audio_OboeLine_nativeRead(JNIEnv *env, jclass, jlong } JNIEXPORT void JNICALL -Java_com_ts3client_android_audio_OboeLine_nativeWrite(JNIEnv *env, jclass, jlong handle, jbyteArray buffer, +Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeWrite(JNIEnv *env, jclass, jlong handle, jbyteArray buffer, jint offset, jint length) { size_t samples = static_cast(length) / sizeof(int16_t); scratch.resize(samples); @@ -262,12 +262,12 @@ Java_com_ts3client_android_audio_OboeLine_nativeWrite(JNIEnv *env, jclass, jlong } JNIEXPORT void JNICALL -Java_com_ts3client_android_audio_OboeLine_nativeClose(JNIEnv *, jclass, jlong handle) { +Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeClose(JNIEnv *, jclass, jlong handle) { line(handle)->close(); } JNIEXPORT void JNICALL -Java_com_ts3client_android_audio_OboeLine_nativeDelete(JNIEnv *, jclass, jlong handle) { +Java_eu_lixko_ts3j_client_android_audio_OboeLine_nativeDelete(JNIEnv *, jclass, jlong handle) { delete line(handle); } diff --git a/android/audio/src/main/cpp/opus_jni.cpp b/android/audio/src/main/cpp/opus_jni.cpp index 248f36a..fc17315 100644 --- a/android/audio/src/main/cpp/opus_jni.cpp +++ b/android/audio/src/main/cpp/opus_jni.cpp @@ -24,7 +24,7 @@ OpusDecoder *decoder(jlong handle) { return reinterpret_cast(hand extern "C" { JNIEXPORT jlong JNICALL -Java_com_ts3client_android_audio_NativeOpus_encoderCreate(JNIEnv *env, jclass, jint sampleRate, jint channels, +Java_eu_lixko_ts3j_client_android_audio_NativeOpus_encoderCreate(JNIEnv *env, jclass, jint sampleRate, jint channels, jint application) { int error = OPUS_OK; OpusEncoder *created = opus_encoder_create(sampleRate, channels, application, &error); @@ -36,14 +36,14 @@ Java_com_ts3client_android_audio_NativeOpus_encoderCreate(JNIEnv *env, jclass, j } JNIEXPORT void JNICALL -Java_com_ts3client_android_audio_NativeOpus_encoderCtl(JNIEnv *env, jclass, jlong handle, jint request, +Java_eu_lixko_ts3j_client_android_audio_NativeOpus_encoderCtl(JNIEnv *env, jclass, jlong handle, jint request, jint value) { int result = opus_encoder_ctl(encoder(handle), request, value); if (result < 0) throwOpus(env, "opus_encoder_ctl", result); } JNIEXPORT jbyteArray JNICALL -Java_com_ts3client_android_audio_NativeOpus_encode(JNIEnv *env, jclass, jlong handle, jfloatArray pcm, +Java_eu_lixko_ts3j_client_android_audio_NativeOpus_encode(JNIEnv *env, jclass, jlong handle, jfloatArray pcm, jint frameSize) { unsigned char packet[kMaxPacketBytes]; jfloat *samples = env->GetFloatArrayElements(pcm, nullptr); @@ -59,12 +59,12 @@ Java_com_ts3client_android_audio_NativeOpus_encode(JNIEnv *env, jclass, jlong ha } JNIEXPORT void JNICALL -Java_com_ts3client_android_audio_NativeOpus_encoderDestroy(JNIEnv *, jclass, jlong handle) { +Java_eu_lixko_ts3j_client_android_audio_NativeOpus_encoderDestroy(JNIEnv *, jclass, jlong handle) { opus_encoder_destroy(encoder(handle)); } JNIEXPORT jlong JNICALL -Java_com_ts3client_android_audio_NativeOpus_decoderCreate(JNIEnv *env, jclass, jint sampleRate, jint channels) { +Java_eu_lixko_ts3j_client_android_audio_NativeOpus_decoderCreate(JNIEnv *env, jclass, jint sampleRate, jint channels) { int error = OPUS_OK; OpusDecoder *created = opus_decoder_create(sampleRate, channels, &error); if (error != OPUS_OK) { @@ -79,7 +79,7 @@ Java_com_ts3client_android_audio_NativeOpus_decoderCreate(JNIEnv *env, jclass, j * rebuilds the packet before {@code packet} from its error correction copy. */ JNIEXPORT jint JNICALL -Java_com_ts3client_android_audio_NativeOpus_decode(JNIEnv *env, jclass, jlong handle, jbyteArray packet, +Java_eu_lixko_ts3j_client_android_audio_NativeOpus_decode(JNIEnv *env, jclass, jlong handle, jbyteArray packet, jfloatArray out, jint frameSize, jboolean fec) { std::vector data; if (packet != nullptr) { @@ -95,17 +95,17 @@ Java_com_ts3client_android_audio_NativeOpus_decode(JNIEnv *env, jclass, jlong ha } JNIEXPORT void JNICALL -Java_com_ts3client_android_audio_NativeOpus_decoderReset(JNIEnv *, jclass, jlong handle) { +Java_eu_lixko_ts3j_client_android_audio_NativeOpus_decoderReset(JNIEnv *, jclass, jlong handle) { opus_decoder_ctl(decoder(handle), OPUS_RESET_STATE); } JNIEXPORT void JNICALL -Java_com_ts3client_android_audio_NativeOpus_decoderDestroy(JNIEnv *, jclass, jlong handle) { +Java_eu_lixko_ts3j_client_android_audio_NativeOpus_decoderDestroy(JNIEnv *, jclass, jlong handle) { opus_decoder_destroy(decoder(handle)); } JNIEXPORT jstring JNICALL -Java_com_ts3client_android_audio_NativeOpus_version0(JNIEnv *env, jclass) { +Java_eu_lixko_ts3j_client_android_audio_NativeOpus_version0(JNIEnv *env, jclass) { return env->NewStringUTF(opus_get_version_string()); } diff --git a/android/audio/src/main/java/com/ts3client/android/audio/AndroidAudioBackend.java b/android/audio/src/main/java/com/ts3client/android/audio/AndroidAudioBackend.java deleted file mode 100644 index 5dd11f2..0000000 --- a/android/audio/src/main/java/com/ts3client/android/audio/AndroidAudioBackend.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.ts3client.android.audio; - -import android.content.Context; - -import com.ts3client.audio.AudioBackend; -import com.ts3client.audio.AudioIo; -import com.ts3client.audio.StreamingVoiceOutput; -import com.ts3client.audio.opus.OpusCodec; - -/** Android's audio stack: Oboe for the devices, libopus built with the NDK. */ -public final class AndroidAudioBackend implements AudioBackend { - - private final AndroidAudioIo io; - private final OpusCodec opus = new NativeOpus(); - - public AndroidAudioBackend(Context context) { - this.io = new AndroidAudioIo(context.getApplicationContext()); - } - - @Override - public AudioIo io() { - return io; - } - - /** How the lines meet Android's audio: microphone preset, and media or call playback. */ - public AudioRoute route() { - return io.route(); - } - - /** Applies at once to the lines that are open. */ - public void setRoute(AudioRoute route) { - io.setRoute(route); - } - - /** Whether the device offers {@link AudioRoute.InputPreset#UNPROCESSED} truly unprocessed. */ - public boolean unprocessedSupported() { - return io.unprocessedSupported(); - } - - /** Runs on the main thread whenever an audio device comes or goes. */ - public void addDeviceListener(Runnable listener) { - io.addDeviceListener(listener); - } - - @Override - public OpusCodec opus() { - return opus; - } - - /** One low-latency stream for everyone, as mobile audio wants. */ - @Override - public StreamingVoiceOutput.Lines outputLines() { - return StreamingVoiceOutput.Lines.SHARED; - } - - @Override - public String description() { - return "Opus " + opus.version() + ", Oboe"; - } -} diff --git a/android/audio/src/main/java/com/ts3client/android/audio/AndroidAudioIo.java b/android/audio/src/main/java/com/ts3client/android/audio/AndroidAudioIo.java deleted file mode 100644 index e098c38..0000000 --- a/android/audio/src/main/java/com/ts3client/android/audio/AndroidAudioIo.java +++ /dev/null @@ -1,332 +0,0 @@ -package com.ts3client.android.audio; - -import android.content.Context; -import android.media.AudioDeviceCallback; -import android.media.AudioDeviceInfo; -import android.media.AudioManager; -import android.os.Handler; -import android.os.Looper; - -import com.ts3client.audio.AudioCapture; -import com.ts3client.audio.AudioDevice; -import com.ts3client.audio.AudioIo; -import com.ts3client.audio.AudioPlayback; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * The device's microphones and speakers, opened through Oboe. - * - *

Android's device ids are handed out anew whenever a device appears, so a Bluetooth - * headset has another one each time it reconnects. What the settings keep is the device's - * type and address instead, which stay the same, and each open looks the id up. - * - *

Also owns the phone's call state: communication mode and the communication device are - * only set while a line needs them, i.e. playback as a call or a headset microphone. - */ -final class AndroidAudioIo implements AudioIo { - - /** AudioDeviceInfo.TYPE_ECHO_REFERENCE, which the SDK keeps as a system API. */ - private static final int TYPE_ECHO_REFERENCE = 28; - - private final AudioManager audioManager; - private final Set open = ConcurrentHashMap.newKeySet(); - /** Reopening streams takes a moment; it happens off the caller's thread, one at a time. */ - private final ExecutorService reopener = Executors.newSingleThreadExecutor(r -> { - Thread t = new Thread(r, "audio-reopen"); - t.setDaemon(true); - return t; - }); - private final List deviceListeners = new ArrayList<>(); - private volatile AudioRoute route = AudioRoute.DEFAULT; - /** Whether this class put the phone into communication mode, and so must take it out. */ - private boolean inCall; - /** The line being opened, which counts towards the call before it exists; null when none is. */ - private String openingDevice; - private boolean openingInput; - - AndroidAudioIo(Context context) { - this.audioManager = context.getSystemService(AudioManager.class); - audioManager.registerAudioDeviceCallback(new AudioDeviceCallback() { - @Override - public void onAudioDevicesAdded(AudioDeviceInfo[] added) { - returnToDevices(added); - notifyDevices(); - } - - @Override - public void onAudioDevicesRemoved(AudioDeviceInfo[] removed) { - notifyDevices(); - } - }, new Handler(Looper.getMainLooper())); - } - - // ---- devices ---- - - @Override - public List inputDevices() { - return devices(AudioManager.GET_DEVICES_INPUTS, true); - } - - @Override - public List outputDevices() { - return devices(AudioManager.GET_DEVICES_OUTPUTS, false); - } - - /** Runs on the main thread whenever a device comes or goes. */ - void addDeviceListener(Runnable listener) { - synchronized (deviceListeners) { - deviceListeners.add(listener); - } - } - - private void notifyDevices() { - synchronized (deviceListeners) { - for (Runnable listener : deviceListeners) listener.run(); - } - } - - private List devices(int flags, boolean input) { - Map out = new LinkedHashMap<>(); - out.put(AudioDevice.DEFAULT.id(), AudioDevice.DEFAULT); - for (AudioDeviceInfo info : audioManager.getDevices(flags)) { - String label = label(info, input); - if (label != null) out.putIfAbsent(key(info), new AudioDevice(key(info), label)); - } - return new ArrayList<>(out.values()); - } - - /** What the settings store for a device. */ - private static String key(AudioDeviceInfo info) { - return info.getType() + ":" + info.getAddress(); - } - - /** The device's current id, or 0 to let the system choose when it is not there. */ - private int resolve(String device, int flags) { - if (device == null || device.isEmpty()) return 0; - for (AudioDeviceInfo info : audioManager.getDevices(flags)) { - if (key(info).equals(device)) return info.getId(); - } - return 0; - } - - private static int flags(OboeLine line) { - return line.isInput() ? AudioManager.GET_DEVICES_INPUTS : AudioManager.GET_DEVICES_OUTPUTS; - } - - /** A picked device that dropped out took its lines to the default; bring them back. */ - private void returnToDevices(AudioDeviceInfo[] added) { - for (AudioDeviceInfo info : added) { - for (OboeLine line : open) { - if (key(info).equals(line.device) && info.isSource() == line.isInput()) { - reopen(line, info.getId()); - } - } - } - } - - // ---- lines ---- - - AudioRoute route() { - return route; - } - - /** Takes on a new route, moving the lines it concerns over at once. */ - void setRoute(AudioRoute newRoute) { - AudioRoute old = route; - route = newRoute; - synchronized (this) { - updateCall(); - } - for (OboeLine line : open) { - boolean affected = line.isInput() - ? old.inputPreset() != newRoute.inputPreset() - : old.usage() != newRoute.usage(); - if (affected) reopen(line, resolve(line.device, flags(line))); - } - } - - private void reopen(OboeLine line, int deviceId) { - reopener.execute(() -> { - try { - line.reopen(deviceId, route); - } catch (IllegalStateException ignored) { - // The stream could not come back on those terms; the line reads silence until closed. - } - }); - } - - @Override - public AudioCapture openCapture(String deviceId, int preferredChannels) { - opening(true, deviceId); - try { - return register(OboeLine.capture(deviceId, resolve(deviceId, AudioManager.GET_DEVICES_INPUTS), - preferredChannels, route, this::closed)); - } finally { - opened(); - } - } - - @Override - public AudioPlayback openPlayback(String deviceId, int preferredChannels) { - opening(false, deviceId); - try { - return register(OboeLine.playback(deviceId, resolve(deviceId, AudioManager.GET_DEVICES_OUTPUTS), - preferredChannels, route, this::closed)); - } finally { - opened(); - } - } - - /** A stream opens on the call as it will be, so the call is set up for it first. */ - private synchronized void opening(boolean input, String device) { - openingInput = input; - openingDevice = device == null ? "" : device; - updateCall(); - } - - private synchronized void opened() { - openingDevice = null; - updateCall(); - } - - private synchronized OboeLine register(OboeLine line) { - open.add(line); - return line; - } - - private synchronized void closed() { - open.removeIf(line -> !line.isOpen()); - updateCall(); - } - - /** - * Puts the phone into communication mode while a line needs it, pointing the call at - * the picked device, and leaves it again once none does. - */ - private void updateCall() { - AudioDeviceInfo headsetMic = null; - String output = null; - List inputs = new ArrayList<>(); - for (OboeLine line : open) { - if (line.isInput()) inputs.add(line.device); - else if (output == null) output = line.device; - } - if (openingDevice != null) { - if (openingInput) inputs.add(openingDevice); - else if (output == null) output = openingDevice; - } - for (String input : inputs) { - AudioDeviceInfo mic = find(input, AudioManager.GET_DEVICES_INPUTS); - if (mic != null && isHeadsetMic(mic)) headsetMic = mic; - } - // Held while anything is open, the microphone included: a notification sound coming - // and going must not take the phone in and out of a call. - boolean call = route.usage() == AudioRoute.Usage.VOICE_COMMUNICATION && (!open.isEmpty() || openingDevice != null); - boolean needed = headsetMic != null || call; - if (needed && !inCall) { - audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION); - inCall = true; - } else if (!needed && inCall) { - audioManager.clearCommunicationDevice(); - audioManager.setMode(AudioManager.MODE_NORMAL); - inCall = false; - } - if (!needed) return; - - // A headset microphone only works over the headset's call link, so it decides. - AudioDeviceInfo target = headsetMic != null - ? communicationDevice(headsetMic.getAddress(), headsetMic.getType()) - : communicationDevice(find(output, AudioManager.GET_DEVICES_OUTPUTS)); - if (target != null) audioManager.setCommunicationDevice(target); - else audioManager.clearCommunicationDevice(); - } - - private AudioDeviceInfo find(String device, int flags) { - if (device == null || device.isEmpty()) return null; - for (AudioDeviceInfo info : audioManager.getDevices(flags)) { - if (key(info).equals(device)) return info; - } - return null; - } - - private static boolean isHeadsetMic(AudioDeviceInfo info) { - return info.getType() == AudioDeviceInfo.TYPE_BLUETOOTH_SCO || info.getType() == AudioDeviceInfo.TYPE_BLE_HEADSET; - } - - /** The communication device that is {@code output}, if calls can go there. */ - private AudioDeviceInfo communicationDevice(AudioDeviceInfo output) { - if (output == null) return null; - // Calls cannot go over A2DP; the same headset's call profile can. - int type = output.getType() == AudioDeviceInfo.TYPE_BLUETOOTH_A2DP ? AudioDeviceInfo.TYPE_BLUETOOTH_SCO : output.getType(); - return communicationDevice(output.getAddress(), type); - } - - private AudioDeviceInfo communicationDevice(String address, int inputType) { - for (AudioDeviceInfo info : audioManager.getAvailableCommunicationDevices()) { - if (info.getType() == inputType && info.getAddress().equals(address)) return info; - } - // Wired and USB headsets, and the built-in microphone, have no address in common with an output. - for (AudioDeviceInfo info : audioManager.getAvailableCommunicationDevices()) { - if (info.getType() == inputType) return info; - } - return null; - } - - boolean unprocessedSupported() { - return "true".equals(audioManager.getProperty(AudioManager.PROPERTY_SUPPORT_AUDIO_SOURCE_UNPROCESSED)); - } - - /** How a device is offered in the settings, or null for one no user would pick. */ - private static String label(AudioDeviceInfo info, boolean input) { - String product = info.getProductName() == null ? "" : info.getProductName().toString(); - String address = info.getAddress(); - switch (info.getType()) { - case AudioDeviceInfo.TYPE_BUILTIN_MIC: - return "Phone microphone" + (address.isEmpty() ? "" : " (" + address + ")"); - case AudioDeviceInfo.TYPE_BUILTIN_SPEAKER: - return "Phone speaker"; - case AudioDeviceInfo.TYPE_BUILTIN_EARPIECE: - return "Earpiece"; - case AudioDeviceInfo.TYPE_WIRED_HEADSET: - return input ? "Wired headset microphone" : "Wired headset"; - case AudioDeviceInfo.TYPE_WIRED_HEADPHONES: - return "Wired headphones"; - case AudioDeviceInfo.TYPE_USB_HEADSET: - case AudioDeviceInfo.TYPE_USB_DEVICE: - case AudioDeviceInfo.TYPE_USB_ACCESSORY: - return product + " (USB)"; - case AudioDeviceInfo.TYPE_BLUETOOTH_A2DP: - return product + " (Bluetooth, media quality)"; - case AudioDeviceInfo.TYPE_BLUETOOTH_SCO: - return product + " (Bluetooth, call quality)"; - case AudioDeviceInfo.TYPE_BLE_HEADSET: - case AudioDeviceInfo.TYPE_BLE_SPEAKER: - return product + " (Bluetooth LE)"; - case AudioDeviceInfo.TYPE_HEARING_AID: - return product + " (hearing aid)"; - case AudioDeviceInfo.TYPE_HDMI: - case AudioDeviceInfo.TYPE_HDMI_ARC: - case AudioDeviceInfo.TYPE_HDMI_EARC: - return "HDMI"; - case AudioDeviceInfo.TYPE_TELEPHONY: - case AudioDeviceInfo.TYPE_REMOTE_SUBMIX: - case AudioDeviceInfo.TYPE_BUILTIN_SPEAKER_SAFE: - case TYPE_ECHO_REFERENCE: - case AudioDeviceInfo.TYPE_FM_TUNER: - case AudioDeviceInfo.TYPE_TV_TUNER: - case AudioDeviceInfo.TYPE_BUS: - case AudioDeviceInfo.TYPE_BLE_BROADCAST: - return null; - default: - return product.isEmpty() ? "Device " + info.getId() : product; - } - } -} diff --git a/android/audio/src/main/java/com/ts3client/android/audio/AudioRoute.java b/android/audio/src/main/java/com/ts3client/android/audio/AudioRoute.java deleted file mode 100644 index d01429e..0000000 --- a/android/audio/src/main/java/com/ts3client/android/audio/AudioRoute.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.ts3client.android.audio; - -/** - * How the app's audio meets Android's: which processing the platform applies to the - * microphone, and whether playback is media or a call. - */ -public record AudioRoute(InputPreset inputPreset, Usage usage) { - - /** The client runs TS3's own processing, so by default the platform adds as little as it can. */ - public static final AudioRoute DEFAULT = new AudioRoute(InputPreset.VOICE_RECOGNITION, Usage.MEDIA); - - /** Oboe's input presets, which are Android's audio sources. */ - public enum InputPreset { - /** Tuned for speech with light or no processing; what the client expects. */ - VOICE_RECOGNITION(6), - /** The platform's call processing: echo cancellation, noise suppression, gain control. */ - VOICE_COMMUNICATION(7), - /** No processing at all, where the device supports it. */ - UNPROCESSED(9), - /** Low latency and no processing, meant for live performance. */ - VOICE_PERFORMANCE(10), - /** The plain microphone source, with whatever the vendor applies to it. */ - GENERIC(1), - CAMCORDER(5); - - final int oboeValue; - - InputPreset(int oboeValue) { - this.oboeValue = oboeValue; - } - } - - /** Oboe's playback usages. */ - public enum Usage { - /** Plays like music: stays on A2DP headphones and leaves the phone out of call mode. */ - MEDIA(1), - /** - * Plays as a call: Android goes into communication mode, which is what its echo - * canceller works against, and Bluetooth headsets switch to their headset profile. - */ - VOICE_COMMUNICATION(2); - - final int oboeValue; - - Usage(int oboeValue) { - this.oboeValue = oboeValue; - } - } -} diff --git a/android/audio/src/main/java/com/ts3client/android/audio/NativeOpus.java b/android/audio/src/main/java/com/ts3client/android/audio/NativeOpus.java deleted file mode 100644 index 5abbb56..0000000 --- a/android/audio/src/main/java/com/ts3client/android/audio/NativeOpus.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.ts3client.android.audio; - -import com.ts3client.audio.opus.CtlOpusEncoder; -import com.ts3client.audio.opus.LibOpus; -import com.ts3client.audio.opus.OpusCodec; -import com.ts3client.audio.opus.OpusDecoder; -import com.ts3client.audio.opus.OpusEncoder; - -/** libopus, built into the app with the NDK. */ -public final class NativeOpus implements OpusCodec { - - static { - System.loadLibrary("ts3audio"); - } - - @Override - public OpusEncoder createEncoder(int sampleRate, int frameSize, int channels, Application application) { - return new Encoder(encoderCreate(sampleRate, channels, LibOpus.application(application)), frameSize); - } - - @Override - public OpusDecoder createDecoder(int sampleRate, int maxFrameSize, int channels) { - return new Decoder(decoderCreate(sampleRate, channels), maxFrameSize); - } - - @Override - public String version() { - return version0(); - } - - /** Methods may come from different threads, one at a time, so they only share the handle. */ - private static final class Encoder extends CtlOpusEncoder { - private final int frameSize; - private long handle; - - Encoder(long handle, int frameSize) { - this.handle = handle; - this.frameSize = frameSize; - } - - @Override - protected synchronized void ctl(int request, int value) { - if (handle != 0) encoderCtl(handle, request, value); - } - - @Override - public synchronized byte[] encode(float[] pcm) { - if (handle == 0) throw new IllegalStateException("encoder closed"); - return NativeOpus.encode(handle, pcm, frameSize); - } - - @Override - public synchronized void close() { - if (handle == 0) return; - encoderDestroy(handle); - handle = 0; - } - } - - private static final class Decoder implements OpusDecoder { - private final int maxFrameSize; - private long handle; - - Decoder(long handle, int maxFrameSize) { - this.handle = handle; - this.maxFrameSize = maxFrameSize; - } - - @Override - public int decode(byte[] packet, float[] out) { - return NativeOpus.decode(live(), packet, out, maxFrameSize, false); - } - - @Override - public int conceal(float[] out, int frameSize) { - return NativeOpus.decode(live(), null, out, Math.min(frameSize, maxFrameSize), false); - } - - @Override - public int recover(byte[] next, float[] out, int frameSize) { - return NativeOpus.decode(live(), next, out, Math.min(frameSize, maxFrameSize), true); - } - - @Override - public void reset() { - if (handle != 0) decoderReset(handle); - } - - @Override - public void close() { - if (handle == 0) return; - decoderDestroy(handle); - handle = 0; - } - - private long live() { - if (handle == 0) throw new IllegalStateException("decoder closed"); - return handle; - } - } - - private static native long encoderCreate(int sampleRate, int channels, int application); - - private static native void encoderCtl(long handle, int request, int value); - - private static native byte[] encode(long handle, float[] pcm, int frameSize); - - private static native void encoderDestroy(long handle); - - private static native long decoderCreate(int sampleRate, int channels); - - private static native int decode(long handle, byte[] packet, float[] out, int frameSize, boolean fec); - - private static native void decoderReset(long handle); - - private static native void decoderDestroy(long handle); - - private static native String version0(); -} diff --git a/android/audio/src/main/java/com/ts3client/android/audio/OboeLine.java b/android/audio/src/main/java/com/ts3client/android/audio/OboeLine.java deleted file mode 100644 index 9dbf707..0000000 --- a/android/audio/src/main/java/com/ts3client/android/audio/OboeLine.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.ts3client.android.audio; - -import com.ts3client.audio.AudioCapture; -import com.ts3client.audio.AudioPlayback; - -/** - * An Oboe stream, as either an {@link AudioCapture} or an {@link AudioPlayback}. The native - * side keeps a ring between the real-time callback and these blocking calls. - */ -final class OboeLine implements AudioCapture, AudioPlayback { - - static { - System.loadLibrary("ts3audio"); - } - - /** Held across native reads and writes, so {@link #close} never frees a line in use. */ - private final Object io = new Object(); - private final int channels; - private final boolean input; - /** The device as the settings name it, to find it again when the line is reopened. */ - final String device; - private final Runnable onClose; - private volatile long handle; - - private OboeLine(boolean input, String device, int deviceId, int channels, AudioRoute route, Runnable onClose) { - this.input = input; - this.device = device; - this.onClose = onClose; - this.handle = nativeOpen(input, deviceId, channels, route.inputPreset().oboeValue, route.usage().oboeValue); - this.channels = nativeChannels(handle); - } - - static OboeLine capture(String device, int deviceId, int channels, AudioRoute route, Runnable onClose) { - return new OboeLine(true, device, deviceId, channels, route, onClose); - } - - static OboeLine playback(String device, int deviceId, int channels, AudioRoute route, Runnable onClose) { - return new OboeLine(false, device, deviceId, channels, route, onClose); - } - - boolean isInput() { - return input; - } - - boolean isOpen() { - return handle != 0; - } - - /** Moves the open stream onto {@code deviceId} with {@code route}; readers and writers carry on. */ - void reopen(int deviceId, AudioRoute route) { - long h = handle; - if (h != 0) nativeReopen(h, deviceId, route.inputPreset().oboeValue, route.usage().oboeValue); - } - - @Override - public int channels() { - return channels; - } - - @Override - public void start() { - long h = handle; - if (h != 0) nativeStart(h); - } - - @Override - public int read(byte[] buffer, int offset, int length) { - synchronized (io) { - long h = handle; - return h == 0 ? 0 : nativeRead(h, buffer, offset, length); - } - } - - @Override - public void write(byte[] buffer, int offset, int length) { - synchronized (io) { - long h = handle; - if (h != 0) nativeWrite(h, buffer, offset, length); - } - } - - /** Oboe has no drain; what is queued is at most a few frames and simply plays out. */ - @Override - public void drain() { - } - - @Override - public void close() { - long h = handle; - if (h == 0) return; - nativeClose(h); // wakes a blocked read or write - synchronized (io) { - if (handle == 0) return; - handle = 0; - nativeDelete(h); - } - onClose.run(); - } - - private static native long nativeOpen(boolean input, int deviceId, int channels, int preset, int usage); - - private static native void nativeReopen(long handle, int deviceId, int preset, int usage); - - private static native int nativeChannels(long handle); - - private static native void nativeStart(long handle); - - private static native int nativeRead(long handle, byte[] buffer, int offset, int length); - - private static native void nativeWrite(long handle, byte[] buffer, int offset, int length); - - private static native void nativeClose(long handle); - - private static native void nativeDelete(long handle); -} diff --git a/android/audio/src/main/java/eu/lixko/ts3j/client/android/audio/AndroidAudioBackend.java b/android/audio/src/main/java/eu/lixko/ts3j/client/android/audio/AndroidAudioBackend.java new file mode 100644 index 0000000..9250d39 --- /dev/null +++ b/android/audio/src/main/java/eu/lixko/ts3j/client/android/audio/AndroidAudioBackend.java @@ -0,0 +1,60 @@ +package eu.lixko.ts3j.client.android.audio; + +import android.content.Context; + +import eu.lixko.ts3j.client.audio.AudioBackend; +import eu.lixko.ts3j.client.audio.AudioIo; +import eu.lixko.ts3j.client.audio.StreamingVoiceOutput; +import eu.lixko.ts3j.client.audio.opus.OpusCodec; + +/** Android's audio stack: Oboe for the devices, libopus built with the NDK. */ +public final class AndroidAudioBackend implements AudioBackend { + + private final AndroidAudioIo io; + private final OpusCodec opus = new NativeOpus(); + + public AndroidAudioBackend(Context context) { + this.io = new AndroidAudioIo(context.getApplicationContext()); + } + + @Override + public AudioIo io() { + return io; + } + + /** How the lines meet Android's audio: microphone preset, and media or call playback. */ + public AudioRoute route() { + return io.route(); + } + + /** Applies at once to the lines that are open. */ + public void setRoute(AudioRoute route) { + io.setRoute(route); + } + + /** Whether the device offers {@link AudioRoute.InputPreset#UNPROCESSED} truly unprocessed. */ + public boolean unprocessedSupported() { + return io.unprocessedSupported(); + } + + /** Runs on the main thread whenever an audio device comes or goes. */ + public void addDeviceListener(Runnable listener) { + io.addDeviceListener(listener); + } + + @Override + public OpusCodec opus() { + return opus; + } + + /** One low-latency stream for everyone, as mobile audio wants. */ + @Override + public StreamingVoiceOutput.Lines outputLines() { + return StreamingVoiceOutput.Lines.SHARED; + } + + @Override + public String description() { + return "Opus " + opus.version() + ", Oboe"; + } +} diff --git a/android/audio/src/main/java/eu/lixko/ts3j/client/android/audio/AndroidAudioIo.java b/android/audio/src/main/java/eu/lixko/ts3j/client/android/audio/AndroidAudioIo.java new file mode 100644 index 0000000..598c18f --- /dev/null +++ b/android/audio/src/main/java/eu/lixko/ts3j/client/android/audio/AndroidAudioIo.java @@ -0,0 +1,332 @@ +package eu.lixko.ts3j.client.android.audio; + +import android.content.Context; +import android.media.AudioDeviceCallback; +import android.media.AudioDeviceInfo; +import android.media.AudioManager; +import android.os.Handler; +import android.os.Looper; + +import eu.lixko.ts3j.client.audio.AudioCapture; +import eu.lixko.ts3j.client.audio.AudioDevice; +import eu.lixko.ts3j.client.audio.AudioIo; +import eu.lixko.ts3j.client.audio.AudioPlayback; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * The device's microphones and speakers, opened through Oboe. + * + *

Android's device ids are handed out anew whenever a device appears, so a Bluetooth + * headset has another one each time it reconnects. What the settings keep is the device's + * type and address instead, which stay the same, and each open looks the id up. + * + *

Also owns the phone's call state: communication mode and the communication device are + * only set while a line needs them, i.e. playback as a call or a headset microphone. + */ +final class AndroidAudioIo implements AudioIo { + + /** AudioDeviceInfo.TYPE_ECHO_REFERENCE, which the SDK keeps as a system API. */ + private static final int TYPE_ECHO_REFERENCE = 28; + + private final AudioManager audioManager; + private final Set open = ConcurrentHashMap.newKeySet(); + /** Reopening streams takes a moment; it happens off the caller's thread, one at a time. */ + private final ExecutorService reopener = Executors.newSingleThreadExecutor(r -> { + Thread t = new Thread(r, "audio-reopen"); + t.setDaemon(true); + return t; + }); + private final List deviceListeners = new ArrayList<>(); + private volatile AudioRoute route = AudioRoute.DEFAULT; + /** Whether this class put the phone into communication mode, and so must take it out. */ + private boolean inCall; + /** The line being opened, which counts towards the call before it exists; null when none is. */ + private String openingDevice; + private boolean openingInput; + + AndroidAudioIo(Context context) { + this.audioManager = context.getSystemService(AudioManager.class); + audioManager.registerAudioDeviceCallback(new AudioDeviceCallback() { + @Override + public void onAudioDevicesAdded(AudioDeviceInfo[] added) { + returnToDevices(added); + notifyDevices(); + } + + @Override + public void onAudioDevicesRemoved(AudioDeviceInfo[] removed) { + notifyDevices(); + } + }, new Handler(Looper.getMainLooper())); + } + + // ---- devices ---- + + @Override + public List inputDevices() { + return devices(AudioManager.GET_DEVICES_INPUTS, true); + } + + @Override + public List outputDevices() { + return devices(AudioManager.GET_DEVICES_OUTPUTS, false); + } + + /** Runs on the main thread whenever a device comes or goes. */ + void addDeviceListener(Runnable listener) { + synchronized (deviceListeners) { + deviceListeners.add(listener); + } + } + + private void notifyDevices() { + synchronized (deviceListeners) { + for (Runnable listener : deviceListeners) listener.run(); + } + } + + private List devices(int flags, boolean input) { + Map out = new LinkedHashMap<>(); + out.put(AudioDevice.DEFAULT.id(), AudioDevice.DEFAULT); + for (AudioDeviceInfo info : audioManager.getDevices(flags)) { + String label = label(info, input); + if (label != null) out.putIfAbsent(key(info), new AudioDevice(key(info), label)); + } + return new ArrayList<>(out.values()); + } + + /** What the settings store for a device. */ + private static String key(AudioDeviceInfo info) { + return info.getType() + ":" + info.getAddress(); + } + + /** The device's current id, or 0 to let the system choose when it is not there. */ + private int resolve(String device, int flags) { + if (device == null || device.isEmpty()) return 0; + for (AudioDeviceInfo info : audioManager.getDevices(flags)) { + if (key(info).equals(device)) return info.getId(); + } + return 0; + } + + private static int flags(OboeLine line) { + return line.isInput() ? AudioManager.GET_DEVICES_INPUTS : AudioManager.GET_DEVICES_OUTPUTS; + } + + /** A picked device that dropped out took its lines to the default; bring them back. */ + private void returnToDevices(AudioDeviceInfo[] added) { + for (AudioDeviceInfo info : added) { + for (OboeLine line : open) { + if (key(info).equals(line.device) && info.isSource() == line.isInput()) { + reopen(line, info.getId()); + } + } + } + } + + // ---- lines ---- + + AudioRoute route() { + return route; + } + + /** Takes on a new route, moving the lines it concerns over at once. */ + void setRoute(AudioRoute newRoute) { + AudioRoute old = route; + route = newRoute; + synchronized (this) { + updateCall(); + } + for (OboeLine line : open) { + boolean affected = line.isInput() + ? old.inputPreset() != newRoute.inputPreset() + : old.usage() != newRoute.usage(); + if (affected) reopen(line, resolve(line.device, flags(line))); + } + } + + private void reopen(OboeLine line, int deviceId) { + reopener.execute(() -> { + try { + line.reopen(deviceId, route); + } catch (IllegalStateException ignored) { + // The stream could not come back on those terms; the line reads silence until closed. + } + }); + } + + @Override + public AudioCapture openCapture(String deviceId, int preferredChannels) { + opening(true, deviceId); + try { + return register(OboeLine.capture(deviceId, resolve(deviceId, AudioManager.GET_DEVICES_INPUTS), + preferredChannels, route, this::closed)); + } finally { + opened(); + } + } + + @Override + public AudioPlayback openPlayback(String deviceId, int preferredChannels) { + opening(false, deviceId); + try { + return register(OboeLine.playback(deviceId, resolve(deviceId, AudioManager.GET_DEVICES_OUTPUTS), + preferredChannels, route, this::closed)); + } finally { + opened(); + } + } + + /** A stream opens on the call as it will be, so the call is set up for it first. */ + private synchronized void opening(boolean input, String device) { + openingInput = input; + openingDevice = device == null ? "" : device; + updateCall(); + } + + private synchronized void opened() { + openingDevice = null; + updateCall(); + } + + private synchronized OboeLine register(OboeLine line) { + open.add(line); + return line; + } + + private synchronized void closed() { + open.removeIf(line -> !line.isOpen()); + updateCall(); + } + + /** + * Puts the phone into communication mode while a line needs it, pointing the call at + * the picked device, and leaves it again once none does. + */ + private void updateCall() { + AudioDeviceInfo headsetMic = null; + String output = null; + List inputs = new ArrayList<>(); + for (OboeLine line : open) { + if (line.isInput()) inputs.add(line.device); + else if (output == null) output = line.device; + } + if (openingDevice != null) { + if (openingInput) inputs.add(openingDevice); + else if (output == null) output = openingDevice; + } + for (String input : inputs) { + AudioDeviceInfo mic = find(input, AudioManager.GET_DEVICES_INPUTS); + if (mic != null && isHeadsetMic(mic)) headsetMic = mic; + } + // Held while anything is open, the microphone included: a notification sound coming + // and going must not take the phone in and out of a call. + boolean call = route.usage() == AudioRoute.Usage.VOICE_COMMUNICATION && (!open.isEmpty() || openingDevice != null); + boolean needed = headsetMic != null || call; + if (needed && !inCall) { + audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION); + inCall = true; + } else if (!needed && inCall) { + audioManager.clearCommunicationDevice(); + audioManager.setMode(AudioManager.MODE_NORMAL); + inCall = false; + } + if (!needed) return; + + // A headset microphone only works over the headset's call link, so it decides. + AudioDeviceInfo target = headsetMic != null + ? communicationDevice(headsetMic.getAddress(), headsetMic.getType()) + : communicationDevice(find(output, AudioManager.GET_DEVICES_OUTPUTS)); + if (target != null) audioManager.setCommunicationDevice(target); + else audioManager.clearCommunicationDevice(); + } + + private AudioDeviceInfo find(String device, int flags) { + if (device == null || device.isEmpty()) return null; + for (AudioDeviceInfo info : audioManager.getDevices(flags)) { + if (key(info).equals(device)) return info; + } + return null; + } + + private static boolean isHeadsetMic(AudioDeviceInfo info) { + return info.getType() == AudioDeviceInfo.TYPE_BLUETOOTH_SCO || info.getType() == AudioDeviceInfo.TYPE_BLE_HEADSET; + } + + /** The communication device that is {@code output}, if calls can go there. */ + private AudioDeviceInfo communicationDevice(AudioDeviceInfo output) { + if (output == null) return null; + // Calls cannot go over A2DP; the same headset's call profile can. + int type = output.getType() == AudioDeviceInfo.TYPE_BLUETOOTH_A2DP ? AudioDeviceInfo.TYPE_BLUETOOTH_SCO : output.getType(); + return communicationDevice(output.getAddress(), type); + } + + private AudioDeviceInfo communicationDevice(String address, int inputType) { + for (AudioDeviceInfo info : audioManager.getAvailableCommunicationDevices()) { + if (info.getType() == inputType && info.getAddress().equals(address)) return info; + } + // Wired and USB headsets, and the built-in microphone, have no address in common with an output. + for (AudioDeviceInfo info : audioManager.getAvailableCommunicationDevices()) { + if (info.getType() == inputType) return info; + } + return null; + } + + boolean unprocessedSupported() { + return "true".equals(audioManager.getProperty(AudioManager.PROPERTY_SUPPORT_AUDIO_SOURCE_UNPROCESSED)); + } + + /** How a device is offered in the settings, or null for one no user would pick. */ + private static String label(AudioDeviceInfo info, boolean input) { + String product = info.getProductName() == null ? "" : info.getProductName().toString(); + String address = info.getAddress(); + switch (info.getType()) { + case AudioDeviceInfo.TYPE_BUILTIN_MIC: + return "Phone microphone" + (address.isEmpty() ? "" : " (" + address + ")"); + case AudioDeviceInfo.TYPE_BUILTIN_SPEAKER: + return "Phone speaker"; + case AudioDeviceInfo.TYPE_BUILTIN_EARPIECE: + return "Earpiece"; + case AudioDeviceInfo.TYPE_WIRED_HEADSET: + return input ? "Wired headset microphone" : "Wired headset"; + case AudioDeviceInfo.TYPE_WIRED_HEADPHONES: + return "Wired headphones"; + case AudioDeviceInfo.TYPE_USB_HEADSET: + case AudioDeviceInfo.TYPE_USB_DEVICE: + case AudioDeviceInfo.TYPE_USB_ACCESSORY: + return product + " (USB)"; + case AudioDeviceInfo.TYPE_BLUETOOTH_A2DP: + return product + " (Bluetooth, media quality)"; + case AudioDeviceInfo.TYPE_BLUETOOTH_SCO: + return product + " (Bluetooth, call quality)"; + case AudioDeviceInfo.TYPE_BLE_HEADSET: + case AudioDeviceInfo.TYPE_BLE_SPEAKER: + return product + " (Bluetooth LE)"; + case AudioDeviceInfo.TYPE_HEARING_AID: + return product + " (hearing aid)"; + case AudioDeviceInfo.TYPE_HDMI: + case AudioDeviceInfo.TYPE_HDMI_ARC: + case AudioDeviceInfo.TYPE_HDMI_EARC: + return "HDMI"; + case AudioDeviceInfo.TYPE_TELEPHONY: + case AudioDeviceInfo.TYPE_REMOTE_SUBMIX: + case AudioDeviceInfo.TYPE_BUILTIN_SPEAKER_SAFE: + case TYPE_ECHO_REFERENCE: + case AudioDeviceInfo.TYPE_FM_TUNER: + case AudioDeviceInfo.TYPE_TV_TUNER: + case AudioDeviceInfo.TYPE_BUS: + case AudioDeviceInfo.TYPE_BLE_BROADCAST: + return null; + default: + return product.isEmpty() ? "Device " + info.getId() : product; + } + } +} diff --git a/android/audio/src/main/java/eu/lixko/ts3j/client/android/audio/AudioRoute.java b/android/audio/src/main/java/eu/lixko/ts3j/client/android/audio/AudioRoute.java new file mode 100644 index 0000000..4eaf80e --- /dev/null +++ b/android/audio/src/main/java/eu/lixko/ts3j/client/android/audio/AudioRoute.java @@ -0,0 +1,49 @@ +package eu.lixko.ts3j.client.android.audio; + +/** + * How the app's audio meets Android's: which processing the platform applies to the + * microphone, and whether playback is media or a call. + */ +public record AudioRoute(InputPreset inputPreset, Usage usage) { + + /** The client runs TS3's own processing, so by default the platform adds as little as it can. */ + public static final AudioRoute DEFAULT = new AudioRoute(InputPreset.VOICE_RECOGNITION, Usage.MEDIA); + + /** Oboe's input presets, which are Android's audio sources. */ + public enum InputPreset { + /** Tuned for speech with light or no processing; what the client expects. */ + VOICE_RECOGNITION(6), + /** The platform's call processing: echo cancellation, noise suppression, gain control. */ + VOICE_COMMUNICATION(7), + /** No processing at all, where the device supports it. */ + UNPROCESSED(9), + /** Low latency and no processing, meant for live performance. */ + VOICE_PERFORMANCE(10), + /** The plain microphone source, with whatever the vendor applies to it. */ + GENERIC(1), + CAMCORDER(5); + + final int oboeValue; + + InputPreset(int oboeValue) { + this.oboeValue = oboeValue; + } + } + + /** Oboe's playback usages. */ + public enum Usage { + /** Plays like music: stays on A2DP headphones and leaves the phone out of call mode. */ + MEDIA(1), + /** + * Plays as a call: Android goes into communication mode, which is what its echo + * canceller works against, and Bluetooth headsets switch to their headset profile. + */ + VOICE_COMMUNICATION(2); + + final int oboeValue; + + Usage(int oboeValue) { + this.oboeValue = oboeValue; + } + } +} diff --git a/android/audio/src/main/java/eu/lixko/ts3j/client/android/audio/NativeOpus.java b/android/audio/src/main/java/eu/lixko/ts3j/client/android/audio/NativeOpus.java new file mode 100644 index 0000000..2f304ff --- /dev/null +++ b/android/audio/src/main/java/eu/lixko/ts3j/client/android/audio/NativeOpus.java @@ -0,0 +1,119 @@ +package eu.lixko.ts3j.client.android.audio; + +import eu.lixko.ts3j.client.audio.opus.CtlOpusEncoder; +import eu.lixko.ts3j.client.audio.opus.LibOpus; +import eu.lixko.ts3j.client.audio.opus.OpusCodec; +import eu.lixko.ts3j.client.audio.opus.OpusDecoder; +import eu.lixko.ts3j.client.audio.opus.OpusEncoder; + +/** libopus, built into the app with the NDK. */ +public final class NativeOpus implements OpusCodec { + + static { + System.loadLibrary("ts3audio"); + } + + @Override + public OpusEncoder createEncoder(int sampleRate, int frameSize, int channels, Application application) { + return new Encoder(encoderCreate(sampleRate, channels, LibOpus.application(application)), frameSize); + } + + @Override + public OpusDecoder createDecoder(int sampleRate, int maxFrameSize, int channels) { + return new Decoder(decoderCreate(sampleRate, channels), maxFrameSize); + } + + @Override + public String version() { + return version0(); + } + + /** Methods may come from different threads, one at a time, so they only share the handle. */ + private static final class Encoder extends CtlOpusEncoder { + private final int frameSize; + private long handle; + + Encoder(long handle, int frameSize) { + this.handle = handle; + this.frameSize = frameSize; + } + + @Override + protected synchronized void ctl(int request, int value) { + if (handle != 0) encoderCtl(handle, request, value); + } + + @Override + public synchronized byte[] encode(float[] pcm) { + if (handle == 0) throw new IllegalStateException("encoder closed"); + return NativeOpus.encode(handle, pcm, frameSize); + } + + @Override + public synchronized void close() { + if (handle == 0) return; + encoderDestroy(handle); + handle = 0; + } + } + + private static final class Decoder implements OpusDecoder { + private final int maxFrameSize; + private long handle; + + Decoder(long handle, int maxFrameSize) { + this.handle = handle; + this.maxFrameSize = maxFrameSize; + } + + @Override + public int decode(byte[] packet, float[] out) { + return NativeOpus.decode(live(), packet, out, maxFrameSize, false); + } + + @Override + public int conceal(float[] out, int frameSize) { + return NativeOpus.decode(live(), null, out, Math.min(frameSize, maxFrameSize), false); + } + + @Override + public int recover(byte[] next, float[] out, int frameSize) { + return NativeOpus.decode(live(), next, out, Math.min(frameSize, maxFrameSize), true); + } + + @Override + public void reset() { + if (handle != 0) decoderReset(handle); + } + + @Override + public void close() { + if (handle == 0) return; + decoderDestroy(handle); + handle = 0; + } + + private long live() { + if (handle == 0) throw new IllegalStateException("decoder closed"); + return handle; + } + } + + private static native long encoderCreate(int sampleRate, int channels, int application); + + private static native void encoderCtl(long handle, int request, int value); + + private static native byte[] encode(long handle, float[] pcm, int frameSize); + + private static native void encoderDestroy(long handle); + + private static native long decoderCreate(int sampleRate, int channels); + + private static native int decode(long handle, byte[] packet, float[] out, int frameSize, boolean fec); + + private static native void decoderReset(long handle); + + private static native void decoderDestroy(long handle); + + private static native String version0(); +} diff --git a/android/audio/src/main/java/eu/lixko/ts3j/client/android/audio/OboeLine.java b/android/audio/src/main/java/eu/lixko/ts3j/client/android/audio/OboeLine.java new file mode 100644 index 0000000..5ea0673 --- /dev/null +++ b/android/audio/src/main/java/eu/lixko/ts3j/client/android/audio/OboeLine.java @@ -0,0 +1,115 @@ +package eu.lixko.ts3j.client.android.audio; + +import eu.lixko.ts3j.client.audio.AudioCapture; +import eu.lixko.ts3j.client.audio.AudioPlayback; + +/** + * An Oboe stream, as either an {@link AudioCapture} or an {@link AudioPlayback}. The native + * side keeps a ring between the real-time callback and these blocking calls. + */ +final class OboeLine implements AudioCapture, AudioPlayback { + + static { + System.loadLibrary("ts3audio"); + } + + /** Held across native reads and writes, so {@link #close} never frees a line in use. */ + private final Object io = new Object(); + private final int channels; + private final boolean input; + /** The device as the settings name it, to find it again when the line is reopened. */ + final String device; + private final Runnable onClose; + private volatile long handle; + + private OboeLine(boolean input, String device, int deviceId, int channels, AudioRoute route, Runnable onClose) { + this.input = input; + this.device = device; + this.onClose = onClose; + this.handle = nativeOpen(input, deviceId, channels, route.inputPreset().oboeValue, route.usage().oboeValue); + this.channels = nativeChannels(handle); + } + + static OboeLine capture(String device, int deviceId, int channels, AudioRoute route, Runnable onClose) { + return new OboeLine(true, device, deviceId, channels, route, onClose); + } + + static OboeLine playback(String device, int deviceId, int channels, AudioRoute route, Runnable onClose) { + return new OboeLine(false, device, deviceId, channels, route, onClose); + } + + boolean isInput() { + return input; + } + + boolean isOpen() { + return handle != 0; + } + + /** Moves the open stream onto {@code deviceId} with {@code route}; readers and writers carry on. */ + void reopen(int deviceId, AudioRoute route) { + long h = handle; + if (h != 0) nativeReopen(h, deviceId, route.inputPreset().oboeValue, route.usage().oboeValue); + } + + @Override + public int channels() { + return channels; + } + + @Override + public void start() { + long h = handle; + if (h != 0) nativeStart(h); + } + + @Override + public int read(byte[] buffer, int offset, int length) { + synchronized (io) { + long h = handle; + return h == 0 ? 0 : nativeRead(h, buffer, offset, length); + } + } + + @Override + public void write(byte[] buffer, int offset, int length) { + synchronized (io) { + long h = handle; + if (h != 0) nativeWrite(h, buffer, offset, length); + } + } + + /** Oboe has no drain; what is queued is at most a few frames and simply plays out. */ + @Override + public void drain() { + } + + @Override + public void close() { + long h = handle; + if (h == 0) return; + nativeClose(h); // wakes a blocked read or write + synchronized (io) { + if (handle == 0) return; + handle = 0; + nativeDelete(h); + } + onClose.run(); + } + + private static native long nativeOpen(boolean input, int deviceId, int channels, int preset, int usage); + + private static native void nativeReopen(long handle, int deviceId, int preset, int usage); + + private static native int nativeChannels(long handle); + + private static native void nativeStart(long handle); + + private static native int nativeRead(long handle, byte[] buffer, int offset, int length); + + private static native void nativeWrite(long handle, byte[] buffer, int offset, int length); + + private static native void nativeClose(long handle); + + private static native void nativeDelete(long handle); +} diff --git a/ts3-client/README.md b/ts3-client/README.md index 2299844..bd99179 100644 --- a/ts3-client/README.md +++ b/ts3-client/README.md @@ -1,4 +1,4 @@ -# TS3J Client +# TeamSpook TS3j A desktop TeamSpeak 3 client built on top of the [`ts3j`](../ts3j) reverse-engineered TS3 protocol library. It looks and behaves like the official TS3 client and focuses @@ -217,7 +217,7 @@ voice activation while watching the live meter. ## Architecture ``` -core/ com.ts3client +core/ eu.lixko.ts3j.client ├── config the profile (~/.ts3jclient): Settings, Bookmarks, IdentityStore, │ AwayMessages, …; AppDirs finds it, ProfileFiles writes it │ privately and all at once @@ -269,7 +269,7 @@ core/ com.ts3client ├── SyncItemDecoder protobuf wire decoding of Item_Data, via ProtobufReader └── TeamSpeakImporter merges synced items into IdentityStore / Bookmarks -desktop/ com.ts3client.audio.desktop + com.ts3client.hotkey.desktop +desktop/ eu.lixko.ts3j.client.audio.desktop + eu.lixko.ts3j.client.hotkey.desktop ├── DesktopAudioBackend PipeWire where it runs, Java Sound elsewhere, and native Opus ├── Opus/NativeOpusCodec Panama (FFM) binding to native libopus ├── AudioDevices device enumeration + line opening (48 kHz/16-bit) @@ -284,7 +284,7 @@ desktop/ com.ts3client.audio.desktop + com.ts3client.hotkey.desktop ├── X11KeyNamer/WindowsKeyNamer layout-aware key labels per platform └── DesktopInputHooks picks the backend that suits the session -swing/ com.ts3client +swing/ eu.lixko.ts3j.client ├── Main entry point (look & feel, settings, backend injection) └── ui ├── MainFrame window: menu, toolbar, tree | chat, status bar diff --git a/ts3-client/core/pom.xml b/ts3-client/core/pom.xml index b25aecc..61f934d 100644 --- a/ts3-client/core/pom.xml +++ b/ts3-client/core/pom.xml @@ -5,13 +5,13 @@ 4.0.0 - com.ts3client + eu.lixko.ts3j.client ts3-client-parent 0.1.0 ts3-client-core - TS3J Client Core + TeamSpook TS3j Core Frontend-agnostic library: protocol integration, model, audio abstractions diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/AudioBackend.java b/ts3-client/core/src/main/java/com/ts3client/audio/AudioBackend.java deleted file mode 100644 index 135d73d..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/AudioBackend.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.ts3client.audio; - -import com.ts3client.audio.opus.OpusCodec; -import com.ts3client.config.Settings; -import com.ts3client.sound.SoundPlayer; -import com.ts3client.sound.PackSoundPlayer; - -/** - * A platform's audio stack: its devices and its libopus. Injected into the connection - * layer so the core stays independent of any concrete audio stack; the voice pipelines - * and the sound player on top are the same everywhere. - */ -public interface AudioBackend { - - AudioIo io(); - - OpusCodec opus(); - - /** How incoming voice reaches this platform's devices. */ - StreamingVoiceOutput.Lines outputLines(); - - default VoiceInput createInput(Settings settings) { - return new CaptureVoiceInput(settings, io(), opus()); - } - - default VoiceOutput createOutput(Settings settings) { - return new StreamingVoiceOutput(io(), opus(), settings.outputDevice, outputLines()); - } - - /** Player for notification sounds (sound packs); shared by all connections. */ - default SoundPlayer createSoundPlayer(Settings settings) { - return new PackSoundPlayer(io(), opus(), settings.outputDevice); - } - - /** Human-readable codec/backend description, e.g. for an "about" line. */ - String description(); -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/AudioCapture.java b/ts3-client/core/src/main/java/com/ts3client/audio/AudioCapture.java deleted file mode 100644 index 827ed76..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/AudioCapture.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.ts3client.audio; - -/** - * An open microphone line, delivering 16-bit little-endian PCM at - * {@link VoiceFormat#SAMPLE_RATE}. - * - *

Modelled on Java Sound's {@code TargetDataLine} so the capture pipeline does - * not care which platform audio API delivers it. - */ -public interface AudioCapture extends AutoCloseable { - - /** Channel count actually negotiated with the device. */ - int channels(); - - /** Begins capturing; audio read before this call is not delivered. */ - void start(); - - /** - * Blocks until {@code length} bytes are captured. Returns fewer bytes only when the - * line is closing or the calling thread was interrupted. - */ - int read(byte[] buffer, int offset, int length); - - @Override - void close(); -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/AudioDevice.java b/ts3-client/core/src/main/java/com/ts3client/audio/AudioDevice.java deleted file mode 100644 index 11145b7..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/AudioDevice.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.ts3client.audio; - -/** A selectable audio device. {@code id} is what gets persisted in the settings. */ -public record AudioDevice(String id, String label) { - - /** The implicit entry that lets the platform choose. */ - public static final AudioDevice DEFAULT = new AudioDevice("", "(System default)"); - - @Override - public String toString() { - return label; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/AudioFrameListener.java b/ts3-client/core/src/main/java/com/ts3client/audio/AudioFrameListener.java deleted file mode 100644 index b1af1a2..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/AudioFrameListener.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.ts3client.audio; - -/** Receives frames of PCM audio as they pass through the capture or playback chain. */ -@FunctionalInterface -public interface AudioFrameListener { - - /** - * Called with one frame of interleaved samples in [-1, 1]. - * - *

The array is reused between calls, so copy anything you need to keep. Called from - * the audio thread: do not block. - * - * @param interleaved samples, {@code channels} per sample position - * @param channels number of interleaved channels - */ - void onFrame(float[] interleaved, int channels); -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/AudioIo.java b/ts3-client/core/src/main/java/com/ts3client/audio/AudioIo.java deleted file mode 100644 index 22247de..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/AudioIo.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.ts3client.audio; - -import java.util.List; - -/** The platform's audio devices: what can be picked, and opening lines on them. */ -public interface AudioIo { - - /** Devices that can provide microphone lines, {@link AudioDevice#DEFAULT} first. */ - List inputDevices(); - - /** Devices that can provide speaker lines, {@link AudioDevice#DEFAULT} first. */ - List outputDevices(); - - /** - * Opens a capture line at {@link VoiceFormat#SAMPLE_RATE}, preferring - * {@code preferredChannels} but falling back to what the device takes; inspect - * {@link AudioCapture#channels()} for the result. An empty id means the default device. - */ - AudioCapture openCapture(String deviceId, int preferredChannels) throws Exception; - - /** Opens a playback line; see {@link #openCapture} for the channel negotiation. */ - AudioPlayback openPlayback(String deviceId, int preferredChannels) throws Exception; -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/AudioPlayback.java b/ts3-client/core/src/main/java/com/ts3client/audio/AudioPlayback.java deleted file mode 100644 index e1e5b95..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/AudioPlayback.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.ts3client.audio; - -/** - * An open speaker line, accepting 16-bit little-endian PCM at - * {@link VoiceFormat#SAMPLE_RATE}. - * - *

Modelled on Java Sound's {@code SourceDataLine} so the playback pipeline does - * not care which platform audio API plays it. - */ -public interface AudioPlayback extends AutoCloseable { - - /** Channel count actually negotiated with the device. */ - int channels(); - - /** Begins playing whatever is written from now on. */ - void start(); - - /** - * Blocks until the audio has been queued for playback. - * - * @throws IllegalStateException once the line is gone for good (its device went away, - * say), so the caller can open another - */ - void write(byte[] buffer, int offset, int length); - - /** Blocks until everything already written has been played out. */ - void drain(); - - @Override - void close(); -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/CaptureVoiceInput.java b/ts3-client/core/src/main/java/com/ts3client/audio/CaptureVoiceInput.java deleted file mode 100644 index dbefd86..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/CaptureVoiceInput.java +++ /dev/null @@ -1,592 +0,0 @@ -package com.ts3client.audio; - -import com.github.manevolent.ts3j.enums.CodecType; -import com.ts3client.audio.opus.OpusCodec; -import com.ts3client.audio.opus.OpusEncoder; -import com.ts3client.audio.processing.AudioProcessor; -import com.ts3client.audio.processing.ns.SuppressionLevel; -import com.ts3client.audio.vad.RnnSpeechDetector; -import com.ts3client.config.Settings; - -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Consumer; - -/** - * The {@link VoiceInput} every platform shares: captures the microphone, applies voice-activation - * or push-to-talk gating, and Opus-encodes 20 ms frames. - * - *

The capture line comes from the platform's {@link AudioIo}; it is opened in stereo - * when the device offers it. Voice - * ({@code OPUS_VOICE}) is transmitted mono, from the downmix, so the pre-processing - * chain and VAD see a single channel; the music codec ({@code OPUS_MUSIC}) transmits - * the stereo capture as-is. - * - *

A dedicated capture thread fills a small packet queue while ts3j polls - * {@link #isReady()} / {@link #provide()} on its own timer, decoupling capture from - * network sending. When the gate closes and the queue drains {@link #isReady()} - * returns {@code false}, prompting ts3j to emit the terminating empty voice packet. - */ -public final class CaptureVoiceInput implements VoiceInput { - - /** - * How long the gate stays open after the last active frame. TS3 counts 64 of its - * 10 ms preprocessor frames before closing, so the tail of a word is never clipped. - */ - private static final int HANGOVER_MS = 640; - - /** - * Audio replayed when the gate opens, so a word's onset is not swallowed by the frame - * that detected it. TS3 keeps up to three 10 ms buffers ({@code vad_extrabuffersize} - * defaults to 2, plus one). - */ - private static final int PREROLL_MS = 30; - - private static final int HANGOVER_FRAMES = - Math.max(1, HANGOVER_MS * VoiceFormat.SAMPLE_RATE / 1000 / VoiceFormat.FRAME_SIZE); - private static final int PREROLL_FRAMES = - Math.max(1, PREROLL_MS * VoiceFormat.SAMPLE_RATE / 1000 / VoiceFormat.FRAME_SIZE); - /** How long stop() waits for the capture loop to finish its frame. */ - private static final long STOP_TIMEOUT_MS = 500; - - private final ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue<>(); - private final AtomicBoolean muted = new AtomicBoolean(false); - private final AtomicBoolean localMuted = new AtomicBoolean(false); - private final AtomicBoolean transmitting = new AtomicBoolean(false); - private final AtomicBoolean pttDown = new AtomicBoolean(false); - private final AtomicBoolean forceDown = new AtomicBoolean(false); - private final AtomicBoolean running = new AtomicBoolean(false); - - private volatile Settings.InputMode mode; - private volatile Settings.VadMode vadMode; - private volatile double thresholdDb; - private volatile double speechThreshold; - private volatile boolean vadOverPtt; - private volatile double inputGain; - private volatile CodecType codec = CodecType.OPUS_VOICE; - private volatile int redundancyDelay; - private volatile int redundancyCopies; - - private final SpeechProbabilityDetector speechDetector = - new RnnSpeechDetector(VoiceFormat.SAMPLE_RATE); - private final AudioProcessor processor = new AudioProcessor(); - - private volatile Consumer levelListener; // input level, InputLevel scale - private volatile Consumer talkListener; // local talk-state changes - private volatile Runnable mutedTalkListener; // speech detected while muted - private volatile AudioFrameListener monitorListener; // local monitoring of what is sent - private boolean mutedTalking; - - private final AudioIo io; - private final OpusCodec opus; - private volatile String deviceName; - - private final Object encoderLock = new Object(); - private volatile OpusParameters params; - private OpusParameters appliedParams; - private OpusCodec.Application encoderApplication; - private volatile int encoderChannels = 1; - private volatile int captureChannels = 1; - - private Thread captureThread; - private AudioCapture line; - private OpusEncoder encoder; - - private int hangover; - private boolean lastTransmitting; - - // Ring of recent frames captured while the gate was shut. - private final float[][] preroll = new float[PREROLL_FRAMES][]; - private int prerollTail; - private int prerollCount; - - public CaptureVoiceInput(Settings settings, AudioIo io, OpusCodec opus) { - this.io = io; - this.opus = opus; - this.deviceName = settings.inputDevice; - this.mode = settings.inputMode; - this.vadMode = settings.vadMode; - this.thresholdDb = settings.vadThresholdDb; - this.speechThreshold = settings.speechThreshold; - this.vadOverPtt = settings.vadOverPtt; - this.inputGain = settings.inputVolume; - this.params = OpusParameters.from(settings); - this.codec = codecFor(params); - setRedundancy(settings.redundancyDelay, settings.redundancyCopies); - processor.setNoiseSuppression(settings.denoise); - processor.setSuppressionLevel(SuppressionLevel.fromDenoiserLevel(settings.denoiserLevel)); - processor.setTransientSuppression(settings.typingAttenuation); - processor.setGainControl(settings.agc); - processor.setGainBoost(settings.agcBoostDb); - } - - // ---- live configuration (safe to call from the UI thread) ---- - - @Override - public synchronized void setInputDevice(String deviceId) { - String device = deviceId == null ? "" : deviceId; - if (device.equals(deviceName)) return; - deviceName = device; - if (running.get()) { - stop(); - start(); - } - } - - public void setMode(Settings.InputMode mode) { - this.mode = mode; - } - - public void setVadMode(Settings.VadMode mode) { - this.vadMode = mode; - speechDetector.reset(); - } - - public void setThresholdDb(double db) { - this.thresholdDb = db; - } - - public void setSpeechThreshold(double threshold) { - this.speechThreshold = threshold; - } - - public void setVadOverPtt(boolean enabled) { - this.vadOverPtt = enabled; - } - - public void setInputGain(double gain) { - this.inputGain = gain; - } - - public void setNoiseSuppression(boolean enabled) { - processor.setNoiseSuppression(enabled); - } - - public void setDenoiserLevel(int level) { - processor.setSuppressionLevel(SuppressionLevel.fromDenoiserLevel(level)); - } - - public void setTypingAttenuation(boolean enabled) { - processor.setTransientSuppression(enabled); - } - - public void setAgc(boolean enabled) { - processor.setGainControl(enabled); - } - - public void setAgcBoost(int db) { - processor.setGainBoost(db); - } - - @Override - public void keyPressed() { - processor.keyPressed(); - } - - /** - * Stages new encoder settings; the capture thread picks them up on the next frame - * (or {@link #start()} applies them directly when idle). - */ - public void setOpusParameters(OpusParameters p) { - this.params = p; - synchronized (encoderLock) { - // While capturing, the codec flag flips together with the encoder swap so - // no packet is ever tagged with a codec it wasn't encoded for. - if (encoder == null) this.codec = codecFor(p); - } - } - - @Override - public void setRedundancy(int delayMillis, int copies) { - this.redundancyDelay = Math.max(0, delayMillis); - this.redundancyCopies = Math.max(1, Math.min(Settings.MAX_REDUNDANCY_COPIES, copies)); - } - - private static OpusCodec.Application applicationFor(OpusParameters p) { - return p.music ? OpusCodec.Application.AUDIO : OpusCodec.Application.VOIP; - } - - private static CodecType codecFor(OpusParameters p) { - return p.music ? CodecType.OPUS_MUSIC : CodecType.OPUS_VOICE; - } - - /** - * Channels to transmit: TeamSpeak's {@code OPUS_MUSIC} stream is stereo, - * {@code OPUS_VOICE} is mono. A mono-only capture device caps this at one. - */ - private int channelsFor(OpusParameters p) { - return (p.music && captureChannels >= 2) ? 2 : 1; - } - - /** Creates or reconfigures the encoder to match {@code p}. Call under {@link #encoderLock}. */ - private void applyParams(OpusParameters p) { - OpusCodec.Application application = applicationFor(p); - int channels = channelsFor(p); - // Application (VOIP vs AUDIO) and channel count are fixed at creation, so - // switching voice<->music means building a new encoder. - if (encoder == null || application != encoderApplication || channels != encoderChannels) { - OpusEncoder replacement = opus.createEncoder( - VoiceFormat.SAMPLE_RATE, VoiceFormat.FRAME_SIZE, channels, application); - configureEncoder(replacement, p); - OpusEncoder previous = encoder; - encoder = replacement; - encoderApplication = application; - encoderChannels = channels; - if (previous != null) previous.close(); - } else { - configureEncoder(encoder, p); - } - codec = codecFor(p); - appliedParams = p; - } - - private static void configureEncoder(OpusEncoder enc, OpusParameters p) { - enc.setBitrate(p.bitrate); - enc.setComplexity(p.complexity); - enc.setVbr(p.vbr); - enc.setInbandFec(p.fec); - enc.setExpectedPacketLoss(p.expectedPacketLoss); - enc.setSignal(p.music ? OpusEncoder.Signal.MUSIC : OpusEncoder.Signal.VOICE); - } - - public void setLevelListener(Consumer l) { - this.levelListener = l; - } - - public void setTalkListener(Consumer l) { - this.talkListener = l; - } - - @Override - public void setMonitorListener(AudioFrameListener l) { - this.monitorListener = l; - } - - @Override - public void setMutedTalkListener(Runnable l) { - this.mutedTalkListener = l; - } - - public void setPushToTalk(boolean down) { - this.pttDown.set(down); - } - - @Override - public void setForceTransmit(boolean down) { - this.forceDown.set(down); - } - - public void setMuted(boolean m) { - this.muted.set(m); - } - - @Override - public void setLocalMuted(boolean m) { - this.localMuted.set(m); - } - - @Override - public boolean isLocalMuted() { - return localMuted.get(); - } - - // ---- lifecycle ---- - - public synchronized void start() { - if (running.get()) return; - try { - line = io.openCapture(deviceName, VoiceFormat.MAX_CHANNELS); - captureChannels = line.channels(); - synchronized (encoderLock) { - applyParams(params); - } - } catch (Throwable t) { - cleanup(); - throw new RuntimeException("Could not start microphone: " + t.getMessage(), t); - } - speechDetector.reset(); - processor.reset(); - running.set(true); - captureThread = new Thread(this::captureLoop, "ts3j-mic-capture"); - captureThread.setDaemon(true); - // Falling behind overruns the device's buffer, losing audio. - captureThread.setPriority(Thread.MAX_PRIORITY); - captureThread.start(); - } - - public synchronized void stop() { - running.set(false); - Thread capture = captureThread; - captureThread = null; - if (line != null) { - line.close(); // wakes the capture loop's blocking read - line = null; - } - if (capture != null) { - // Let the loop finish its frame, so it cannot reopen the gate or overlap a restart. - capture.interrupt(); - try { - capture.join(STOP_TIMEOUT_MS); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - } - cleanup(); - queue.clear(); - setTransmitting(false); - } - - private void cleanup() { - if (line != null) { - line.close(); - line = null; - } - synchronized (encoderLock) { - if (encoder != null) { - try { - encoder.close(); - } catch (Exception ignored) { - } - encoder = null; - encoderApplication = null; - appliedParams = null; - } - } - } - - private void captureLoop() { - final int frameSamples = VoiceFormat.FRAME_SIZE; - final int channels = captureChannels; - final byte[] buf = new byte[frameSamples * 2 * channels]; - final float[] pcm = new float[frameSamples * channels]; // interleaved capture - // Analysis (level, VAD) always runs on a mono downmix; with a mono device that - // is the capture buffer itself, so nothing is copied. - final float[] mono = (channels == 1) ? pcm : new float[frameSamples]; - - // Held locally so a concurrent stop() closing the line cannot null it mid-loop. - final AudioCapture capture = line; - capture.start(); - - while (running.get()) { - // A short read only happens once the line is closing, or on interruption. - if (capture.read(buf, 0, buf.length) < buf.length) break; - - // 16-bit LE -> float, with input gain - for (int i = 0; i < pcm.length; i++) { - int lo = buf[2 * i] & 0xFF; - int hi = buf[2 * i + 1]; - short s = (short) ((hi << 8) | lo); - float f = (float) (s / 32768.0 * inputGain); - if (f > 1f) f = 1f; - else if (f < -1f) f = -1f; - pcm[i] = f; - } - if (channels > 1) { - for (int i = 0; i < frameSamples; i++) { - float sum = 0; - for (int c = 0; c < channels; c++) sum += pcm[i * channels + c]; - mono[i] = sum / channels; - } - } - - byte[] packet = null; - synchronized (encoderLock) { - OpusParameters p = params; - if (p != appliedParams && encoder != null) applyParams(p); - boolean stereo = encoderChannels == 2; - - // As in TS3, the speech detector judges the raw microphone signal, while - // the level meter and volume gate see the processed one. - double probability = usesSpeechDetector() - ? speechDetector.process(mono, frameSamples) : 0.0; - - // Processing is a voice-chain stage on the mono path. A stereo (music) - // stream bypasses it and is transmitted as captured. - if (!stereo) processor.process(mono, frameSamples); - - double db = InputLevel.toDb(mono, frameSamples); - Consumer ll = levelListener; - if (ll != null) ll.accept(db); - - boolean wasOpen = transmitting.get(); - boolean open = decideGate(db, probability); - setTransmitting(open); - - if (open && !muted.get() && encoder != null) { - try { - // On the opening edge, send the buffered lead-in first so the - // word's onset isn't lost to the frame that detected it. - if (!wasOpen) { - flushPreroll(stereo); - } - float[] sent = stereo ? pcm : mono; - packet = encoder.encode(sent); - monitor(sent, stereo ? encoderChannels : 1); - } catch (Exception ignored) { - } - } - if (!open) { - rememberForPreroll(stereo ? pcm : mono); - } - } - - if (packet != null && packet.length > 0) { - offer(packet); - } - } - } - - private void offer(byte[] packet) { - queue.offer(packet); - // Guard against unbounded growth if the network stalls. - while (queue.size() > 10) queue.poll(); - } - - /** Keeps the most recent frames while the gate is shut, for {@link #flushPreroll}. */ - private void rememberForPreroll(float[] frame) { - float[] slot = preroll[prerollTail]; - if (slot == null || slot.length != frame.length) { - slot = new float[frame.length]; - preroll[prerollTail] = slot; - } - System.arraycopy(frame, 0, slot, 0, frame.length); - prerollTail = (prerollTail + 1) % PREROLL_FRAMES; - if (prerollCount < PREROLL_FRAMES) prerollCount++; - } - - /** Encodes and queues the buffered lead-in, oldest first. Call under {@link #encoderLock}. */ - private void flushPreroll(boolean stereo) { - int expected = stereo ? VoiceFormat.FRAME_SIZE * encoderChannels : VoiceFormat.FRAME_SIZE; - for (int i = 0; i < prerollCount; i++) { - int idx = (prerollTail - prerollCount + i + PREROLL_FRAMES) % PREROLL_FRAMES; - float[] frame = preroll[idx]; - // A channel-count change between capture and flush invalidates the buffer. - if (frame == null || frame.length != expected) continue; - try { - byte[] p = encoder.encode(frame); - if (p != null && p.length > 0) offer(p); - monitor(frame, stereo ? encoderChannels : 1); - } catch (Exception ignored) { - } - } - prerollCount = 0; - } - - /** Whether the gate may consult the speech detector, so it must follow the signal. */ - private boolean usesSpeechDetector() { - if (vadMode == Settings.VadMode.VOLUME_GATE) return false; - Settings.InputMode m = mode; - return m == Settings.InputMode.VOICE_ACTIVATION || (m == Settings.InputMode.PUSH_TO_TALK && vadOverPtt); - } - - private boolean decideGate(double db, double probability) { - if (muted.get() || localMuted.get()) { - hangover = 0; - detectMutedSpeech(db); - return false; - } - mutedTalking = false; - if (forceDown.get()) return true; - switch (mode) { - case CONTINUOUS: - return true; - case PUSH_TO_TALK: - if (pttDown.get()) return true; - return vadOverPtt && voiceActivated(db, probability); - case VOICE_ACTIVATION: - default: - return voiceActivated(db, probability); - } - } - - /** - * Applies the selected VAD mode with a hangover so trailing syllables aren't clipped. - * - *

The modes match the TS3 client's: the volume gate alone, the speech detector - * alone, or both together. Volume Gate skips the detector entirely, as TS3 does. - */ - private boolean voiceActivated(double db, double probability) { - boolean detected = switch (vadMode) { - case VOLUME_GATE -> db >= thresholdDb; - case AUTOMATIC -> probability >= speechThreshold; - case HYBRID -> db >= thresholdDb && probability >= speechThreshold; - }; - if (detected) { - hangover = HANGOVER_FRAMES; - return true; - } - if (hangover > 0) { - hangover--; - return true; - } - return false; - } - - /** - * Reports the start of a talk burst that the mute is swallowing. The volume gate - * alone decides here: the speech detector's state is kept for real transmission. - */ - private void detectMutedSpeech(double db) { - boolean talking = db >= thresholdDb; - if (talking && !mutedTalking) { - Runnable listener = mutedTalkListener; - if (listener != null) listener.run(); - } - mutedTalking = talking; - } - - /** Hands a transmitted frame to the monitor, if one is attached. */ - private void monitor(float[] frame, int channels) { - AudioFrameListener l = monitorListener; - if (l != null) l.onFrame(frame, channels); - } - - private void setTransmitting(boolean t) { - transmitting.set(t); - if (t != lastTransmitting) { - lastTransmitting = t; - Consumer tl = talkListener; - if (tl != null) tl.accept(t); - } - } - - // ---- ts3j Microphone contract ---- - - @Override - public boolean isMuted() { - return muted.get(); - } - - @Override - public boolean isReady() { - // Keep the ts3j sender "active" while we're transmitting or still have - // buffered packets. When both are false ts3j sends the terminating packet. - return transmitting.get() || !queue.isEmpty(); - } - - @Override - public boolean isLiveCapture() { - return true; - } - - @Override - public CodecType getCodec() { - return codec; - } - - @Override - public int getRedundancyDelay() { - return redundancyDelay; - } - - @Override - public int getRedundancyCopies() { - return redundancyCopies; - } - - @Override - public byte[] provide() { - byte[] p = queue.poll(); - return p != null ? p : new byte[0]; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/Fft.java b/ts3-client/core/src/main/java/com/ts3client/audio/Fft.java deleted file mode 100644 index 7c4a1d3..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/Fft.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.ts3client.audio; - -/** - * In-place iterative radix-2 Cooley–Tukey FFT shared by the voice DSP stages. - * All arrays must have a power-of-two length. Pure math, no platform dependencies. - */ -public final class Fft { - - private Fft() { - } - - /** Forward transform (unnormalised). */ - public static void forward(double[] re, double[] im) { - transform(re, im, false); - } - - /** Inverse transform, normalised by {@code 1/n} so it inverts {@link #forward}. */ - public static void inverse(double[] re, double[] im) { - transform(re, im, true); - int n = re.length; - double scale = 1.0 / n; - for (int i = 0; i < n; i++) { - re[i] *= scale; - im[i] *= scale; - } - } - - private static void transform(double[] re, double[] im, boolean inverse) { - int n = re.length; - for (int i = 1, j = 0; i < n; i++) { - int bit = n >> 1; - for (; (j & bit) != 0; bit >>= 1) { - j ^= bit; - } - j ^= bit; - if (i < j) { - double tr = re[i]; - re[i] = re[j]; - re[j] = tr; - double ti = im[i]; - im[i] = im[j]; - im[j] = ti; - } - } - double sign = inverse ? 2 * Math.PI : -2 * Math.PI; - for (int len = 2; len <= n; len <<= 1) { - double ang = sign / len; - double wr = Math.cos(ang); - double wi = Math.sin(ang); - for (int i = 0; i < n; i += len) { - double curR = 1, curI = 0; - for (int k = 0; k < len / 2; k++) { - int a = i + k; - int b = i + k + len / 2; - double vr = re[b] * curR - im[b] * curI; - double vi = re[b] * curI + im[b] * curR; - re[b] = re[a] - vr; - im[b] = im[a] - vi; - re[a] += vr; - im[a] += vi; - double nr = curR * wr - curI * wi; - curI = curR * wi + curI * wr; - curR = nr; - } - } - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/InputLevel.java b/ts3-client/core/src/main/java/com/ts3client/audio/InputLevel.java deleted file mode 100644 index 905a093..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/InputLevel.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.ts3client.audio; - -/** - * Capture level on the scale the TeamSpeak 3 client puts on its voice-activation slider. - * - *

TS3 stores {@code voiceactivation_level} in decibels but compares powers: its setter - * converts the slider value with {@code 10^(dB/10) * 0.0095} and its getter reports a - * measured power back with {@code 10*log10(power / 0.0095)}. The same reference constant is - * used here so a threshold of −40 means the same thing it does in TeamSpeak. - * - *

The resulting scale runs from {@link #MIN_DB} to {@link #MAX_DB}, with 0 dB - * corresponding to roughly −20 dBFS and the default −40 to about - * −60 dBFS. - */ -public final class InputLevel { - - /** - * Mean-square level that reads as 0 dB, taken from the client's own dB conversion. - */ - private static final double REFERENCE_POWER = 0.0095; - - /** Lower end of the slider range. */ - public static final double MIN_DB = -50.0; - - /** Upper end of the slider range. */ - public static final double MAX_DB = 50.0; - - /** Reported when the frame is digital silence. */ - public static final double SILENCE_DB = MIN_DB; - - private InputLevel() { - } - - /** Level of {@code length} mono samples in [-1, 1], in dB on the scale above. */ - public static double toDb(float[] frame, int length) { - if (length <= 0) { - return SILENCE_DB; - } - double sumSq = 0; - for (int i = 0; i < length; i++) { - sumSq += (double) frame[i] * frame[i]; - } - return powerToDb(sumSq / length); - } - - /** Converts a mean-square power to the slider's dB scale. */ - public static double powerToDb(double power) { - if (power <= 0) { - return SILENCE_DB; - } - return Math.max(SILENCE_DB, 10.0 * Math.log10(power / REFERENCE_POWER)); - } - - /** Inverse of {@link #powerToDb}, matching the client's threshold conversion. */ - public static double dbToPower(double db) { - return Math.pow(10.0, db / 10.0) * REFERENCE_POWER; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/JitterBuffer.java b/ts3-client/core/src/main/java/com/ts3client/audio/JitterBuffer.java deleted file mode 100644 index 05afcd7..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/JitterBuffer.java +++ /dev/null @@ -1,595 +0,0 @@ -package com.ts3client.audio; - -/** - * Adaptive jitter buffer for incoming voice packets. - * - *

This is a port of the jitter buffer TeamSpeak itself uses: the official client links - * libspeex's {@code libspeex/jitter.c} verbatim (its diagnostics are still in the shipped - * binary) and drives it through the wrapper described in {@link #forTeamSpeakVoice}. The - * algorithm is what makes a voice stream survive a bad network: packets are reordered by - * timestamp, losses are reported so the codec can conceal them, and — most importantly — - * the playback delay continuously re-tunes itself to the measured jitter instead of being - * a fixed guess. - * - *

How the delay adapts

- * Every packet's arrival is recorded as a timing: how early (positive) or late - * (negative) it was relative to the moment it was needed. Timings are kept in three - * rotating sub-windows, each holding only the {@value #MAX_TIMINGS} latest arrivals - * it saw, which makes the set a cheap running estimate of the distribution's late tail. - * {@link #computeOptimalDelay()} then walks the {@value #TOP_DELAY} latest timings and picks - * the delay minimising {@code delay + lateCost * (packets that would then be late)}. The - * result is applied a whole {@link #delayStep} at a time, by dropping a frame to shrink the - * delay or inserting a concealed one to grow it, so the correction is inaudible. - * - *

Timestamp units

- * Timestamps and spans are in caller-defined ticks; the buffer never converts them to time. - * All comparisons are wrap-safe, so a tick counter may overflow freely. - * - *

Not thread-safe: every call must be externally serialised. - */ -public final class JitterBuffer { - - /** Outcome of a {@link #get} call. */ - public enum Status { - /** A packet was available; see {@link #payload()}. */ - OK, - /** Nothing available — the caller should conceal {@link #span()} ticks of loss. */ - MISSING, - /** The buffer is growing its delay; the caller should insert {@link #span()} ticks. */ - INSERTION - } - - /** How many packets may be held at once, awaiting playback or reordering. */ - private static final int MAX_PACKETS = 200; - - /** Timings kept per sub-window. Only the latest arrivals are retained. */ - private static final int MAX_TIMINGS = 40; - - /** Rotating sub-windows the timings are spread over. */ - private static final int SUB_WINDOWS = 3; - - /** How many of the latest timings the delay search considers. */ - private static final int TOP_DELAY = 40; - - /** - * The latest arrival timings seen within one sub-window, sorted ascending. - * - *

Only the {@value #MAX_TIMINGS} latest are kept: an arrival too early to displace - * any of them is counted but not stored, since the delay search only ever looks at the - * late tail. - */ - private static final class TimingWindow { - final int[] timing = new int[MAX_TIMINGS]; - /** Timings actually stored. */ - int filled; - /** Arrivals seen, including those too early to store. */ - int seen; - - void clear() { - filled = 0; - seen = 0; - } - - void add(int value) { - if (filled >= MAX_TIMINGS && value >= timing[filled - 1]) { - seen++; - return; - } - - int pos = 0; - while (pos < filled && value >= timing[pos]) pos++; - - if (pos < filled) { - int moveSize = filled - pos; - if (filled == MAX_TIMINGS) moveSize--; - System.arraycopy(timing, pos, timing, pos + 1, moveSize); - } - timing[pos] = value; - - seen++; - if (filled < MAX_TIMINGS) filled++; - } - } - - private final byte[][] data = new byte[MAX_PACKETS][]; - private final int[] timestamp = new int[MAX_PACKETS]; - private final int[] span = new int[MAX_PACKETS]; - /** Value of {@link #nextStop} when the packet arrived, or 0 if that is unknown. */ - private final int[] arrival = new int[MAX_PACKETS]; - - private final TimingWindow[] windows = new TimingWindow[SUB_WINDOWS]; - /** {@link #windows} in age order, newest first; rotated in place. */ - private final TimingWindow[] byAge = new TimingWindow[SUB_WINDOWS]; - - private final int delayStep; - private final int concealmentSize; - - private int bufferMargin; - private int maxLateRate; - private int lateCost; - private int windowSize; - private int subWindowSize; - - /** Playback position: the timestamp the next {@link #get} wants. */ - private int pointerTimestamp; - /** Timestamp playback will have reached by the time the next packet is needed. */ - private int nextStop; - /** Ticks handed out by the last {@link #get} beyond what was asked for. */ - private int buffered; - /** Ticks of concealment {@link #get} has been told to insert before reading on. */ - private int interpolationRequested; - /** Consecutive {@link #get} calls that found nothing. */ - private int lostCount; - /** True until the first packet arrives and defines the timeline. */ - private boolean resetState; - /** Self-tuned cost of a late packet, used when {@link #lateCost} is 0. */ - private int autoTradeoff; - - // Result of the most recent get(), kept here so the per-frame path allocates nothing. - private byte[] resultPayload; - private int resultTimestamp; - private int resultSpan; - - /** - * @param stepSize granularity of delay changes, and the span of one concealed frame; - * normally the span of a single packet - * @param margin extra delay held on top of the measured optimum - * @param maxLateRate percentage of packets allowed to arrive too late, which also sets - * how long a window the delay is estimated over - * @param lateCost cost of one late packet relative to delay, or 0 to self-tune - */ - public JitterBuffer(int stepSize, int margin, int maxLateRate, int lateCost) { - this.delayStep = stepSize; - this.concealmentSize = stepSize; - this.bufferMargin = margin; - this.lateCost = lateCost; - setMaxLateRate(maxLateRate); - - for (int i = 0; i < SUB_WINDOWS; i++) { - windows[i] = new TimingWindow(); - byAge[i] = windows[i]; - } - reset(); - } - - /** - * A buffer configured the way the official TeamSpeak client configures its own. - * - *

Recovered from {@code ts3client_linux_amd64} (3.6.x): it calls - * {@code jitter_buffer_init(60)} and then sets margin 60 and max late rate 1, pulling - * one 60-tick frame per {@code jitter_buffer_get}. One tick is therefore a sixtieth of - * a 20 ms voice frame, so the delay moves in whole-frame steps, one frame of slack - * is held on top of the measured optimum, and the target is for no more than 1% of - * packets to arrive late — a deliberately conservative setting that estimates over a - * ~1.3 s window and is the reason TeamSpeak rides out network trouble smoothly. - * - * @param ticksPerFrame ticks spanned by one voice frame; see {@link #TEAMSPEAK_TICKS_PER_FRAME} - */ - public static JitterBuffer forTeamSpeakVoice(int ticksPerFrame) { - return new JitterBuffer(ticksPerFrame, ticksPerFrame, 1, 0); - } - - /** Ticks per voice frame in TeamSpeak's own timebase, i.e. a 20 ms frame in 1/3 ms units. */ - public static final int TEAMSPEAK_TICKS_PER_FRAME = 60; - - /** - * Sets the share of packets allowed to arrive too late, as a percentage. - * - *

This doubles as the estimator's time constant: a stricter rate needs a - * proportionally longer window to observe that many late packets. - */ - public void setMaxLateRate(int rate) { - this.maxLateRate = Math.max(1, rate); - this.windowSize = 100 * TOP_DELAY / this.maxLateRate; - this.subWindowSize = this.windowSize / SUB_WINDOWS; - } - - /** - * Sets the extra delay held on top of the measured optimum. The timings already recorded - * are re-based onto it, so the delay moves at the next {@link #tick} rather than once the - * estimate has turned over. - */ - public void setMargin(int margin) { - shiftTimings(bufferMargin - margin); - this.bufferMargin = margin; - } - - public int margin() { - return bufferMargin; - } - - /** Ticks currently held ahead of the playback position, i.e. the live buffering depth. */ - public int bufferedSpan() { - int total = 0; - for (int i = 0; i < MAX_PACKETS; i++) { - if (data[i] != null && ge(timestamp[i], pointerTimestamp)) total += span[i]; - } - return total; - } - - /** True when no packet is held and playback has nothing left to drain. */ - public boolean isEmpty() { - for (int i = 0; i < MAX_PACKETS; i++) { - if (data[i] != null) return false; - } - return true; - } - - /** - * Drops every held packet and forgets both the timeline and the network estimate. - * - *

Reserved for the cases where a speaker's position genuinely stopped meaning - * anything — a new speaker, or a silence long enough that the sequence may have been - * recycled. Notably not something to do between talk bursts: the timeline stays - * valid across a pause because the sender stops numbering while the receiver stops - * playing, and the estimate needs far longer than one burst to be worth anything. - */ - public void reset() { - for (int i = 0; i < MAX_PACKETS; i++) data[i] = null; - pointerTimestamp = 0; - nextStop = 0; - resetState = true; - lostCount = 0; - buffered = 0; - interpolationRequested = 0; - autoTradeoff = 32000; - for (TimingWindow w : windows) w.clear(); - System.arraycopy(windows, 0, byAge, 0, SUB_WINDOWS); - } - - /** - * Offers an arrived packet to the buffer. - * - * @param payload the packet, retained by reference until played or dropped - * @param timestamp the packet's position on the sender's timeline, in ticks - * @param span how many ticks the packet covers - */ - public void put(byte[] payload, int timestamp, int span) { - // Drop anything playback has already moved past. - if (!resetState) { - for (int i = 0; i < MAX_PACKETS; i++) { - if (data[i] != null && le(this.timestamp[i] + this.span[i], pointerTimestamp)) { - data[i] = null; - } - } - } - - // A packet that missed its slot still tells us how far behind the clock we are. - boolean late = !resetState && lt(timestamp, nextStop); - if (late) { - updateTimings(timestamp - nextStop - bufferMargin); - } - - // The consumer has stopped fetching; don't sit on packets it will never take. - if (lostCount > 20) reset(); - - // Ignore packets so late that even concealment has moved past them. - if (!resetState && !ge(timestamp + span + delayStep, pointerTimestamp)) return; - - int slot = -1; - for (int i = 0; i < MAX_PACKETS; i++) { - if (data[i] == null) { - slot = i; - break; - } - } - if (slot < 0) { - // Full: make room by discarding the oldest packet. - slot = 0; - int earliest = this.timestamp[0]; - for (int i = 1; i < MAX_PACKETS; i++) { - if (lt(this.timestamp[i], earliest)) { - earliest = this.timestamp[i]; - slot = i; - } - } - } - - data[slot] = payload; - this.timestamp[slot] = timestamp; - this.span[slot] = span; - this.arrival[slot] = (resetState || late) ? 0 : nextStop; - } - - /** - * Takes the next {@code desiredSpan} ticks of audio. - * - *

On {@link Status#OK} the packet is in {@link #payload()}. On {@link Status#MISSING} - * or {@link Status#INSERTION} the caller must produce {@link #span()} ticks of - * concealment instead — for Opus that means decoding a null packet. - */ - public Status get(int desiredSpan) { - resultPayload = null; - - // The first packet to arrive defines where the timeline starts. - if (resetState) { - int oldest = 0; - boolean found = false; - for (int i = 0; i < MAX_PACKETS; i++) { - if (data[i] != null && (!found || lt(timestamp[i], oldest))) { - oldest = timestamp[i]; - found = true; - } - } - if (!found) { - resultTimestamp = 0; - resultSpan = interpolationRequested; - return Status.MISSING; - } - resetState = false; - pointerTimestamp = oldest; - nextStop = oldest; - } - - // A delay increase decided during the last tick(): pad before reading on. - if (interpolationRequested != 0) { - resultTimestamp = pointerTimestamp; - resultSpan = interpolationRequested; - pointerTimestamp += interpolationRequested; - interpolationRequested = 0; - buffered = resultSpan - desiredSpan; - return Status.INSERTION; - } - - int found = findPacket(desiredSpan); - if (found >= 0) { - lostCount = 0; - - // An on-time arrival: record how much slack it had. - if (arrival[found] != 0) { - updateTimings(timestamp[found] - arrival[found] - bufferMargin); - } - - resultPayload = data[found]; - resultTimestamp = timestamp[found]; - resultSpan = span[found]; - data[found] = null; - - pointerTimestamp = resultTimestamp + resultSpan; - buffered = resultSpan - desiredSpan; - return Status.OK; - } - - lostCount++; - - int optimal = computeOptimalDelay(); - if (optimal < 0) { - // The measured jitter wants a deeper buffer: insert without advancing playback. - shiftTimings(-optimal); - resultTimestamp = pointerTimestamp; - resultSpan = -optimal; - buffered = resultSpan - desiredSpan; - return Status.INSERTION; - } - - // Ordinary loss: conceal a whole number of frames and move on. - int concealed = roundDown(desiredSpan, concealmentSize); - resultTimestamp = pointerTimestamp; - resultSpan = concealed; - pointerTimestamp += concealed; - buffered = concealed - desiredSpan; - return Status.MISSING; - } - - /** - * The held packet sitting at the playback position, without consuming it. - * - *

After a {@link Status#MISSING} the position has already stepped past the gap, so - * this is the packet immediately following the lost one — the one carrying the FEC copy - * that can rebuild it. {@code null} when that packet is missing too. - */ - public byte[] nextPayload() { - for (int i = 0; i < MAX_PACKETS; i++) { - if (data[i] != null && timestamp[i] == pointerTimestamp) return data[i]; - } - return null; - } - - /** The timestamp the next {@link #get} will play from. */ - public int position() { - return pointerTimestamp; - } - - /** Whole frames currently held, given a frame spans {@code frameSpan} ticks. */ - public int heldFrames(int frameSpan) { - int held = 0; - for (int i = 0; i < MAX_PACKETS; i++) { - if (data[i] != null) held += Math.max(1, span[i] / frameSpan); - } - return held; - } - - /** The packet returned by the last {@link #get}, or {@code null} if it was not {@link Status#OK}. */ - public byte[] payload() { - return resultPayload; - } - - /** Ticks covered by the last {@link #get}, whether a real packet or concealment. */ - public int span() { - return resultSpan; - } - - /** Timestamp of the last {@link #get}. */ - public int timestamp() { - return resultTimestamp; - } - - /** - * Advances the playback clock by one frame, after the audio from {@link #get} has been - * handed to the output. This is also where the delay is re-tuned. - */ - public void tick() { - updateDelay(); - nextStop = pointerTimestamp - Math.max(0, buffered); - buffered = 0; - } - - /** - * Advances the playback clock by one frame that the caller played from audio it still had - * from an earlier {@link #get}, instead of calling {@link #get} and {@link #tick}. - * - * @param remaining ticks of that audio still left after this frame - */ - public void remainingSpan(int remaining) { - updateDelay(); - nextStop = pointerTimestamp - remaining; - } - - /** Picks the held packet that best covers the chunk starting at the playback position. */ - private int findPacket(int desiredSpan) { - // Exact start, covering the whole chunk. - for (int i = 0; i < MAX_PACKETS; i++) { - if (data[i] != null && timestamp[i] == pointerTimestamp - && ge(timestamp[i] + span[i], pointerTimestamp + desiredSpan)) { - return i; - } - } - // An earlier packet still covering the whole chunk. - for (int i = 0; i < MAX_PACKETS; i++) { - if (data[i] != null && le(timestamp[i], pointerTimestamp) - && ge(timestamp[i] + span[i], pointerTimestamp + desiredSpan)) { - return i; - } - } - // An earlier packet covering part of it. - for (int i = 0; i < MAX_PACKETS; i++) { - if (data[i] != null && le(timestamp[i], pointerTimestamp) - && gt(timestamp[i] + span[i], pointerTimestamp)) { - return i; - } - } - // Anything starting inside the chunk: prefer the earliest, then the longest. - int best = -1; - for (int i = 0; i < MAX_PACKETS; i++) { - if (data[i] == null) continue; - if (!(lt(timestamp[i], pointerTimestamp + desiredSpan) && ge(timestamp[i], pointerTimestamp))) continue; - if (best < 0 || lt(timestamp[i], timestamp[best]) - || (timestamp[i] == timestamp[best] && gt(span[i], span[best]))) { - best = i; - } - } - return best; - } - - /** - * Applies the delay the timings call for, by scheduling an insertion to grow the buffer - * or skipping ahead to shrink it. The timings are shifted by the same amount so the - * next estimate is made relative to the new delay. - */ - private void updateDelay() { - int optimal = computeOptimalDelay(); - if (optimal == 0) return; - - shiftTimings(-optimal); - pointerTimestamp += optimal; - if (optimal < 0) interpolationRequested = -optimal; - // Held packets measure their slack against when they arrived, so move that with the - // timeline too. libspeex does not, which makes a delay jump of several frames count - // twice: every packet already waiting reports the old shortfall again on playout. - for (int i = 0; i < MAX_PACKETS; i++) { - if (data[i] != null && arrival[i] != 0) arrival[i] += optimal; - } - } - - /** - * Finds the delay minimising {@code delay + lateCost * latePackets} over the observed - * timings, quantised to whole {@link #delayStep}s. - * - * @return ticks to shift playback by: negative to buffer more, positive to catch up - */ - private int computeOptimalDelay() { - int totalSeen = 0; - for (TimingWindow w : windows) totalSeen += w.seen; - if (totalSeen == 0) return 0; - - float lateFactor = lateCost != 0 - ? lateCost * 100.0f / totalSeen - : (float) autoTradeoff * windowSize / totalSeen; - - int[] pos = new int[SUB_WINDOWS]; - int optimal = 0; - int bestCost = Integer.MAX_VALUE; - int late = 0; - boolean penaltyTaken = false; - int earliestSeen = 0; - int latestSeen = 0; - - // Walk the timings from latest to earliest, costing each as a candidate delay. - for (int i = 0; i < TOP_DELAY; i++) { - int next = -1; - int timing = Integer.MAX_VALUE; - for (int j = 0; j < SUB_WINDOWS; j++) { - if (pos[j] < windows[j].filled && windows[j].timing[pos[j]] < timing) { - next = j; - timing = windows[j].timing[pos[j]]; - } - } - if (next < 0) break; - - if (i == 0) latestSeen = timing; - earliestSeen = timing; - timing = roundDown(timing, delayStep); - pos[next]++; - - int cost = (int) (-timing + lateFactor * late); - if (cost < bestCost) { - bestCost = cost; - optimal = timing; - } - - late++; - // Hysteresis: charge extra the first time we would start making packets late. - if (timing >= 0 && !penaltyTaken) { - penaltyTaken = true; - late += 4; - } - } - - autoTradeoff = 1 + (earliestSeen - latestSeen) / TOP_DELAY; - - // Too little evidence to justify shrinking the buffer. - if (totalSeen < TOP_DELAY && optimal > 0) return 0; - return optimal; - } - - /** Records one arrival's slack, rotating the sub-windows when the newest fills up. */ - private void updateTimings(int timing) { - timing = Math.max(-32767, Math.min(32767, timing)); - - if (byAge[0].seen >= subWindowSize) { - TimingWindow oldest = byAge[SUB_WINDOWS - 1]; - System.arraycopy(byAge, 0, byAge, 1, SUB_WINDOWS - 1); - byAge[0] = oldest; - oldest.clear(); - } - byAge[0].add(timing); - } - - /** Re-bases every recorded timing after the delay moved. */ - private void shiftTimings(int amount) { - for (TimingWindow w : windows) { - for (int i = 0; i < w.filled; i++) w.timing[i] += amount; - } - } - - private static int roundDown(int value, int step) { - return value < 0 ? (value - step + 1) / step * step : value / step * step; - } - - // Wrap-safe comparisons, so tick counters may overflow. - private static boolean lt(int a, int b) { - return a - b < 0; - } - - private static boolean le(int a, int b) { - return a - b <= 0; - } - - private static boolean gt(int a, int b) { - return a - b > 0; - } - - private static boolean ge(int a, int b) { - return a - b >= 0; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/MixedPlayout.java b/ts3-client/core/src/main/java/com/ts3client/audio/MixedPlayout.java deleted file mode 100644 index 81ef5c2..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/MixedPlayout.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.ts3client.audio; - -import java.util.Arrays; -import java.util.Collection; -import java.util.function.Supplier; -import java.util.function.ToDoubleFunction; - -/** - * Mixes every speaker onto one playback line, as mobile audio APIs want: a single - * low-latency stream. The line's blocking writes pace the mix, so it runs on the device's - * clock; between talk bursts the mixer writes nothing and waits. - */ -final class MixedPlayout implements Playout { - - private static final int FRAME = VoiceFormat.FRAME_SIZE; - - private final AudioIo io; - private final Supplier outputDevice; - private final ToDoubleFunction gain; - private final Collection streams; - - private final Object lock = new Object(); - /** Guarded by {@link #lock}. */ - private boolean running = true; - private Thread mixer; - - MixedPlayout(AudioIo io, Supplier outputDevice, ToDoubleFunction gain, - Collection streams) { - this.io = io; - this.outputDevice = outputDevice; - this.gain = gain; - this.streams = streams; - } - - @Override - public void started(VoiceStream stream) { - synchronized (lock) { - if (!running) return; - if (mixer == null) { - mixer = new Thread(this::mixLoop, "ts3j-voice-mixer"); - mixer.setDaemon(true); - mixer.start(); - } - lock.notifyAll(); - } - } - - @Override - public void removed(VoiceStream stream) { - // The stream has already left the collection the mixer iterates. - } - - @Override - public void shutdown() { - synchronized (lock) { - running = false; - if (mixer != null) mixer.interrupt(); - lock.notifyAll(); - } - } - - private void mixLoop() { - AudioPlayback line = null; - try { - int channels = 0; - float[] mix = null; - float[] scratch = null; - byte[] out = null; - String device = null; - while (awaitSpeech()) { - if (line != null && !device.equals(outputDevice.get())) { - line.close(); - line = null; - } - if (line == null) { - device = outputDevice.get(); - line = io.openPlayback(device, VoiceFormat.MAX_CHANNELS); - line.start(); - channels = line.channels(); - mix = new float[FRAME * channels]; - scratch = new float[VoiceStream.MAX_FRAME * channels]; - out = new byte[mix.length * 2]; - } - Arrays.fill(mix, 0f); - for (VoiceStream stream : streams) { - int frames = stream.pull(scratch, channels, gain.applyAsDouble(stream)); - // TeamSpeak clients send 20 ms packets; anything longer is cut to the frame. - int samples = Math.min(frames, FRAME) * channels; - for (int i = 0; i < samples; i++) mix[i] += scratch[i]; - } - Pcm16.encode(mix, mix.length, out); - line.write(out, 0, out.length); - } - } catch (Exception ignored) { - // No usable line: this mixer ends, and the next talk burst tries again. - } finally { - if (line != null) line.close(); - synchronized (lock) { - mixer = null; - } - } - } - - /** Waits until some stream is playing; false once shut down. */ - private boolean awaitSpeech() throws InterruptedException { - synchronized (lock) { - while (running) { - for (VoiceStream stream : streams) { - if (stream.isPlaying()) return true; - } - lock.wait(); - } - return false; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/OpusParameters.java b/ts3-client/core/src/main/java/com/ts3client/audio/OpusParameters.java deleted file mode 100644 index 8edc86d..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/OpusParameters.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.ts3client.audio; - -import com.ts3client.config.Settings; - -/** - * Immutable set of Opus encoder settings that a {@link VoiceInput} can apply, - * including while capturing. Frontend-agnostic: carries no native handles. - */ -public final class OpusParameters { - - public static OpusParameters from(Settings s) { - return new OpusParameters(s.bitrate, s.complexity, s.vbr, s.fec, s.packetLoss, s.music); - } - - /** Target bitrate in bits per second. */ - public final int bitrate; - /** Encoder complexity, 0 (fast) .. 10 (best). */ - public final int complexity; - /** Variable bitrate. */ - public final boolean vbr; - /** In-band forward error correction. */ - public final boolean fec; - /** Expected packet loss, 0..100 percent (drives FEC redundancy). */ - public final int expectedPacketLoss; - /** {@code true} to encode as music (OPUS_MUSIC, stereo-friendly); {@code false} for voice. */ - public final boolean music; - - public OpusParameters(int bitrate, int complexity, boolean vbr, boolean fec, - int expectedPacketLoss, boolean music) { - this.bitrate = bitrate; - this.complexity = Math.max(0, Math.min(10, complexity)); - this.vbr = vbr; - this.fec = fec; - this.expectedPacketLoss = Math.max(0, Math.min(100, expectedPacketLoss)); - this.music = music; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/Pcm16.java b/ts3-client/core/src/main/java/com/ts3client/audio/Pcm16.java deleted file mode 100644 index ea38f07..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/Pcm16.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.ts3client.audio; - -/** Conversion between float samples in [-1, 1] and 16-bit little-endian PCM. */ -public final class Pcm16 { - - private Pcm16() { - } - - /** Writes {@code count} samples to {@code out}, clipping anything out of range. */ - public static void encode(float[] samples, int count, byte[] out) { - for (int i = 0; i < count; i++) { - float f = samples[i]; - if (f > 1f) f = 1f; - else if (f < -1f) f = -1f; - int s = Math.round(f * 32767f); - out[2 * i] = (byte) (s & 0xFF); - out[2 * i + 1] = (byte) ((s >> 8) & 0xFF); - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/PerSpeakerPlayout.java b/ts3-client/core/src/main/java/com/ts3client/audio/PerSpeakerPlayout.java deleted file mode 100644 index 9d541c2..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/PerSpeakerPlayout.java +++ /dev/null @@ -1,181 +0,0 @@ -package com.ts3client.audio; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Supplier; -import java.util.function.ToDoubleFunction; - -/** - * Gives every speaker a playback line and worker thread of its own, so simultaneous - * speakers are mixed by the audio server and one slow decode never blocks another. On a - * PipeWire desktop every speaker then shows up as a separate stream in the mixer. - */ -final class PerSpeakerPlayout implements Playout { - - private static final long FRAME_NANOS = - TimeUnit.SECONDS.toNanos(VoiceFormat.FRAME_SIZE) / VoiceFormat.SAMPLE_RATE; - /** Silence after which a speaker's line and thread are given back; the next burst reopens them. */ - private static final long IDLE_RELEASE_NANOS = TimeUnit.SECONDS.toNanos(30); - - private final class Speaker { - final VoiceStream stream; - final AudioPlayback line; - final int lineChannels; - final ExecutorService worker; - final AtomicBoolean tickQueued = new AtomicBoolean(); - /** Touched only by {@link #worker}. */ - final float[] pcm; - final byte[] out; - /** Guarded by this speaker. */ - ScheduledFuture ticks; - /** Guarded by this speaker; a closed speaker is never ticked again. */ - boolean closed; - - Speaker(VoiceStream stream) throws Exception { - this.stream = stream; - this.line = io.openPlayback(outputDevice.get(), VoiceFormat.MAX_CHANNELS); - this.lineChannels = line.channels(); - this.line.start(); - this.pcm = new float[VoiceStream.MAX_FRAME * lineChannels]; - this.out = new byte[pcm.length * 2]; - this.worker = Executors.newSingleThreadExecutor(r -> { - Thread t = new Thread(r, "ts3j-play-" + stream.clientId); - t.setDaemon(true); - return t; - }); - } - - void close() { - synchronized (this) { - closed = true; - if (ticks != null) ticks.cancel(false); - } - worker.shutdownNow(); - line.close(); - } - } - - private final AudioIo io; - private final Supplier outputDevice; - private final ToDoubleFunction gain; - private final ScheduledExecutorService clock; - private final Map speakers = new ConcurrentHashMap<>(); - - PerSpeakerPlayout(AudioIo io, Supplier outputDevice, ToDoubleFunction gain, - ScheduledExecutorService clock) { - this.io = io; - this.outputDevice = outputDevice; - this.gain = gain; - this.clock = clock; - clock.scheduleWithFixedDelay(this::releaseIdle, 1, 1, TimeUnit.SECONDS); - } - - @Override - public void started(VoiceStream stream) { - while (true) { - Speaker speaker = speakers.get(stream); - if (speaker == null) { - try { - speaker = new Speaker(stream); - } catch (Exception e) { - stream.stop(); // couldn't open a line; drop the burst - return; - } - Speaker existing = speakers.putIfAbsent(stream, speaker); - if (existing != null) { - speaker.close(); - speaker = existing; - } - } - synchronized (speaker) { - if (speaker.closed) { - // Released a moment ago; this burst gets a fresh line. - speakers.remove(stream, speaker); - continue; - } - if (speaker.ticks == null) { - Speaker s = speaker; - speaker.ticks = clock.scheduleAtFixedRate( - () -> queueTick(s), FRAME_NANOS, FRAME_NANOS, TimeUnit.NANOSECONDS); - } - return; - } - } - } - - /** Gives back the line and thread of every speaker that has been silent for a while. */ - private void releaseIdle() { - long now = System.nanoTime(); - for (Speaker speaker : speakers.values()) { - synchronized (speaker) { - if (speaker.ticks != null || now - speaker.stream.lastPacketNanos() < IDLE_RELEASE_NANOS) continue; - speaker.closed = true; - } - speakers.remove(speaker.stream, speaker); - speaker.close(); - } - } - - private void queueTick(Speaker speaker) { - if (!speaker.tickQueued.compareAndSet(false, true)) return; - try { - speaker.worker.submit(() -> { - try { - tick(speaker); - } finally { - speaker.tickQueued.set(false); - } - }); - } catch (RuntimeException e) { - if (speaker.worker.isShutdown()) { - speaker.tickQueued.set(false); - } else { - throw e; - } - } - } - - private void tick(Speaker speaker) { - int frames = speaker.stream.pull(speaker.pcm, speaker.lineChannels, gain.applyAsDouble(speaker.stream)); - if (frames == VoiceStream.IDLE) { - synchronized (speaker) { - // A packet may have started the next burst since the pull; keep ticking then. - if (!speaker.stream.isPlaying() && speaker.ticks != null) { - speaker.ticks.cancel(false); - speaker.ticks = null; - } - } - return; - } - if (frames == 0) return; - int samples = frames * speaker.lineChannels; - Pcm16.encode(speaker.pcm, samples, speaker.out); - try { - speaker.line.write(speaker.out, 0, samples * 2); - } catch (RuntimeException e) { - // The line died (a device went away, say). Drop it rather than keep writing into it: - // the speaker's next packet starts a burst on a fresh one. - speakers.remove(speaker.stream, speaker); - speaker.close(); - speaker.stream.stop(); - } - } - - @Override - public void removed(VoiceStream stream) { - Speaker speaker = speakers.remove(stream); - if (speaker != null) speaker.close(); - } - - @Override - public void shutdown() { - for (Speaker speaker : speakers.values()) speaker.close(); - speakers.clear(); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/Playout.java b/ts3-client/core/src/main/java/com/ts3client/audio/Playout.java deleted file mode 100644 index c691b3f..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/Playout.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.ts3client.audio; - -/** Drives the {@link VoiceStream}s of a {@link StreamingVoiceOutput} out to the speakers. */ -interface Playout { - - /** A stream began a talk burst and must now be pulled every 20 ms. */ - void started(VoiceStream stream); - - /** The stream's client left; it will not be pulled again. */ - void removed(VoiceStream stream); - - void shutdown(); -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/SpeechProbabilityDetector.java b/ts3-client/core/src/main/java/com/ts3client/audio/SpeechProbabilityDetector.java deleted file mode 100644 index ddf04aa..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/SpeechProbabilityDetector.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.ts3client.audio; - -/** - * Estimates how likely it is that a frame of captured audio contains speech. - * - *

Used by the "Automatic" and "Hybrid" voice-activation modes. Implementations are - * stateful and expect frames in capture order; {@link #reset()} clears that state. - * - *

Pure DSP with no platform dependencies, so any frontend or backend can reuse it. - */ -public interface SpeechProbabilityDetector { - - /** - * Consumes one frame of mono PCM in [-1, 1] and returns the current speech - * probability in [0, 1]. - * - * @param frame samples in capture order - * @param length number of valid samples in {@code frame} - */ - double process(float[] frame, int length); - - /** Speech probability from the most recent {@link #process} call. */ - double probability(); - - /** Drops all history. Call on a capture discontinuity or a settings change. */ - void reset(); -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/StreamingVoiceOutput.java b/ts3-client/core/src/main/java/com/ts3client/audio/StreamingVoiceOutput.java deleted file mode 100644 index 5a25131..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/StreamingVoiceOutput.java +++ /dev/null @@ -1,221 +0,0 @@ -package com.ts3client.audio; - -import com.github.manevolent.ts3j.enums.CodecType; -import com.github.manevolent.ts3j.protocol.packet.PacketBody0Voice; -import com.github.manevolent.ts3j.protocol.packet.PacketBody1VoiceWhisper; -import com.ts3client.audio.opus.OpusCodec; - -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.function.BiConsumer; - -/** - * The {@link VoiceOutput} every platform shares: decodes incoming voice per speaker, each - * through its own jitter buffer, and plays it on the platform's {@link AudioIo}. - */ -public final class StreamingVoiceOutput implements VoiceOutput { - - /** How speakers reach the device. */ - public enum Lines { - /** A line per speaker, mixed by the platform's audio server. */ - PER_SPEAKER, - /** One line all speakers are mixed onto here. */ - SHARED - } - - /** - * A speaker is only meant to stop when the empty voice packet marking the end of a - * talk burst arrives — but that packet is UDP too, and a lost one otherwise leaves - * the talking indicator stuck until the speaker's next burst. Opus frames are 20 ms - * apart while someone is actually talking, so a gap several times that long, with no - * packet of either kind, is unambiguous: force the indicator off rather than trust - * the one packet that could go missing. - */ - private static final long TALK_TIMEOUT_NANOS = TimeUnit.MILLISECONDS.toNanos(400); - - private final OpusCodec opus; - private final Map streams = new ConcurrentHashMap<>(); - private final Set mutedClients = ConcurrentHashMap.newKeySet(); - /** Per-client gain on top of the master volume; absent means 1.0. */ - private final Map clientVolumes = new ConcurrentHashMap<>(); - /** What came in from speakers who have left. */ - private volatile VoiceReceiveStats departed = VoiceReceiveStats.NONE; - - private volatile String outputDevice; - private volatile double masterVolume = 1.0; - /** Extra playback delay, in jitter buffer ticks. */ - private volatile int extraDelayTicks; - private volatile boolean deafened = false; - - /** Notified (clientId, talking) on an audio thread when a speaker starts/stops. */ - private volatile BiConsumer talkListener; - private volatile VoiceTap voiceTap; - - /** Catches talk bursts whose end packet never arrived, and paces per-speaker lines. */ - private final ScheduledExecutorService clock = Executors.newSingleThreadScheduledExecutor(r -> { - Thread t = new Thread(r, "ts3j-talk-watchdog"); - t.setDaemon(true); - return t; - }); - private final Playout playout; - - public StreamingVoiceOutput(AudioIo io, OpusCodec opus, String outputDevice, Lines lines) { - this.opus = opus; - this.outputDevice = outputDevice == null ? "" : outputDevice; - this.playout = switch (lines) { - case PER_SPEAKER -> new PerSpeakerPlayout(io, () -> this.outputDevice, this::gainFor, clock); - case SHARED -> new MixedPlayout(io, () -> this.outputDevice, this::gainFor, streams.values()); - }; - clock.scheduleWithFixedDelay(this::checkTalkTimeouts, 50, 50, TimeUnit.MILLISECONDS); - } - - private void checkTalkTimeouts() { - long now = System.nanoTime(); - for (VoiceStream s : streams.values()) { - if (s.isTalking() && now - s.lastPacketNanos() > TALK_TIMEOUT_NANOS) s.stop(); - } - } - - private double gainFor(VoiceStream stream) { - return masterVolume * clientVolumes.getOrDefault(stream.clientId, 1.0); - } - - private void fireTalk(int clientId, boolean talking) { - BiConsumer l = talkListener; - if (l != null) l.accept(clientId, talking); - } - - @Override - public void setTalkListener(BiConsumer l) { - this.talkListener = l; - } - - @Override - public void setVoiceTap(VoiceTap tap) { - this.voiceTap = tap; - for (VoiceStream s : streams.values()) s.setTap(tap); - } - - @Override - public void setMasterVolume(double v) { - this.masterVolume = Math.max(0, Math.min(2.0, v)); - } - - @Override - public void setDeafened(boolean d) { - this.deafened = d; - if (d) { - // Stop everyone talking immediately. - for (VoiceStream s : streams.values()) s.stop(); - } - } - - @Override - public boolean isDeafened() { - return deafened; - } - - @Override - public void setClientMuted(int clientId, boolean muted) { - if (muted) { - mutedClients.add(clientId); - VoiceStream s = streams.get(clientId); - if (s != null) s.stop(); - } else { - mutedClients.remove(clientId); - } - } - - @Override - public boolean isClientMuted(int clientId) { - return mutedClients.contains(clientId); - } - - @Override - public void setClientVolume(int clientId, double gain) { - if (gain == 1.0) clientVolumes.remove(clientId); - else clientVolumes.put(clientId, Math.max(0, gain)); - } - - @Override - public double getClientVolume(int clientId) { - return clientVolumes.getOrDefault(clientId, 1.0); - } - - @Override - public void setOutputDevice(String device) { - this.outputDevice = device == null ? "" : device; - } - - @Override - public void setReceiveBuffer(int ms) { - int frames = Math.max(0, ms) * (VoiceFormat.SAMPLE_RATE / 1000) / VoiceFormat.FRAME_SIZE; - extraDelayTicks = frames * JitterBuffer.TEAMSPEAK_TICKS_PER_FRAME; - for (VoiceStream s : streams.values()) s.setExtraDelay(extraDelayTicks); - } - - /** Entry point wired into {@code client.setVoiceHandler(...)}. */ - @Override - public void handleVoice(PacketBody0Voice voice) { - route(voice.getClientId(), voice.getPacketId(), voice.getCodecType(), voice.getCodecData()); - } - - /** Entry point wired into {@code client.setWhisperHandler(...)}. */ - @Override - public void handleWhisper(PacketBody1VoiceWhisper whisper) { - route(whisper.getClientId(), whisper.getPacketId(), whisper.getCodecType(), whisper.getCodecData()); - } - - private void route(int clientId, int packetId, CodecType codec, byte[] data) { - if (deafened) return; - if (mutedClients.contains(clientId)) return; - - VoiceStream stream = streams.computeIfAbsent(clientId, id -> { - VoiceStream created = new VoiceStream(id, opus, this::fireTalk); - created.setTap(voiceTap); - created.setExtraDelay(extraDelayTicks); - return created; - }); - if (stream.offer(packetId, codec, data)) playout.started(stream); - } - - /** Forgets a client that left; the server may hand its id to somebody else. */ - @Override - public void removeClient(int clientId) { - VoiceStream s = streams.remove(clientId); - if (s != null) { - synchronized (this) { - departed = departed.plus(s.stats()); - } - playout.removed(s); - s.close(); - } - mutedClients.remove(clientId); - clientVolumes.remove(clientId); - } - - @Override - public VoiceReceiveStats receiveStats(int clientId) { - VoiceStream s = streams.get(clientId); - return s == null ? null : s.stats(); - } - - @Override - public VoiceReceiveStats receiveStats() { - VoiceReceiveStats total = departed; - for (VoiceStream s : streams.values()) total = total.plus(s.stats()); - return total; - } - - @Override - public void shutdown() { - clock.shutdownNow(); - playout.shutdown(); - for (VoiceStream s : streams.values()) s.close(); - streams.clear(); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/VoiceFormat.java b/ts3-client/core/src/main/java/com/ts3client/audio/VoiceFormat.java deleted file mode 100644 index cb4bd97..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/VoiceFormat.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.ts3client.audio; - -/** - * The PCM format voice is captured, processed and played in. TeamSpeak's Opus codecs run at - * 48 kHz in 20 ms frames, mono for {@code OPUS_VOICE} and stereo for {@code OPUS_MUSIC}. - */ -public final class VoiceFormat { - - public static final int SAMPLE_RATE = 48_000; - /** Samples per channel in one 20 ms frame. */ - public static final int FRAME_SIZE = 960; - public static final int MAX_CHANNELS = 2; - - private VoiceFormat() { - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/VoiceInput.java b/ts3-client/core/src/main/java/com/ts3client/audio/VoiceInput.java deleted file mode 100644 index ae5bfaa..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/VoiceInput.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.ts3client.audio; - -import com.github.manevolent.ts3j.audio.Microphone; -import com.ts3client.config.Settings; - -import java.util.function.Consumer; - -/** - * Voice capture source feeding the TS3 socket. Extends ts3j's {@link Microphone} - * (the encoded-packet supplier) with capture lifecycle and voice-gating controls - * so the connection layer can drive it without knowing the platform backend. - */ -public interface VoiceInput extends Microphone { - - void start(); - - void stop(); - - void setMuted(boolean muted); - - /** - * Silences capture the same way {@link #setMuted} does, but locally only: it does - * not touch {@link #isMuted}, so the mute status published to the server (and the - * mute/unmute sound) is unaffected. TS3's "Local Mic Mute". - */ - void setLocalMuted(boolean muted); - - boolean isLocalMuted(); - - /** Moves capture to another device, reopening at once if capturing; empty is the default. */ - void setInputDevice(String deviceId); - - void setMode(Settings.InputMode mode); - - void setVadMode(Settings.VadMode mode); - - /** Volume-gate threshold on {@link InputLevel}'s scale. */ - void setThresholdDb(double db); - - /** Speech-probability threshold (0..1) for Automatic/Hybrid modes. */ - void setSpeechThreshold(double threshold); - - /** Keep voice activation active while in push-to-talk mode. */ - void setVadOverPtt(boolean enabled); - - void setInputGain(double gain); - - /** Enables removal of steady background noise (WebRTC noise suppression). */ - void setNoiseSuppression(boolean enabled); - - /** Noise suppression strength as TS3's {@code denoiser_level}: 0 (6 dB) .. 3 (21 dB). */ - void setDenoiserLevel(int level); - - /** Enables attenuation of keyboard clicks while the user is typing. */ - void setTypingAttenuation(boolean enabled); - - /** Reports a key press anywhere on the system; typing attenuation only acts while typing. */ - void keyPressed(); - - /** Enables automatic gain control (normalise microphone loudness). */ - void setAgc(boolean enabled); - - /** Lets AGC raise the background noise this many dB more to bring up a quiet voice. */ - void setAgcBoost(int db); - - /** Applies Opus encoder parameters, taking effect immediately if capturing. */ - void setOpusParameters(OpusParameters parameters); - - /** Sends every voice packet {@code copies} more times, {@code delayMillis} apart; a delay of 0 sends it once. */ - void setRedundancy(int delayMillis, int copies); - - void setPushToTalk(boolean pressed); - - /** Transmits while held, whatever the input mode or the gate says; a mute still wins. */ - void setForceTransmit(boolean pressed); - - /** Receives the live input level on {@link InputLevel}'s scale, once per captured frame. */ - void setLevelListener(Consumer listener); - - /** Receives local transmit-state transitions (talking / silent). */ - void setTalkListener(Consumer listener); - - /** - * Receives every frame that is actually transmitted, for local monitoring: the audio - * after pre-processing and gating, including the pre-roll replayed when the gate opens. - * Nothing is delivered while the gate is shut or the microphone is muted. - */ - void setMonitorListener(AudioFrameListener listener); - - /** Called when speech is detected while the microphone is muted. */ - void setMutedTalkListener(Runnable listener); - - /** Takes on the voice settings, as they stand now, while capturing. */ - default void apply(Settings settings) { - setInputDevice(settings.inputDevice); - setMode(settings.inputMode); - setVadMode(settings.vadMode); - setThresholdDb(settings.vadThresholdDb); - setSpeechThreshold(settings.speechThreshold); - setVadOverPtt(settings.vadOverPtt); - setInputGain(settings.inputVolume); - setNoiseSuppression(settings.denoise); - setDenoiserLevel(settings.denoiserLevel); - setTypingAttenuation(settings.typingAttenuation); - setAgc(settings.agc); - setAgcBoost(settings.agcBoostDb); - setOpusParameters(OpusParameters.from(settings)); - setRedundancy(settings.redundancyDelay, settings.redundancyCopies); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/VoiceOutput.java b/ts3-client/core/src/main/java/com/ts3client/audio/VoiceOutput.java deleted file mode 100644 index d6bfd35..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/VoiceOutput.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.ts3client.audio; - -import com.github.manevolent.ts3j.protocol.packet.PacketBody0Voice; -import com.github.manevolent.ts3j.protocol.packet.PacketBody1VoiceWhisper; - -import java.util.function.BiConsumer; - -/** - * Playback sink for incoming voice packets. The connection layer registers - * {@link #handleVoice} as the socket's voice handler; the backend decodes and - * renders per speaker. - */ -public interface VoiceOutput { - - void handleVoice(PacketBody0Voice voice); - - /** Handles a whisper (targeted voice) packet; decoded and played like normal voice. */ - void handleWhisper(PacketBody1VoiceWhisper whisper); - - void setMasterVolume(double volume); - - void setDeafened(boolean deafened); - - boolean isDeafened(); - - void setClientMuted(int clientId, boolean muted); - - boolean isClientMuted(int clientId); - - /** Scales one client's voice on top of the master volume; 1.0 is unchanged, the default. */ - void setClientVolume(int clientId, double gain); - - double getClientVolume(int clientId); - - void setOutputDevice(String device); - - /** - * Delays every speaker by {@code ms} more than the network calls for, trading latency for - * fewer dropouts on a bad connection. - */ - void setReceiveBuffer(int ms); - - void removeClient(int clientId); - - void shutdown(); - - /** Receives remote speaker talk-state transitions as (clientId, talking). */ - void setTalkListener(BiConsumer listener); - - /** Receives every speaker's voice as it is played, e.g. for recording; null detaches it. */ - void setVoiceTap(VoiceTap tap); - - /** How one speaker's voice has been coming in, or {@code null} if none came yet. */ - VoiceReceiveStats receiveStats(int clientId); - - /** How everyone's voice has been coming in, those who left included. */ - VoiceReceiveStats receiveStats(); -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/VoiceReceiveStats.java b/ts3-client/core/src/main/java/com/ts3client/audio/VoiceReceiveStats.java deleted file mode 100644 index 847d7f6..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/VoiceReceiveStats.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.ts3client.audio; - -/** - * How one speaker's voice, or everyone's together, has been coming in: what arrived, and - * what playback had to do without. - * - * @param received voice packets that arrived, copies included - * @param played frames played from a packet - * @param missed frames whose packet was not there when due - * @param recovered of those, frames rebuilt from the error correction copy in the next packet - * rather than concealed - * @param outOfOrder packets that arrived after a later one - * @param late packets that arrived after their frame was concealed, so were dropped; - * each one is also among {@code missed} - * @param duplicates copies of a packet already received, discarded - */ -public record VoiceReceiveStats(long received, long played, long missed, long recovered, long outOfOrder, long late, - long duplicates) { - - public static final VoiceReceiveStats NONE = new VoiceReceiveStats(0, 0, 0, 0, 0, 0, 0); - - public VoiceReceiveStats plus(VoiceReceiveStats o) { - return new VoiceReceiveStats(received + o.received, played + o.played, missed + o.missed, - recovered + o.recovered, outOfOrder + o.outOfOrder, late + o.late, duplicates + o.duplicates); - } - - /** Frames that were due, whether played or missed. */ - public long due() { - return played + missed; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/VoiceStream.java b/ts3-client/core/src/main/java/com/ts3client/audio/VoiceStream.java deleted file mode 100644 index d0e9b80..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/VoiceStream.java +++ /dev/null @@ -1,489 +0,0 @@ -package com.ts3client.audio; - -import com.github.manevolent.ts3j.enums.CodecType; -import com.ts3client.audio.opus.OpusCodec; -import com.ts3client.audio.opus.OpusDecoder; - -import java.util.function.BiConsumer; - -/** - * One speaker's incoming voice: packets go into an adaptive {@link JitterBuffer} as they - * arrive, and every {@link #pull} plays out the next 20 ms, concealing what went missing. - * - *

The buffer is driven the way the official client drives it. A speaker has one timeline, - * {@code unwrap16(packetId) * 60} ticks, which is never re-anchored between talk bursts: the - * sender stops numbering when it stops talking and playback stops at the same point, so the - * next burst lands where the last one left off and the delay the buffer has learned carries - * over. Only a long silence drops the timeline. - * - *

An empty packet is the talker letting go of the key. It never enters the buffer; its - * position is remembered, the burst ends once playback reaches it, and its slot is played as - * silence rather than concealed, since nothing was lost there. - * - *

A frame that did go missing is rebuilt from the error correction copy in the packet after - * it, when that one is already held; only otherwise is it concealed. An - * {@linkplain #setExtraDelay extra delay} makes that, and late packets, more likely to be in - * time. - * - *

The stream keeps no clock of its own: whoever pulls sets the pace, one call per - * 20 ms frame. {@link #offer} and {@link #stop} may be called from any thread; pulls - * must come from one thread at a time. - */ -final class VoiceStream { - - /** Returned by {@link #pull} when no talk burst is playing. */ - static final int IDLE = -1; - - /** Longest Opus frame (120 ms @ 48 kHz) a packet may decode to, per channel. */ - static final int MAX_FRAME = 5760; - - private static final int FRAME = VoiceFormat.FRAME_SIZE; - private static final float[] SILENT_FRAME = new float[FRAME]; - private static final int FRAME_TICKS = JitterBuffer.TEAMSPEAK_TICKS_PER_FRAME; - /** Pulls in a row with nothing held before a burst whose end marker got lost is given up. */ - private static final int EMPTY_PULLS_TO_END = 10; - /** How far back a talker's stop is remembered, as in the official client. */ - private static final int STOP_MARK_WINDOW_TICKS = 3000; - /** Silence after which the timeline and the delay estimate are dropped, as in the official client. */ - private static final long IDLE_RESET_NANOS = 5_000_000_000L; - private static final int EPOCH_UNSET = Integer.MIN_VALUE; - /** How many recent sequence numbers are remembered to recognise a copy; a power of two. */ - private static final int SEEN_WINDOW = 1024; - - /** What a pull plays, decided under the lock and produced outside it. */ - private enum Source { PACKET, RECOVER, CONCEAL, SILENCE, SURPLUS } - - final int clientId; - private final OpusCodec opus; - private final BiConsumer talkListener; - - private final Object lock = new Object(); - // Guarded by lock. - private final JitterBuffer jitter = JitterBuffer.forTeamSpeakVoice(FRAME_TICKS); - private int epoch = EPOCH_UNSET; - private int lastSeq; - private int[] stopMarks = new int[8]; - private int stopMarkCount; - /** Channels of the latest packet: TeamSpeak streams {@code OPUS_MUSIC} in stereo. */ - private int channels = 1; - private boolean playing; - private int emptyPulls; - /** Frames of decoded audio left over from the last packet, still to be played. */ - private int surplusFrames; - /** Frames of concealment still owed to a delay increase. */ - private int concealOwed; - /** Ticks of delay held on top of what the jitter buffer measures it needs. */ - private int extraTicks; - /** Frames of silence still to play before a fresh timeline starts, building up {@link #extraTicks}. */ - private int leadInFrames; - /** Set when the timeline was dropped; the decoder follows on the next pull. */ - private boolean resetDecoder; - /** Recently received sequence numbers, each at {@code seq % SEEN_WINDOW}. */ - private final int[] seen = new int[SEEN_WINDOW]; - private int highestSeq; - private long received; - private long played; - private long missed; - private long recovered; - private long outOfOrder; - private long late; - private long duplicates; - - /** Guards the decoder: a close from another thread may reach it mid-pull. */ - private final Object decoderLock = new Object(); - private final float[] pcm = new float[MAX_FRAME * VoiceFormat.MAX_CHANNELS]; - /** Audio a packet decoded to beyond its first frame; only the pulling thread touches it. */ - private final float[] surplus = new float[MAX_FRAME * VoiceFormat.MAX_CHANNELS]; - private int surplusOffset; - private int surplusChannels; - private OpusDecoder decoder; - private int decoderChannels; - private boolean closed; - /** The played frame in mono and at full volume, for the {@link #tap}. */ - private final float[] tapped = new float[FRAME]; - private volatile VoiceTap tap; - - private volatile boolean talking; - private volatile long lastPacketNanos; - - VoiceStream(int clientId, OpusCodec opus, BiConsumer talkListener) { - this.clientId = clientId; - this.opus = opus; - this.talkListener = talkListener; - forgetSeen(); - } - - void setTap(VoiceTap tap) { - this.tap = tap; - } - - /** - * Holds {@code ticks} more delay than the network calls for, for a better chance that - * late packets and those carrying a lost one's error correction copy arrive in time. - */ - void setExtraDelay(int ticks) { - synchronized (lock) { - extraTicks = Math.max(0, ticks); - jitter.setMargin(FRAME_TICKS + extraTicks); - } - } - - private static int channelsFor(CodecType codec) { - return codec == CodecType.OPUS_MUSIC ? 2 : 1; - } - - /** - * Places an incoming packet on the speaker's timeline; an empty one marks the end of the - * talk burst. - * - * @return true if the packet started a new burst, so playout has to begin - */ - boolean offer(int packetId, CodecType codec, byte[] data) { - long now = System.nanoTime(); - boolean longIdle = lastPacketNanos != 0 && now - lastPacketNanos >= IDLE_RESET_NANOS; - lastPacketNanos = now; - boolean end = data == null || data.length == 0; - boolean started = false; - - synchronized (lock) { - if (longIdle && !playing) { - jitter.reset(); - epoch = EPOCH_UNSET; - stopMarkCount = 0; - resetDecoder = true; - forgetSeen(); - } - boolean fresh = epoch == EPOCH_UNSET; - int seq = unwrap(packetId & 0xFFFF); - int ticks = seq * FRAME_TICKS; - if (end) { - markStop(ticks); - return false; - } - boolean behind = !fresh && ticks - jitter.position() < 0; - count(seq, fresh, behind); - // Playback already went past it, but the buffer still learns how late it ran, as in - // the official client; that is what grows the delay to wait for redundant copies. - if (behind) { - jitter.put(data, ticks, FRAME_TICKS); - return false; - } - - channels = channelsFor(codec); - jitter.put(data, ticks, FRAME_TICKS); - if (!playing) { - playing = true; - started = true; - emptyPulls = 0; - // The buffer would otherwise reach the extra delay by concealing frames mid-speech. - if (fresh) leadInFrames = extraTicks / FRAME_TICKS; - } - } - markTalking(true); - return started; - } - - /** - * Plays out the next frame into {@code out}, interleaved over {@code outChannels} and - * scaled by {@code gain} but not clipped, so it can still be mixed. - * - * @param out room for {@link VoiceFormat#FRAME_SIZE} samples per channel - * @return the samples written per channel, at most one frame; 0 if a packet could not be - * decoded, or {@link #IDLE} once the burst is over - */ - int pull(float[] out, int outChannels, double gain) { - Source source; - byte[] packet = null; - int surplusTake = 0; - int packetChannels; - boolean reset; - synchronized (lock) { - if (!playing) return IDLE; - reset = resetDecoder; - resetDecoder = false; - packetChannels = channels; - - if (leadInFrames > 0) { - leadInFrames--; - source = Source.SILENCE; - } else if (surplusFrames > 0 || concealOwed > 0) { - // Still playing out what the last get() handed over. - if (surplusFrames > 0) { - source = Source.SURPLUS; - surplusTake = Math.min(FRAME, surplusFrames); - surplusFrames -= surplusTake; - } else { - source = Source.CONCEAL; - concealOwed--; - } - jitter.remainingSpan(remainingTicks()); - } else { - boolean empty = jitter.isEmpty(); - emptyPulls = empty ? emptyPulls + 1 : 0; - if (empty && (stoppedAt(jitter.position()) || emptyPulls >= EMPTY_PULLS_TO_END)) { - stopLocked(); - source = null; - } else { - JitterBuffer.Status status = jitter.get(FRAME_TICKS); - switch (status) { - case OK -> { - source = Source.PACKET; - packet = jitter.payload(); - played++; - } - case MISSING -> { - if (isStopMark(jitter.timestamp())) { - source = Source.SILENCE; - } else { - missed++; - packet = jitter.nextPayload(); - if (packet != null) { - source = Source.RECOVER; - recovered++; - } else { - source = Source.CONCEAL; - } - } - } - default -> { - // The buffer grows its delay by inserting this many frames. - source = Source.CONCEAL; - concealOwed = Math.max(1, jitter.span() / FRAME_TICKS) - 1; - } - } - jitter.tick(); - } - } - } - if (source == null) { - markTalking(false); - return IDLE; - } - - int frames; - synchronized (decoderLock) { - if (closed) return 0; - try { - if (reset && decoder != null) decoder.reset(); - frames = produce(source, packet, surplusTake, packetChannels, out, outChannels, gain); - } catch (RuntimeException e) { - return 0; - } - } - return frames; - } - - private int produce(Source source, byte[] packet, int surplusTake, int packetChannels, float[] out, - int outChannels, double gain) { - switch (source) { - case SURPLUS -> { - play(surplus, surplusOffset, surplusTake, surplusChannels, out, outChannels, gain); - surplusOffset += surplusTake; - return surplusTake; - } - case SILENCE -> { - play(SILENT_FRAME, 0, FRAME, 1, out, outChannels, gain); - return FRAME; - } - case CONCEAL -> { - int frames = decoderFor(decoderChannels == 0 ? packetChannels : decoderChannels).conceal(pcm, FRAME); - play(pcm, 0, frames, decoderChannels, out, outChannels, gain); - return frames; - } - case RECOVER -> { - int frames = decoderFor(decoderChannels == 0 ? packetChannels : decoderChannels).recover(packet, pcm, FRAME); - play(pcm, 0, frames, decoderChannels, out, outChannels, gain); - return frames; - } - default -> { - int frames = decoderFor(packetChannels).decode(packet, pcm); - int played = Math.min(frames, FRAME); - play(pcm, 0, played, packetChannels, out, outChannels, gain); - if (frames > played) keepSurplus(played, frames - played, packetChannels); - return played; - } - } - } - - /** Hands a frame to the output and, if attached, the tap. */ - private void play(float[] src, int fromFrame, int frames, int channels, float[] out, int outChannels, - double gain) { - emit(src, fromFrame, frames, channels, out, outChannels, gain); - VoiceTap t = tap; - if (t == null || frames <= 0) return; - int n = Math.min(frames, FRAME); - emit(src, fromFrame, n, channels, tapped, 1, 1.0); - t.onVoice(clientId, tapped, n); - } - - /** Holds back what a packet decoded to beyond one frame, for the following pulls. */ - private void keepSurplus(int from, int frames, int channels) { - System.arraycopy(pcm, from * channels, surplus, 0, frames * channels); - surplusOffset = 0; - surplusChannels = channels; - synchronized (lock) { - if (playing) surplusFrames = frames; - } - } - - /** Ticks of audio already handed out but not yet played; guarded by the lock. */ - private int remainingTicks() { - return (surplusFrames * FRAME_TICKS + FRAME - 1) / FRAME + concealOwed * FRAME_TICKS; - } - - /** - * Matches decoded audio to the output: duplicates mono across stereo and folds a stereo - * (music) stream down onto mono. - */ - private static void emit(float[] src, int fromFrame, int frames, int channels, float[] out, int outChannels, - double gain) { - int base = fromFrame * channels; - for (int i = 0, k = 0; i < frames; i++) { - for (int c = 0; c < outChannels; c++, k++) { - double v; - if (channels == outChannels) { - v = src[base + i * channels + c]; - } else if (channels == 1) { - v = src[base + i]; - } else { - double sum = 0; - for (int s = 0; s < channels; s++) sum += src[base + i * channels + s]; - v = sum / channels; - } - out[k] = (float) (v * gain); - } - } - } - - /** - * Returns a decoder matching the stream's channel count, rebuilding it when a speaker - * switches between the mono {@code OPUS_VOICE} and stereo {@code OPUS_MUSIC} codecs. - */ - private OpusDecoder decoderFor(int channels) { - if (decoder == null || decoderChannels != channels) { - if (decoder != null) decoder.close(); - decoder = opus.createDecoder(VoiceFormat.SAMPLE_RATE, MAX_FRAME, channels); - decoderChannels = channels; - } - return decoder; - } - - /** - * Widens the 16-bit packet id into a continuous sequence. A packet that arrives after the - * counter wrapped, but was sent before it, counts back into the previous epoch. - */ - private int unwrap(int seq) { - if (epoch == EPOCH_UNSET) { - epoch = 0; - lastSeq = seq; - } else { - int delta = (short) (seq - lastSeq); - if (delta > 0) { - if (seq < lastSeq) epoch++; - lastSeq = seq; - } else if (seq > lastSeq) { - epoch--; - } - } - return (epoch << 16) | seq; - } - - /** Files an arrived packet under the counters. Call under the lock. */ - private void count(int seq, boolean fresh, boolean behind) { - received++; - int slot = seq & (SEEN_WINDOW - 1); - if (!fresh && seen[slot] == seq) { - duplicates++; - return; - } - seen[slot] = seq; - if (behind) late++; - if (fresh || seq - highestSeq > 0) highestSeq = seq; - else outOfOrder++; - } - - private void forgetSeen() { - java.util.Arrays.fill(seen, Integer.MIN_VALUE); - } - - /** How this speaker's voice has been coming in since the stream was created. */ - VoiceReceiveStats stats() { - synchronized (lock) { - return new VoiceReceiveStats(received, played, missed, recovered, outOfOrder, late, duplicates); - } - } - - private void markStop(int ticks) { - int position = jitter.position(); - int kept = 0; - for (int i = 0; i < stopMarkCount; i++) { - if (position - stopMarks[i] < STOP_MARK_WINDOW_TICKS) stopMarks[kept++] = stopMarks[i]; - } - stopMarkCount = kept; - if (stopMarkCount == stopMarks.length) stopMarks = java.util.Arrays.copyOf(stopMarks, stopMarkCount * 2); - stopMarks[stopMarkCount++] = ticks; - } - - private boolean isStopMark(int ticks) { - for (int i = 0; i < stopMarkCount; i++) { - if (stopMarks[i] == ticks) return true; - } - return false; - } - - /** Whether the talker let go at or shortly before {@code position}, so the burst is spoken out. */ - private boolean stoppedAt(int position) { - for (int i = 0; i < stopMarkCount; i++) { - int behind = position - stopMarks[i]; - if (behind >= 0 && behind < STOP_MARK_WINDOW_TICKS) return true; - } - return false; - } - - /** Ends the current talk burst, if any; the next packet starts a new one. */ - void stop() { - synchronized (lock) { - stopLocked(); - } - markTalking(false); - } - - private void stopLocked() { - playing = false; - surplusFrames = 0; - concealOwed = 0; - leadInFrames = 0; - emptyPulls = 0; - } - - boolean isPlaying() { - synchronized (lock) { - return playing; - } - } - - boolean isTalking() { - return talking; - } - - long lastPacketNanos() { - return lastPacketNanos; - } - - void close() { - synchronized (lock) { - stopLocked(); - } - synchronized (decoderLock) { - closed = true; - if (decoder != null) decoder.close(); - decoder = null; - } - } - - private void markTalking(boolean talking) { - if (this.talking == talking) return; - this.talking = talking; - talkListener.accept(clientId, talking); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/VoiceTap.java b/ts3-client/core/src/main/java/com/ts3client/audio/VoiceTap.java deleted file mode 100644 index 3ca4dfa..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/VoiceTap.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.ts3client.audio; - -/** Receives each speaker's voice as it is played, before any volume is applied. */ -@FunctionalInterface -public interface VoiceTap { - - /** - * Called from an audio thread with one played frame; do not block. The array is reused - * between calls. - * - * @param mono samples in [-1, 1] - * @param frames how many samples, at most one 20 ms frame - */ - void onVoice(int clientId, float[] mono, int frames); -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/ogg/OggPageWriter.java b/ts3-client/core/src/main/java/com/ts3client/audio/ogg/OggPageWriter.java deleted file mode 100644 index d665a95..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/ogg/OggPageWriter.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.ts3client.audio.ogg; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.charset.StandardCharsets; - -/** - * Frames the packets of one logical bitstream into Ogg pages (RFC 3533). Packets too long - * for one page run on into the next; a page is closed once it holds about - * {@link #TARGET_PAGE_BYTES}, or on {@link #flush}. - */ -public final class OggPageWriter { - - private static final int TARGET_PAGE_BYTES = 4096; - private static final int MAX_SEGMENTS = 255; - - private static final int FLAG_CONTINUED = 0x01; - private static final int FLAG_FIRST = 0x02; - private static final int FLAG_LAST = 0x04; - - private final OutputStream out; - private final int serial; - private final byte[] lacing = new byte[MAX_SEGMENTS]; - private final ByteArrayOutputStream data = new ByteArrayOutputStream(); - private int segments; - private int sequence; - /** Whether the open page starts with the rest of a packet from the page before. */ - private boolean continued; - /** Granule position of the last packet completed on the open page, -1 if none. */ - private long granule = -1; - private long lastGranule; - - public OggPageWriter(OutputStream out, int serial) { - this.out = out; - this.serial = serial; - } - - /** @param granule the stream position at the end of this packet */ - public void write(byte[] packet, long granule) throws IOException { - int offset = 0; - while (true) { - if (segments == MAX_SEGMENTS) closePage(0, true); - int take = Math.min(255, packet.length - offset); - lacing[segments++] = (byte) take; - data.write(packet, offset, take); - offset += take; - // A packet ends with a segment shorter than 255 bytes, if need be an empty one. - if (take < 255) break; - } - this.granule = granule; - this.lastGranule = granule; - if (data.size() >= TARGET_PAGE_BYTES) flush(); - } - - /** Closes the open page, so the next packet starts a new one (as the Opus headers need). */ - public void flush() throws IOException { - if (segments > 0) closePage(0, false); - } - - /** Writes out the stream's last page. */ - public void finish() throws IOException { - closePage(FLAG_LAST, false); - out.flush(); - } - - private void closePage(int flags, boolean packetContinues) throws IOException { - if (continued) flags |= FLAG_CONTINUED; - if (sequence == 0) flags |= FLAG_FIRST; - long pageGranule = granule >= 0 ? granule : (flags & FLAG_LAST) != 0 ? lastGranule : -1; - - ByteBuffer header = ByteBuffer.allocate(27 + segments).order(ByteOrder.LITTLE_ENDIAN); - header.put("OggS".getBytes(StandardCharsets.US_ASCII)); - header.put((byte) 0); - header.put((byte) flags); - header.putLong(pageGranule); - header.putInt(serial); - header.putInt(sequence++); - header.putInt(0); // checksum, filled in below - header.put((byte) segments); - header.put(lacing, 0, segments); - - byte[] page = new byte[header.capacity() + data.size()]; - System.arraycopy(header.array(), 0, page, 0, header.capacity()); - System.arraycopy(data.toByteArray(), 0, page, header.capacity(), data.size()); - ByteBuffer.wrap(page).order(ByteOrder.LITTLE_ENDIAN).putInt(22, crc(page)); - out.write(page); - - segments = 0; - data.reset(); - granule = -1; - continued = packetContinues; - } - - /** Ogg's CRC-32: polynomial 0x04c11db7, not reflected, starting from 0. */ - private static int crc(byte[] page) { - int crc = 0; - for (byte b : page) crc = (crc << 8) ^ CRC_TABLE[((crc >>> 24) ^ b) & 0xff]; - return crc; - } - - private static final int[] CRC_TABLE = new int[256]; - - static { - for (int i = 0; i < 256; i++) { - int r = i << 24; - for (int j = 0; j < 8; j++) r = (r & 0x80000000) != 0 ? (r << 1) ^ 0x04c11db7 : r << 1; - CRC_TABLE[i] = r; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/ogg/OpusHeaders.java b/ts3-client/core/src/main/java/com/ts3client/audio/ogg/OpusHeaders.java deleted file mode 100644 index 5549095..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/ogg/OpusHeaders.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.ts3client.audio.ogg; - -import java.io.ByteArrayOutputStream; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.charset.StandardCharsets; -import java.util.List; - -/** The two header packets that open an Ogg Opus stream (RFC 7845, section 5). */ -public final class OpusHeaders { - - /** Channel mapping family 255 caps a stream at this many channels. */ - public static final int MAX_DISCRETE_CHANNELS = 255; - /** - * libopus' encoder delay at 48 kHz for 20 ms frames, which the file tells the decoder - * to drop (the SPI does not expose {@code OPUS_GET_LOOKAHEAD}). - */ - public static final int LIBOPUS_PRE_SKIP = 312; - - private OpusHeaders() { - } - - /** A single mono stream (mapping family 0). */ - public static byte[] mono(int preSkip, int inputRate) { - return head(1, preSkip, inputRate, 0).array(); - } - - /** - * {@code channels} unrelated channels, each its own uncoupled mono stream in channel - * order (mapping family 255): every packet is a multistream packet, see - * {@link SelfDelimitedOpus#join}. - */ - public static byte[] discrete(int channels, int preSkip, int inputRate) { - if (channels < 1 || channels > MAX_DISCRETE_CHANNELS) { - throw new IllegalArgumentException("channels " + channels); - } - ByteBuffer b = head(channels, preSkip, inputRate, 255); - b.put((byte) channels); // streams - b.put((byte) 0); // coupled streams - for (int c = 0; c < channels; c++) b.put((byte) c); - return b.array(); - } - - private static ByteBuffer head(int channels, int preSkip, int inputRate, int family) { - ByteBuffer b = ByteBuffer.allocate(19 + (family == 0 ? 0 : 2 + channels)).order(ByteOrder.LITTLE_ENDIAN); - b.put("OpusHead".getBytes(StandardCharsets.US_ASCII)); - b.put((byte) 1); // version - b.put((byte) channels); - b.putShort((short) preSkip); - b.putInt(inputRate); - b.putShort((short) 0); // output gain - b.put((byte) family); - return b; - } - - /** @param comments {@code NAME=value} user comments */ - public static byte[] tags(String vendor, List comments) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - out.writeBytes("OpusTags".getBytes(StandardCharsets.US_ASCII)); - writeString(out, vendor); - writeInt(out, comments.size()); - for (String comment : comments) writeString(out, comment); - return out.toByteArray(); - } - - private static void writeString(ByteArrayOutputStream out, String s) { - byte[] bytes = s.getBytes(StandardCharsets.UTF_8); - writeInt(out, bytes.length); - out.writeBytes(bytes); - } - - private static void writeInt(ByteArrayOutputStream out, int v) { - out.write(v); - out.write(v >>> 8); - out.write(v >>> 16); - out.write(v >>> 24); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/ogg/SelfDelimitedOpus.java b/ts3-client/core/src/main/java/com/ts3client/audio/ogg/SelfDelimitedOpus.java deleted file mode 100644 index 0d12662..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/ogg/SelfDelimitedOpus.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.ts3client.audio.ogg; - -import java.io.ByteArrayOutputStream; -import java.util.List; - -/** - * Opus' self-delimiting packet framing (RFC 6716, appendix B), which multistream packets - * use to put several streams' packets back to back. - */ -public final class SelfDelimitedOpus { - - private SelfDelimitedOpus() { - } - - /** - * Joins one packet per stream into a multistream packet: every packet but the last is - * self-delimited, the last is kept as it is. - */ - public static byte[] join(List packets) { - if (packets.size() == 1) return packets.get(0); - int size = 0; - for (byte[] p : packets) size += p.length + 2; - ByteArrayOutputStream out = new ByteArrayOutputStream(size); - for (int i = 0; i < packets.size() - 1; i++) out.writeBytes(selfDelimited(packets.get(i))); - out.writeBytes(packets.get(packets.size() - 1)); - return out.toByteArray(); - } - - /** Re-frames a packet so its length can be told from the packet itself. */ - public static byte[] selfDelimited(byte[] packet) { - if (packet.length == 0) throw new IllegalArgumentException("empty Opus packet"); - int code = packet[0] & 0x03; - // The extra length goes right after the packet's own header: the TOC byte, plus for - // code 1 and 2 nothing more, for code 2 the first frame's length, and for code 3 the - // frame count, padding length and (VBR) all but the last frame's lengths. - int header; - int lastFrame; - switch (code) { - case 0 -> { - header = 1; - lastFrame = packet.length - 1; - } - case 1 -> { - header = 1; - lastFrame = (packet.length - 1) / 2; - } - case 2 -> { - int[] first = readLength(packet, 1); - header = 1 + first[1]; - lastFrame = packet.length - header - first[0]; - } - default -> { - if (packet.length < 2) throw new IllegalArgumentException("truncated Opus packet"); - int count = packet[1] & 0x3f; - boolean vbr = (packet[1] & 0x80) != 0; - boolean padded = (packet[1] & 0x40) != 0; - int pos = 2; - int padding = 0; - if (padded) { - int b; - do { - b = packet[pos++] & 0xff; - padding += b == 255 ? 254 : b; - } while (b == 255); - } - int payload; - if (vbr) { - int framesBefore = 0; - for (int i = 0; i < count - 1; i++) { - int[] length = readLength(packet, pos); - framesBefore += length[0]; - pos += length[1]; - } - payload = packet.length - pos - padding; - lastFrame = payload - framesBefore; - } else { - payload = packet.length - pos - padding; - lastFrame = payload / count; - } - header = pos; - } - } - if (lastFrame < 0) throw new IllegalArgumentException("malformed Opus packet"); - byte[] length = encodeLength(lastFrame); - byte[] out = new byte[packet.length + length.length]; - System.arraycopy(packet, 0, out, 0, header); - System.arraycopy(length, 0, out, header, length.length); - System.arraycopy(packet, header, out, header + length.length, packet.length - header); - return out; - } - - /** @return the frame length at {@code pos} and how many bytes it took */ - private static int[] readLength(byte[] packet, int pos) { - int b = packet[pos] & 0xff; - if (b < 252) return new int[]{b, 1}; - return new int[]{b + 4 * (packet[pos + 1] & 0xff), 2}; - } - - private static byte[] encodeLength(int length) { - if (length < 252) return new byte[]{(byte) length}; - int first = 252 + (length & 3); - return new byte[]{(byte) first, (byte) ((length - first) / 4)}; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/opus/CtlOpusEncoder.java b/ts3-client/core/src/main/java/com/ts3client/audio/opus/CtlOpusEncoder.java deleted file mode 100644 index 703f230..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/opus/CtlOpusEncoder.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.ts3client.audio.opus; - -/** An {@link OpusEncoder} configured through libopus' own controls; a binding supplies {@link #ctl}. */ -public abstract class CtlOpusEncoder implements OpusEncoder { - - /** Calls {@code opus_encoder_ctl(encoder, request, value)}. */ - protected abstract void ctl(int request, int value); - - @Override - public void setBitrate(int bitsPerSecond) { - ctl(LibOpus.SET_BITRATE_REQUEST, bitsPerSecond); - } - - @Override - public void setComplexity(int complexity) { - ctl(LibOpus.SET_COMPLEXITY_REQUEST, Math.max(0, Math.min(10, complexity))); - } - - @Override - public void setVbr(boolean vbr) { - ctl(LibOpus.SET_VBR_REQUEST, vbr ? 1 : 0); - } - - @Override - public void setInbandFec(boolean fec) { - ctl(LibOpus.SET_INBAND_FEC_REQUEST, fec ? 1 : 0); - } - - @Override - public void setExpectedPacketLoss(int percent) { - ctl(LibOpus.SET_PACKET_LOSS_PERC_REQUEST, Math.max(0, Math.min(100, percent))); - } - - @Override - public void setSignal(Signal signal) { - ctl(LibOpus.SET_SIGNAL_REQUEST, signal == Signal.MUSIC ? LibOpus.SIGNAL_MUSIC : LibOpus.SIGNAL_VOICE); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/opus/LibOpus.java b/ts3-client/core/src/main/java/com/ts3client/audio/opus/LibOpus.java deleted file mode 100644 index 0cdcda0..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/opus/LibOpus.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.ts3client.audio.opus; - -/** libopus' numeric constants (opus_defines.h), shared by every binding of it. */ -public final class LibOpus { - - public static final int APPLICATION_VOIP = 2048; - public static final int APPLICATION_AUDIO = 2049; - - public static final int SET_BITRATE_REQUEST = 4002; - public static final int SET_VBR_REQUEST = 4006; - public static final int SET_COMPLEXITY_REQUEST = 4010; - public static final int SET_INBAND_FEC_REQUEST = 4012; - public static final int SET_PACKET_LOSS_PERC_REQUEST = 4014; - public static final int SET_SIGNAL_REQUEST = 4024; - public static final int RESET_STATE = 4028; - - public static final int SIGNAL_VOICE = 3001; - public static final int SIGNAL_MUSIC = 3002; - - private LibOpus() { - } - - public static int application(OpusCodec.Application application) { - return application == OpusCodec.Application.AUDIO ? APPLICATION_AUDIO : APPLICATION_VOIP; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/opus/OpusCodec.java b/ts3-client/core/src/main/java/com/ts3client/audio/opus/OpusCodec.java deleted file mode 100644 index 15a5661..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/opus/OpusCodec.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.ts3client.audio.opus; - -/** Creates Opus encoders and decoders; each platform binds its own libopus. */ -public interface OpusCodec { - - /** Opus' coding mode, fixed when an encoder is created. */ - enum Application { VOIP, AUDIO } - - OpusEncoder createEncoder(int sampleRate, int frameSize, int channels, Application application); - - /** @param maxFrameSize the longest frame, per channel, a packet may decode to */ - OpusDecoder createDecoder(int sampleRate, int maxFrameSize, int channels); - - /** libopus' version string, for display. */ - String version(); -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/opus/OpusDecoder.java b/ts3-client/core/src/main/java/com/ts3client/audio/opus/OpusDecoder.java deleted file mode 100644 index b2c4e77..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/opus/OpusDecoder.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.ts3client.audio.opus; - -/** One Opus decoder, used from one thread at a time. */ -public interface OpusDecoder extends AutoCloseable { - - /** Decodes {@code packet} into interleaved samples; returns the samples decoded per channel. */ - int decode(byte[] packet, float[] out); - - /** - * Makes up {@code frameSize} samples per channel for a packet that never arrived. Opus - * conceals exactly as much as it is asked for, so this should be the lost packet's length. - */ - int conceal(float[] out, int frameSize); - - /** - * Rebuilds {@code frameSize} samples per channel for a lost packet from the forward error - * correction copy carried in {@code next}, the packet that followed it. Falls back to - * concealment by itself when {@code next} carries none. {@code next} is then decoded as - * usual. - */ - int recover(byte[] next, float[] out, int frameSize); - - /** Forgets the stream's state, as at the start of a new talk burst. */ - void reset(); - - @Override - void close(); -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/opus/OpusEncoder.java b/ts3-client/core/src/main/java/com/ts3client/audio/opus/OpusEncoder.java deleted file mode 100644 index 2b15e49..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/opus/OpusEncoder.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.ts3client.audio.opus; - -/** One Opus encoder. Its methods may be called from different threads, but not concurrently. */ -public interface OpusEncoder extends AutoCloseable { - - enum Signal { VOICE, MUSIC } - - void setBitrate(int bitsPerSecond); - - void setComplexity(int complexity); - - void setVbr(boolean vbr); - - void setInbandFec(boolean fec); - - void setExpectedPacketLoss(int percent); - - void setSignal(Signal signal); - - /** Encodes exactly one frame of interleaved samples. */ - byte[] encode(float[] pcm); - - @Override - void close(); -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/AudioProcessor.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/AudioProcessor.java deleted file mode 100644 index f13d807..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/AudioProcessor.java +++ /dev/null @@ -1,161 +0,0 @@ -package com.ts3client.audio.processing; - -import com.ts3client.audio.processing.agc2.AdaptiveDigitalConfig; -import com.ts3client.audio.processing.agc2.GainController2; -import com.ts3client.audio.processing.ns.NoiseSuppressor; -import com.ts3client.audio.processing.ns.SuppressionLevel; -import com.ts3client.audio.processing.transients.TransientSuppressor; - -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * The microphone pre-processing chain, set up the way the TeamSpeak 3 client configures - * WebRTC's audio processing module. TS3's capture preprocessor applies, per 10 ms at - * 48 kHz: - *

    - *
  1. noise suppression ("Remove background noise") at {@code denoiser_level} 0–3, run - * on the three-band split. TS3 disables APM's high-pass filter, but APM forces it on - * whenever noise suppression runs, so a 100 Hz high-pass comes with it;
  2. - *
  3. transient suppression ("Typing attenuation"), told about key presses;
  4. - *
  5. automatic gain control. TS3 runs WebRTC's legacy AGC1 (adaptive digital, target - * -9 dBFS, 20 dB compression); this runs its successor, AGC2 adaptive digital. AGC2 won't - * amplify the noise floor above -50 dBFS, which also holds back a distant voice - * barely above the noise; {@link #setGainBoost} trades more noise for more of it.
  6. - *
- * - *

One deliberate difference: APM only splits into bands for band-wise stages, so with noise - * suppression and AGC1 both off its transient detector reads stale band data and never - * fires. TS3 hides this behind AGC1, which forces a split; with AGC2 it would show, so the - * split is done whenever typing attenuation is on. - * - *

Pure DSP with no platform dependencies. Drive {@link #process} from the capture thread; - * the setters and {@link #keyPressed()} may be called from any thread and take effect at the - * next 10 ms frame. With every stage off, audio passes through untouched. - */ -public final class AudioProcessor { - - public static final int SAMPLE_RATE = 48_000; - public static final int FRAME_SIZE = ThreeBandFilterBank.FULL_BAND_SIZE; - - private volatile boolean noiseSuppression; - private volatile SuppressionLevel suppressionLevel = SuppressionLevel.DB_12; - private volatile boolean transientSuppression; - private volatile boolean gainControl; - private volatile float gainBoostDb; - private final AtomicBoolean keyPressed = new AtomicBoolean(); - - private final ThreeBandFilterBank filterBank = new ThreeBandFilterBank(); - private HighPassFilter highPassFilter; - private NoiseSuppressor noiseSuppressor; - private TransientSuppressor transientSuppressor; - private GainController2 gainController; - - private final float[] fullBand = new float[FRAME_SIZE]; - private final float[][] bands = new float[ThreeBandFilterBank.NUM_BANDS][ThreeBandFilterBank.SPLIT_BAND_SIZE]; - - public void setNoiseSuppression(boolean enabled) { - this.noiseSuppression = enabled; - } - - public void setSuppressionLevel(SuppressionLevel level) { - this.suppressionLevel = level; - } - - public void setTransientSuppression(boolean enabled) { - this.transientSuppression = enabled; - } - - public void setGainControl(boolean enabled) { - this.gainControl = enabled; - } - - /** Lets the gain control raise the noise floor this many dB higher to reach quiet speech. */ - public void setGainBoost(float db) { - this.gainBoostDb = db; - } - - /** Reports a key press anywhere on the system; the transient suppressor only acts while typing. */ - public void keyPressed() { - keyPressed.set(true); - } - - /** Drops all filter state; call when (re)starting capture. */ - public void reset() { - highPassFilter = null; - noiseSuppressor = null; - transientSuppressor = null; - gainController = null; - keyPressed.set(false); - } - - /** - * Processes mono samples in [-1, 1] in place. {@code len} must be a multiple of - * {@link #FRAME_SIZE}. - */ - public void process(float[] buf, int len) { - for (int offset = 0; offset + FRAME_SIZE <= len; offset += FRAME_SIZE) { - processFrame(buf, offset); - } - } - - private void processFrame(float[] buf, int offset) { - applyConfig(); - boolean key = keyPressed.getAndSet(false); - if (noiseSuppressor == null && transientSuppressor == null && gainController == null) return; - - // APM carries samples on the 16-bit scale. - for (int i = 0; i < FRAME_SIZE; i++) { - fullBand[i] = Math.max(-1.f, Math.min(1.f, buf[offset + i])) * 32768.f; - } - - if (highPassFilter != null) { - highPassFilter.process(fullBand, FRAME_SIZE); - } - if (noiseSuppressor != null || transientSuppressor != null) { - filterBank.analysis(fullBand, bands); - } - if (noiseSuppressor != null) { - noiseSuppressor.analyze(bands[0]); - noiseSuppressor.process(bands); - filterBank.synthesis(bands, fullBand); - } - if (transientSuppressor != null) { - transientSuppressor.suppress(fullBand, bands[0], key); - } - if (gainController != null) { - gainController.process(fullBand); - } - - for (int i = 0; i < FRAME_SIZE; i++) { - buf[offset + i] = Math.max(-32768.f, Math.min(32768.f, fullBand[i])) * (1.f / 32768.f); - } - } - - /** Creates or drops stages to match the settings, as APM's {@code ApplyConfig} does. */ - private void applyConfig() { - SuppressionLevel level = suppressionLevel; - if (!noiseSuppression) { - noiseSuppressor = null; - highPassFilter = null; - } else if (noiseSuppressor == null || noiseSuppressor.level() != level) { - // APM builds a fresh suppressor on a level change; the statistics restart too. - noiseSuppressor = new NoiseSuppressor(level, ThreeBandFilterBank.NUM_BANDS); - if (highPassFilter == null) highPassFilter = new HighPassFilter(); - } - - if (!transientSuppression) { - transientSuppressor = null; - } else if (transientSuppressor == null) { - transientSuppressor = new TransientSuppressor(SAMPLE_RATE / ThreeBandFilterBank.NUM_BANDS); - } - - if (!gainControl) { - gainController = null; - } else if (gainController == null) { - gainController = new GainController2(AdaptiveDigitalConfig.DEFAULT); - } - if (gainController != null) { - gainController.setMaxOutputNoiseLevelDbfs(AdaptiveDigitalConfig.DEFAULT.maxOutputNoiseLevelDbfs() + gainBoostDb); - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/HighPassFilter.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/HighPassFilter.java deleted file mode 100644 index 48a38dd..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/HighPassFilter.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.ts3client.audio.processing; - -/** - * APM's high-pass filter at 48 kHz ({@code high_pass_filter.cc}): one second-order - * Butterworth section at 100 Hz, {@code butter(2, 100/24000, 'high')}, in direct form I. - */ -final class HighPassFilter { - - private static final float B0 = 0.99079f; - private static final float B1 = -1.98157f; - private static final float B2 = 0.99079f; - private static final float A1 = -1.98149f; - private static final float A2 = 0.98166f; - - private float x0, x1, y0, y1; - - void process(float[] y, int len) { - float mx0 = x0, mx1 = x1, my0 = y0, my1 = y1; - for (int k = 0; k < len; k++) { - final float tmp = y[k]; - y[k] = B0 * tmp + B1 * mx0 + B2 * mx1 - A1 * my0 - A2 * my1; - mx1 = mx0; - mx0 = tmp; - my1 = my0; - my0 = y[k]; - } - x0 = mx0; - x1 = mx1; - y0 = my0; - y1 = my1; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/ThreeBandFilterBank.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/ThreeBandFilterBank.java deleted file mode 100644 index faf8bc6..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/ThreeBandFilterBank.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.ts3client.audio.processing; - -/** - * Splits 10 ms of 48 kHz audio into three 16 kHz bands (0–8, 8–16 and - * 16–24 kHz) and merges them back, ported from WebRTC's - * {@code three_band_filter_bank.cc}. It is how APM feeds the noise suppressor at 48 kHz. - * - *

A cosine-modulated polyphase filter bank: the half-bandwidth low-pass prototype (a - * 48-tap Kaiser-windowed FIR, stored as ten non-zero 4-tap phases) is shifted to the three - * band centres by a DCT. - */ -final class ThreeBandFilterBank { - - static final int NUM_BANDS = 3; - static final int FULL_BAND_SIZE = 480; - static final int SPLIT_BAND_SIZE = FULL_BAND_SIZE / NUM_BANDS; - - private static final int SPARSITY = 4; - private static final int STRIDE_LOG2 = 2; - private static final int STRIDE = 1 << STRIDE_LOG2; - private static final int NUM_ZERO_FILTERS = 2; - private static final int FILTER_SIZE = 4; - private static final int MEMORY_SIZE = FILTER_SIZE * STRIDE - 1; - private static final int NUM_NON_ZERO_FILTERS = SPARSITY * NUM_BANDS - NUM_ZERO_FILTERS; - private static final int SUB_SAMPLING = NUM_BANDS; - private static final int ZERO_FILTER_INDEX_1 = 3; - private static final int ZERO_FILTER_INDEX_2 = 9; - - private static final float[][] FILTER_COEFFS = { - {-0.00047749f, -0.00496888f, +0.16547118f, +0.00425496f}, - {-0.00173287f, -0.01585778f, +0.14989004f, +0.00994113f}, - {-0.00304815f, -0.02536082f, +0.12154542f, +0.01157993f}, - {-0.00346946f, -0.02587886f, +0.04760441f, +0.00607594f}, - {-0.00154717f, -0.01136076f, +0.01387458f, +0.00186353f}, - {+0.00186353f, +0.01387458f, -0.01136076f, -0.00154717f}, - {+0.00607594f, +0.04760441f, -0.02587886f, -0.00346946f}, - {+0.00983212f, +0.08543175f, -0.02982767f, -0.00383509f}, - {+0.00994113f, +0.14989004f, -0.01585778f, -0.00173287f}, - {+0.00425496f, +0.16547118f, -0.00496888f, -0.00047749f}}; - - private static final float[][] DCT_MODULATION = { - {2.f, 2.f, 2.f}, - {1.73205077f, 0.f, -1.73205077f}, - {1.f, -2.f, 1.f}, - {-1.f, 2.f, -1.f}, - {-1.73205077f, 0.f, 1.73205077f}, - {-2.f, -2.f, -2.f}, - {-1.73205077f, 0.f, 1.73205077f}, - {-1.f, 2.f, -1.f}, - {1.f, -2.f, 1.f}, - {1.73205077f, 0.f, -1.73205077f}}; - - private final float[][] stateAnalysis = new float[NUM_NON_ZERO_FILTERS][MEMORY_SIZE]; - private final float[][] stateSynthesis = new float[NUM_NON_ZERO_FILTERS][MEMORY_SIZE]; - - private final float[] inSubsampled = new float[SPLIT_BAND_SIZE]; - private final float[] outSubsampled = new float[SPLIT_BAND_SIZE]; - - /** Splits {@code in} (480 samples) into {@code out[band]} (160 samples each). */ - void analysis(float[] in, float[][] out) { - for (int band = 0; band < NUM_BANDS; band++) { - java.util.Arrays.fill(out[band], 0, SPLIT_BAND_SIZE, 0.f); - } - - for (int downsamplingIndex = 0; downsamplingIndex < SUB_SAMPLING; downsamplingIndex++) { - for (int k = 0; k < SPLIT_BAND_SIZE; k++) { - inSubsampled[k] = in[(SUB_SAMPLING - 1) - downsamplingIndex + SUB_SAMPLING * k]; - } - - for (int inShift = 0; inShift < STRIDE; inShift++) { - int filterIndex = filterIndex(downsamplingIndex + inShift * SUB_SAMPLING); - if (filterIndex < 0) continue; - - filterCore(FILTER_COEFFS[filterIndex], inSubsampled, inShift, outSubsampled, - stateAnalysis[filterIndex]); - - float[] dct = DCT_MODULATION[filterIndex]; - for (int band = 0; band < NUM_BANDS; band++) { - float[] outBand = out[band]; - for (int n = 0; n < SPLIT_BAND_SIZE; n++) { - outBand[n] += dct[band] * outSubsampled[n]; - } - } - } - } - } - - /** Merges {@code in[band]} (160 samples each) back into {@code out} (480 samples). */ - void synthesis(float[][] in, float[] out) { - java.util.Arrays.fill(out, 0, FULL_BAND_SIZE, 0.f); - for (int upsamplingIndex = 0; upsamplingIndex < SUB_SAMPLING; upsamplingIndex++) { - for (int inShift = 0; inShift < STRIDE; inShift++) { - int filterIndex = filterIndex(upsamplingIndex + inShift * SUB_SAMPLING); - if (filterIndex < 0) continue; - - float[] dct = DCT_MODULATION[filterIndex]; - java.util.Arrays.fill(inSubsampled, 0.f); - for (int band = 0; band < NUM_BANDS; band++) { - float[] inBand = in[band]; - for (int n = 0; n < SPLIT_BAND_SIZE; n++) { - inSubsampled[n] += dct[band] * inBand[n]; - } - } - - filterCore(FILTER_COEFFS[filterIndex], inSubsampled, inShift, outSubsampled, - stateSynthesis[filterIndex]); - - final float upsamplingScaling = SUB_SAMPLING; - for (int k = 0; k < SPLIT_BAND_SIZE; k++) { - out[upsamplingIndex + SUB_SAMPLING * k] += upsamplingScaling * outSubsampled[k]; - } - } - } - } - - /** Maps a polyphase index to its stored filter, or -1 for the two all-zero phases. */ - private static int filterIndex(int index) { - if (index == ZERO_FILTER_INDEX_1 || index == ZERO_FILTER_INDEX_2) return -1; - if (index < ZERO_FILTER_INDEX_1) return index; - return index < ZERO_FILTER_INDEX_2 ? index - 1 : index - 2; - } - - /** Filters {@code in} with the sparse (upsampled by {@code STRIDE}) filter, shifted by {@code inShift}. */ - private static void filterCore(float[] filter, float[] in, int inShift, float[] out, float[] state) { - java.util.Arrays.fill(out, 0.f); - for (int k = 0; k < inShift; k++) { - for (int i = 0, j = MEMORY_SIZE + k - inShift; i < FILTER_SIZE; i++, j -= STRIDE) { - out[k] += state[j] * filter[i]; - } - } - - for (int k = inShift, shift = 0; k < FILTER_SIZE * STRIDE; k++, shift++) { - final int loopLimit = Math.min(FILTER_SIZE, 1 + (shift >> STRIDE_LOG2)); - for (int i = 0, j = shift; i < loopLimit; i++, j -= STRIDE) { - out[k] += in[j] * filter[i]; - } - for (int i = loopLimit, j = MEMORY_SIZE + shift - loopLimit * STRIDE; i < FILTER_SIZE; - i++, j -= STRIDE) { - out[k] += state[j] * filter[i]; - } - } - - for (int k = FILTER_SIZE * STRIDE, shift = FILTER_SIZE * STRIDE - inShift; k < SPLIT_BAND_SIZE; - k++, shift++) { - for (int i = 0, j = shift; i < FILTER_SIZE; i++, j -= STRIDE) { - out[k] += in[j] * filter[i]; - } - } - - System.arraycopy(in, SPLIT_BAND_SIZE - MEMORY_SIZE, state, 0, MEMORY_SIZE); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/AdaptiveDigitalConfig.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/AdaptiveDigitalConfig.java deleted file mode 100644 index 6824254..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/AdaptiveDigitalConfig.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.ts3client.audio.processing.agc2; - -/** - * AGC2's adaptive digital settings, {@code GainController2::AdaptiveDigital} in - * {@code audio_processing.h}. {@link #DEFAULT} holds WebRTC's defaults. - */ -public record AdaptiveDigitalConfig(float headroomDb, float maxGainDb, float initialGainDb, - float maxGainChangeDbPerSecond, float maxOutputNoiseLevelDbfs) { - - public static final AdaptiveDigitalConfig DEFAULT = new AdaptiveDigitalConfig(5.0f, 50.0f, 15.0f, 6.0f, -50.0f); -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/AdaptiveDigitalGainController.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/AdaptiveDigitalGainController.java deleted file mode 100644 index 11e46c7..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/AdaptiveDigitalGainController.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.ts3client.audio.processing.agc2; - -import static com.ts3client.audio.processing.agc2.Agc2Common.FRAME_DURATION_MS; -import static com.ts3client.audio.processing.agc2.Agc2Common.LIMITER_THRESHOLD_FOR_AGC_GAIN_DBFS; -import static com.ts3client.audio.processing.agc2.Agc2Common.VAD_CONFIDENCE_THRESHOLD; - -/** - * Picks and applies the adaptive gain, from {@code agc2/adaptive_digital_gain_controller.cc}: - * enough to bring the speech level (plus headroom) up to just below full scale, limited so - * the noise floor stays under {@code maxOutputNoiseLevelDbfs}, and moved at most - * {@code maxGainChangeDbPerSecond}. It only raises the gain after a run of confident speech. - */ -final class AdaptiveDigitalGainController { - - /** What the controller knows about the current frame. */ - record FrameInfo(float speechProbability, float speechLevelDbfs, boolean speechLevelReliable, - float noiseRmsDbfs, float headroomDb, float limiterEnvelopeDbfs) { - } - - private final GainApplier gainApplier; - private final AdaptiveDigitalConfig config; - private final int adjacentSpeechFramesThreshold; - private final float maxGainChangeDbPer10ms; - private float maxOutputNoiseLevelDbfs; - private int framesToGainIncreaseAllowed; - private float lastGainDb; - - AdaptiveDigitalGainController(AdaptiveDigitalConfig config, int adjacentSpeechFramesThreshold) { - this.config = config; - this.adjacentSpeechFramesThreshold = adjacentSpeechFramesThreshold; - this.gainApplier = new GainApplier(Agc2Common.dbToRatio(config.initialGainDb())); - this.maxGainChangeDbPer10ms = config.maxGainChangeDbPerSecond() * FRAME_DURATION_MS / 1000.0f; - this.framesToGainIncreaseAllowed = adjacentSpeechFramesThreshold; - this.lastGainDb = config.initialGainDb(); - this.maxOutputNoiseLevelDbfs = config.maxOutputNoiseLevelDbfs(); - } - - void setMaxOutputNoiseLevelDbfs(float dbfs) { - maxOutputNoiseLevelDbfs = dbfs; - } - - void process(FrameInfo info, float[] frame, int samples) { - final float inputLevelDbfs = info.speechLevelDbfs() + info.headroomDb(); - final float targetGainDb = limitGainByLowConfidence( - limitGainByNoise(computeGainDb(inputLevelDbfs), info.noiseRmsDbfs()), - lastGainDb, info.limiterEnvelopeDbfs(), info.speechLevelReliable()); - - // Only allow the gain to rise after a run of confident speech frames. - boolean firstConfidentSpeechFrame = false; - if (info.speechProbability() < VAD_CONFIDENCE_THRESHOLD) { - framesToGainIncreaseAllowed = adjacentSpeechFramesThreshold; - } else if (framesToGainIncreaseAllowed > 0) { - framesToGainIncreaseAllowed--; - firstConfidentSpeechFrame = framesToGainIncreaseAllowed == 0; - } - final boolean gainIncreaseAllowed = framesToGainIncreaseAllowed == 0; - - float maxGainIncreaseDb = maxGainChangeDbPer10ms; - if (firstConfidentSpeechFrame) { - // Make up for the frames the increase was held back. - maxGainIncreaseDb *= adjacentSpeechFramesThreshold; - } - - float difference = targetGainDb - lastGainDb; - if (!gainIncreaseAllowed) { - difference = Math.min(difference, 0.0f); - } - final float gainChangeThisFrameDb = Math.max(-maxGainChangeDbPer10ms, Math.min(maxGainIncreaseDb, difference)); - - if (gainChangeThisFrameDb != 0.f) { - gainApplier.setGainFactor(Agc2Common.dbToRatio(lastGainDb + gainChangeThisFrameDb)); - } - gainApplier.applyGain(frame, samples); - lastGainDb = lastGainDb + gainChangeThisFrameDb; - } - - /** The gain that puts the input level at {@code -headroomDb}, capped at {@code maxGainDb}. */ - private float computeGainDb(float inputLevelDbfs) { - if (inputLevelDbfs < -(config.headroomDb() + config.maxGainDb())) { - return config.maxGainDb(); - } - if (inputLevelDbfs < -config.headroomDb()) { - return -config.headroomDb() - inputLevelDbfs; - } - return 0.0f; - } - - private float limitGainByNoise(float targetGainDb, float inputNoiseLevelDbfs) { - final float maxAllowedGainDb = maxOutputNoiseLevelDbfs - inputNoiseLevelDbfs; - return Math.min(targetGainDb, Math.max(maxAllowedGainDb, 0.0f)); - } - - /** Until the speech level is trusted, don't push the limiter's envelope above -1 dBFS. */ - private static float limitGainByLowConfidence(float targetGainDb, float lastGainDb, - float limiterAudioLevelDbfs, boolean estimateIsConfident) { - if (estimateIsConfident || limiterAudioLevelDbfs <= LIMITER_THRESHOLD_FOR_AGC_GAIN_DBFS) { - return targetGainDb; - } - final float limiterLevelDbfsBeforeGain = limiterAudioLevelDbfs - lastGainDb; - final float newTargetGainDb = Math.max(LIMITER_THRESHOLD_FOR_AGC_GAIN_DBFS - limiterLevelDbfsBeforeGain, 0.0f); - return Math.min(newTargetGainDb, targetGainDb); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/Agc2Common.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/Agc2Common.java deleted file mode 100644 index 19924f8..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/Agc2Common.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.ts3client.audio.processing.agc2; - -/** Constants and level conversions shared by AGC2, from {@code agc2/agc2_common.h} and {@code audio_util.h}. */ -final class Agc2Common { - - static final float MIN_FLOAT_S16_VALUE = -32768.0f; - static final float MAX_FLOAT_S16_VALUE = 32767.0f; - static final float MIN_LEVEL_DBFS = -90.31f; - - static final int FRAME_DURATION_MS = 10; - static final int SUB_FRAMES_IN_FRAME = 20; - - /** Target peak for the limiter's envelope when the speech level isn't trusted yet. */ - static final float LIMITER_THRESHOLD_FOR_AGC_GAIN_DBFS = -1.0f; - - static final int VAD_RESET_PERIOD_MS = 1500; - static final float VAD_CONFIDENCE_THRESHOLD = 0.95f; - static final int ADJACENT_SPEECH_FRAMES_THRESHOLD = 12; - - static final float LEVEL_ESTIMATOR_TIME_TO_CONFIDENCE_MS = 400; - static final float LEVEL_ESTIMATOR_LEAK_FACTOR = 1.0f - 1.0f / LEVEL_ESTIMATOR_TIME_TO_CONFIDENCE_MS; - - static final float SATURATION_PROTECTOR_INITIAL_HEADROOM_DB = 20.0f; - static final int SATURATION_PROTECTOR_BUFFER_SIZE = 4; - - private Agc2Common() { - } - - static float dbToRatio(float db) { - return (float) Math.pow(10.0f, db / 20.0f); - } - - /** Level of a 16-bit-scale amplitude in dBFS, floored at the int16 noise floor. */ - static float floatS16ToDbfs(float v) { - final float minDbfs = -90.30899869919436f; - if (v <= 1.0f) { - return minDbfs; - } - return 20.0f * (float) Math.log10(v) + minDbfs; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/GainApplier.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/GainApplier.java deleted file mode 100644 index 2bae21b..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/GainApplier.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.ts3client.audio.processing.agc2; - -/** - * Applies a gain factor, ramping linearly across the frame from the previous factor, from - * {@code agc2/gain_applier.cc}. - */ -final class GainApplier { - - private float lastGainFactor; - private float currentGainFactor; - - GainApplier(float initialGainFactor) { - this.lastGainFactor = initialGainFactor; - this.currentGainFactor = initialGainFactor; - } - - void setGainFactor(float gainFactor) { - currentGainFactor = gainFactor; - } - - void applyGain(float[] frame, int samples) { - final float last = lastGainFactor; - final float target = currentGainFactor; - lastGainFactor = currentGainFactor; - if (last == target && gainCloseToOne(target)) { - return; - } - if (last == target) { - for (int i = 0; i < samples; i++) { - frame[i] *= target; - } - return; - } - final float increment = (target - last) * (1.f / samples); - float gain = last; - for (int i = 0; i < samples; i++) { - frame[i] *= gain; - gain += increment; - } - } - - private static boolean gainCloseToOne(float gainFactor) { - return 1.f - 1.f / Agc2Common.MAX_FLOAT_S16_VALUE <= gainFactor - && gainFactor <= 1.f + 1.f / Agc2Common.MAX_FLOAT_S16_VALUE; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/GainController2.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/GainController2.java deleted file mode 100644 index bfbab9a..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/GainController2.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.ts3client.audio.processing.agc2; - -import static com.ts3client.audio.processing.agc2.Agc2Common.ADJACENT_SPEECH_FRAMES_THRESHOLD; -import static com.ts3client.audio.processing.agc2.Agc2Common.FRAME_DURATION_MS; -import static com.ts3client.audio.processing.agc2.Agc2Common.SATURATION_PROTECTOR_INITIAL_HEADROOM_DB; -import static com.ts3client.audio.processing.agc2.Agc2Common.VAD_RESET_PERIOD_MS; - -import com.ts3client.audio.vad.RnnSpeechDetector; - -/** - * WebRTC's AGC2 with the adaptive digital controller, as APM runs it - * ({@code gain_controller2.cc}): its own RNN VAD, speech and noise level estimators, a - * saturation protector choosing the headroom, the adaptive gain, and the output limiter. - * - *

TS3 uses the older AGC1 in adaptive-digital mode instead. AGC2 is its replacement in - * WebRTC: it measures the speech level only on frames its RNN VAD calls speech, and caps - * the gain so the measured noise floor stays below -50 dBFS. - * - *

It is also slower to adapt: the gain rises at most 6 dB/s, and only after 12 - * frames in a row that its VAD rates at 0.95 or more, holding still through pauses. A - * distant voice in a reverberant room (half its frames that confident) took about 9 s - * of talking to go from the initial 15 dB to the 26 dB it settled at. How fast - * AGC1 follows the same voice hasn't been measured. - * - *

Takes 10 ms mono frames at 48 kHz on the 16-bit scale, in place. - */ -public final class GainController2 { - - private static final int FRAME_SIZE = 480; - - private final RnnSpeechDetector vad = new RnnSpeechDetector(48_000); - private final float[] vadFrame = new float[FRAME_SIZE]; - private final int vadResetPeriodFrames = VAD_RESET_PERIOD_MS / FRAME_DURATION_MS; - private int timeToVadReset = vadResetPeriodFrames; - - private final SpeechLevelEstimator speechLevelEstimator; - private final NoiseFloorEstimator noiseLevelEstimator = new NoiseFloorEstimator(); - private final SaturationProtector saturationProtector = - new SaturationProtector(SATURATION_PROTECTOR_INITIAL_HEADROOM_DB, ADJACENT_SPEECH_FRAMES_THRESHOLD); - private final AdaptiveDigitalGainController adaptiveDigitalController; - private final Limiter limiter = new Limiter(); - - public GainController2(AdaptiveDigitalConfig config) { - this.speechLevelEstimator = new SpeechLevelEstimator(config, ADJACENT_SPEECH_FRAMES_THRESHOLD); - this.adaptiveDigitalController = new AdaptiveDigitalGainController(config, ADJACENT_SPEECH_FRAMES_THRESHOLD); - } - - /** - * Moves the cap on the amplified noise floor away from the configured - * {@code maxOutputNoiseLevelDbfs}, keeping the rest of the controller's state. - */ - public void setMaxOutputNoiseLevelDbfs(float dbfs) { - adaptiveDigitalController.setMaxOutputNoiseLevelDbfs(dbfs); - } - - public void process(float[] frame) { - final float speechProbability = analyzeVad(frame); - - float peak = 0.0f; - float rms = 0.0f; - for (int i = 0; i < FRAME_SIZE; i++) { - peak = Math.max(Math.abs(frame[i]), peak); - rms += frame[i] * frame[i]; - } - final float peakDbfs = Agc2Common.floatS16ToDbfs(peak); - final float rmsDbfs = Agc2Common.floatS16ToDbfs((float) Math.sqrt(rms / FRAME_SIZE)); - - final float noiseRmsDbfs = noiseLevelEstimator.analyze(frame, FRAME_SIZE); - speechLevelEstimator.update(rmsDbfs, peakDbfs, speechProbability); - final float speechLevelDbfs = speechLevelEstimator.levelDbfs(); - - saturationProtector.analyze(speechProbability, peakDbfs, speechLevelDbfs); - final float limiterEnvelopeDbfs = Agc2Common.floatS16ToDbfs(limiter.lastAudioLevel()); - - adaptiveDigitalController.process(new AdaptiveDigitalGainController.FrameInfo( - speechProbability, speechLevelDbfs, speechLevelEstimator.isConfident(), - noiseRmsDbfs, saturationProtector.headroomDb(), limiterEnvelopeDbfs), frame, FRAME_SIZE); - limiter.process(frame, FRAME_SIZE); - } - - /** {@code vad_wrapper.cc}: the RNN's state is reset every 1.5 s so it can't latch. */ - private float analyzeVad(float[] frame) { - if (--timeToVadReset <= 0) { - vad.resetNetwork(); - timeToVadReset = vadResetPeriodFrames; - } - for (int i = 0; i < FRAME_SIZE; i++) { - vadFrame[i] = frame[i] * (1.f / 32768.f); - } - return (float) vad.process(vadFrame, FRAME_SIZE); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/InterpolatedGainCurve.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/InterpolatedGainCurve.java deleted file mode 100644 index ea086ae..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/InterpolatedGainCurve.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.ts3client.audio.processing.agc2; - -/** - * The limiter's gain curve as a piecewise-linear table, from - * {@code agc2/interpolated_gain_curve.h}: identity below the knee (about -0.8 dBFS), - * then a soft knee into a hard limit at full scale. - */ -final class InterpolatedGainCurve { - - private static final float MAX_INPUT_LEVEL_LINEAR = 36766.300710566735f; - - private static final float[] X = { - 30057.296875f, 30148.986328125f, 30240.67578125f, 30424.052734375f, - 30607.4296875f, 30790.806640625f, 30974.18359375f, 31157.560546875f, - 31340.939453125f, 31524.31640625f, 31707.693359375f, 31891.0703125f, - 32074.447265625f, 32257.82421875f, 32441.201171875f, 32624.580078125f, - 32807.95703125f, 32991.33203125f, 33174.7109375f, 33358.08984375f, - 33541.46484375f, 33724.84375f, 33819.53515625f, 34009.5390625f, - 34200.05859375f, 34389.81640625f, 34674.48828125f, 35054.375f, - 35434.86328125f, 35814.81640625f, 36195.16796875f, 36575.03125f}; - - private static final float[] M = { - -3.515235675877192989e-07f, -1.050251626111275982e-06f, - -2.085213736791047268e-06f, -3.443004743530764244e-06f, - -4.773849468620028347e-06f, -6.077375928725814447e-06f, - -7.353257842623861507e-06f, -8.601219633419532329e-06f, - -9.821013009059242904e-06f, -1.101243378798244521e-05f, - -1.217532644659513608e-05f, -1.330956911260727793e-05f, - -1.441507538402220234e-05f, -1.549179251014720649e-05f, - -1.653970684856176376e-05f, -1.755882840370759368e-05f, - -1.854918446042574942e-05f, -1.951086778717581183e-05f, - -2.044398024736437947e-05f, -2.1348627342376858e-05f, - -2.222496914328075945e-05f, -2.265374678245279938e-05f, - -2.242570917587727308e-05f, -2.220122041762806475e-05f, - -2.19802095671184361e-05f, -2.176260204578284174e-05f, - -2.133731686626560986e-05f, -2.092481918225530535e-05f, - -2.052459603874012828e-05f, -2.013615448959171772e-05f, - -1.975903069251216948e-05f, -1.939277899509761482e-05f}; - - private static final float[] Q = { - 1.010565876960754395f, 1.031631827354431152f, 1.062929749488830566f, - 1.104239225387573242f, 1.144973039627075195f, 1.185109615325927734f, - 1.224629044532775879f, 1.263512492179870605f, 1.301741957664489746f, - 1.339300632476806641f, 1.376173257827758789f, 1.412345528602600098f, - 1.447803974151611328f, 1.482536554336547852f, 1.516532182693481445f, - 1.549780607223510742f, 1.582272171974182129f, 1.613999366760253906f, - 1.644955039024353027f, 1.675132393836975098f, 1.704526185989379883f, - 1.718986630439758301f, 1.711274504661560059f, 1.703639745712280273f, - 1.696081161499023438f, 1.688597679138183594f, 1.673851132392883301f, - 1.659391283988952637f, 1.645209431648254395f, 1.631297469139099121f, - 1.617647409439086914f, 1.604251742362976074f}; - - private InterpolatedGainCurve() { - } - - /** The gain to apply at {@code inputLevel}, a 16-bit-scale peak level. */ - static float lookUpGainToApply(float inputLevel) { - if (inputLevel <= X[0]) { - return 1.0f; - } - if (inputLevel >= MAX_INPUT_LEVEL_LINEAR) { - // Saturating: scale the peak straight down to full scale. - return 32768.f / inputLevel; - } - // Segment whose start is the last point below inputLevel (lower_bound - 1). - int lo = 0; - int hi = X.length; - while (lo < hi) { - int mid = (lo + hi) >>> 1; - if (X[mid] < inputLevel) lo = mid + 1; - else hi = mid; - } - final int index = lo - 1; - return M[index] * inputLevel + Q[index]; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/Limiter.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/Limiter.java deleted file mode 100644 index aec29d1..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/Limiter.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.ts3client.audio.processing.agc2; - -import static com.ts3client.audio.processing.agc2.Agc2Common.MAX_FLOAT_S16_VALUE; -import static com.ts3client.audio.processing.agc2.Agc2Common.MIN_FLOAT_S16_VALUE; -import static com.ts3client.audio.processing.agc2.Agc2Common.SUB_FRAMES_IN_FRAME; - -/** - * AGC2's output limiter, from {@code agc2/limiter.cc} and {@code fixed_digital_level_estimator.cc}: - * a peak envelope per 1/20 of the frame (instant attack, slow decay) looked up on the - * limiter's gain curve, with the gain interpolated across the sub-frames. - */ -final class Limiter { - - private static final float ATTACK_FILTER_CONSTANT = 0.0f; - private static final float DECAY_FILTER_CONSTANT = 0.9971259f; - private static final float ATTACK_FIRST_SUBFRAME_INTERPOLATION_POWER = 8.0f; - - private final float[] envelope = new float[SUB_FRAMES_IN_FRAME]; - private final float[] scalingFactors = new float[SUB_FRAMES_IN_FRAME + 1]; - private final float[] perSampleScalingFactors = new float[480]; - private float filterStateLevel; - private float lastScalingFactor = 1.f; - - /** The envelope level of the last sub-frame, on the 16-bit scale. */ - float lastAudioLevel() { - return filterStateLevel; - } - - void process(float[] frame, int samples) { - computeLevel(frame, samples); - - scalingFactors[0] = lastScalingFactor; - for (int i = 0; i < SUB_FRAMES_IN_FRAME; i++) { - scalingFactors[i + 1] = InterpolatedGainCurve.lookUpGainToApply(envelope[i]); - } - - computePerSampleSubframeFactors(samples); - for (int j = 0; j < samples; j++) { - frame[j] = Math.max(MIN_FLOAT_S16_VALUE, Math.min(MAX_FLOAT_S16_VALUE, frame[j] * perSampleScalingFactors[j])); - } - lastScalingFactor = scalingFactors[SUB_FRAMES_IN_FRAME]; - } - - private void computeLevel(float[] frame, int samples) { - final int samplesInSubFrame = samples / SUB_FRAMES_IN_FRAME; - java.util.Arrays.fill(envelope, 0.f); - for (int subFrame = 0; subFrame < SUB_FRAMES_IN_FRAME; subFrame++) { - for (int i = 0; i < samplesInSubFrame; i++) { - envelope[subFrame] = Math.max(envelope[subFrame], Math.abs(frame[subFrame * samplesInSubFrame + i])); - } - } - // Look one sub-frame ahead, so the gain is already down when a peak arrives. - for (int subFrame = 0; subFrame < SUB_FRAMES_IN_FRAME - 1; subFrame++) { - if (envelope[subFrame] < envelope[subFrame + 1]) { - envelope[subFrame] = envelope[subFrame + 1]; - } - } - for (int subFrame = 0; subFrame < SUB_FRAMES_IN_FRAME; subFrame++) { - final float value = envelope[subFrame]; - if (value > filterStateLevel) { - envelope[subFrame] = value * (1 - ATTACK_FILTER_CONSTANT) + filterStateLevel * ATTACK_FILTER_CONSTANT; - } else { - envelope[subFrame] = value * (1 - DECAY_FILTER_CONSTANT) + filterStateLevel * DECAY_FILTER_CONSTANT; - } - filterStateLevel = envelope[subFrame]; - } - } - - private void computePerSampleSubframeFactors(int samples) { - final int subframeSize = samples / SUB_FRAMES_IN_FRAME; - final boolean isAttack = scalingFactors[0] > scalingFactors[1]; - if (isAttack) { - // Upstream intends a power-curve fade here, but its i / n is integer division - // and always 0, so the first sub-frame holds the previous factor. Kept as is. - final int n = subframeSize; - for (int i = 0; i < n; i++) { - perSampleScalingFactors[i] = (float) Math.pow(1.f - i / n, ATTACK_FIRST_SUBFRAME_INTERPOLATION_POWER) - * (scalingFactors[0] - scalingFactors[1]) + scalingFactors[1]; - } - } - for (int i = isAttack ? 1 : 0; i < SUB_FRAMES_IN_FRAME; i++) { - final int subframeStart = i * subframeSize; - final float scalingStart = scalingFactors[i]; - final float scalingEnd = scalingFactors[i + 1]; - final float scalingDiff = (scalingEnd - scalingStart) / subframeSize; - for (int j = 0; j < subframeSize; j++) { - perSampleScalingFactors[subframeStart + j] = scalingStart + scalingDiff * j; - } - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/NoiseFloorEstimator.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/NoiseFloorEstimator.java deleted file mode 100644 index 71c70d3..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/NoiseFloorEstimator.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.ts3client.audio.processing.agc2; - -/** - * Estimates the background noise level, from {@code agc2/noise_level_estimator.cc}: the - * minimum frame energy over 5 s periods, rising only slowly between periods, so AGC2 - * can cap its gain before it amplifies the noise floor. - */ -final class NoiseFloorEstimator { - - private static final int FRAMES_PER_SECOND = 100; - private static final int UPDATE_PERIOD_NUM_FRAMES = 500; - - private int sampleRateHz; - private float minNoiseEnergy; - private boolean firstPeriod; - private boolean preliminaryNoiseEnergySet; - private float preliminaryNoiseEnergy; - private float noiseEnergy; - private int counter; - - NoiseFloorEstimator() { - initialize(48000); - } - - /** @return the noise RMS in dBFS */ - float analyze(float[] frame, int samples) { - final int rate = samples * FRAMES_PER_SECOND; - if (rate != sampleRateHz) { - initialize(rate); - } - float frameEnergy = 0.0f; - for (int i = 0; i < samples; i++) { - frameEnergy += frame[i] * frame[i]; - } - if (frameEnergy <= minNoiseEnergy) { - // Ignore frames at or below the int16 noise floor, e.g. digital silence. - return energyToDbfs(noiseEnergy, samples); - } - - if (preliminaryNoiseEnergySet) { - preliminaryNoiseEnergy = Math.min(preliminaryNoiseEnergy, frameEnergy); - } else { - preliminaryNoiseEnergy = frameEnergy; - preliminaryNoiseEnergySet = true; - } - - if (counter == 0) { - // Period over: move towards the new minimum, slowly if it rose. - firstPeriod = false; - noiseEnergy = smooth(noiseEnergy, preliminaryNoiseEnergy); - counter = UPDATE_PERIOD_NUM_FRAMES; - preliminaryNoiseEnergySet = false; - } else if (firstPeriod) { - noiseEnergy = preliminaryNoiseEnergy; - counter--; - } else { - noiseEnergy = Math.min(noiseEnergy, preliminaryNoiseEnergy); - counter--; - } - return energyToDbfs(noiseEnergy, samples); - } - - private void initialize(int rate) { - sampleRateHz = rate; - firstPeriod = true; - preliminaryNoiseEnergySet = false; - // Two LSBs of RMS: anything quieter is treated as silence. - minNoiseEnergy = rate * 2.0f * 2.0f / FRAMES_PER_SECOND; - preliminaryNoiseEnergy = minNoiseEnergy; - noiseEnergy = minNoiseEnergy; - counter = UPDATE_PERIOD_NUM_FRAMES; - } - - private static float smooth(float currentEstimate, float newEstimate) { - final float attack = 0.5f; - if (currentEstimate < newEstimate) { - return attack * newEstimate + (1.0f - attack) * currentEstimate; - } - return newEstimate; - } - - private static float energyToDbfs(float signalEnergy, int numSamples) { - final float rmsSquare = signalEnergy / numSamples; - final float minDbfs = -90.30899869919436f; - if (rmsSquare <= 1.0f) { - return minDbfs; - } - return 10.0f * (float) Math.log10(rmsSquare) + minDbfs; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/SaturationProtector.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/SaturationProtector.java deleted file mode 100644 index af7a760..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/SaturationProtector.java +++ /dev/null @@ -1,122 +0,0 @@ -package com.ts3client.audio.processing.agc2; - -import static com.ts3client.audio.processing.agc2.Agc2Common.FRAME_DURATION_MS; -import static com.ts3client.audio.processing.agc2.Agc2Common.MIN_LEVEL_DBFS; -import static com.ts3client.audio.processing.agc2.Agc2Common.SATURATION_PROTECTOR_BUFFER_SIZE; -import static com.ts3client.audio.processing.agc2.Agc2Common.VAD_CONFIDENCE_THRESHOLD; - -/** - * Chooses how much headroom to leave above the speech level, from - * {@code agc2/saturation_protector.cc}: it tracks how far the speech peaks, delayed by a - * few 400 ms super-frames, sit above the speech level, and keeps the margin within - * 12–25 dB. - */ -final class SaturationProtector { - - private static final int PEAK_ENVELOPER_SUPER_FRAME_LENGTH_MS = 400; - private static final float MIN_MARGIN_DB = 12.0f; - private static final float MAX_MARGIN_DB = 25.0f; - private static final float ATTACK = 0.9988493699365052f; - private static final float DECAY = 0.9997697679981565f; - - private static final class State { - float headroomDb; - /** Ring buffer of past super-frame peaks. */ - final float[] peakDelayBuffer = new float[SATURATION_PROTECTOR_BUFFER_SIZE]; - int next; - int size; - float maxPeaksDbfs; - int timeSincePushMs; - - void reset(float initialHeadroomDb) { - headroomDb = initialHeadroomDb; - next = 0; - size = 0; - maxPeaksDbfs = MIN_LEVEL_DBFS; - timeSincePushMs = 0; - } - - void copyFrom(State o) { - headroomDb = o.headroomDb; - System.arraycopy(o.peakDelayBuffer, 0, peakDelayBuffer, 0, peakDelayBuffer.length); - next = o.next; - size = o.size; - maxPeaksDbfs = o.maxPeaksDbfs; - timeSincePushMs = o.timeSincePushMs; - } - - void push(float v) { - peakDelayBuffer[next++] = v; - if (next == peakDelayBuffer.length) next = 0; - if (size < peakDelayBuffer.length) size++; - } - - /** The oldest buffered peak, or {@code fallback} while the buffer is empty. */ - float front(float fallback) { - if (size == 0) return fallback; - return peakDelayBuffer[size == peakDelayBuffer.length ? next : 0]; - } - - void update(float peakDbfs, float speechLevelDbfs) { - maxPeaksDbfs = Math.max(maxPeaksDbfs, peakDbfs); - timeSincePushMs += FRAME_DURATION_MS; - if (timeSincePushMs > PEAK_ENVELOPER_SUPER_FRAME_LENGTH_MS) { - push(maxPeaksDbfs); - maxPeaksDbfs = MIN_LEVEL_DBFS; - timeSincePushMs = 0; - } - - final float delayedPeakDbfs = front(maxPeaksDbfs); - final float differenceDb = delayedPeakDbfs - speechLevelDbfs; - if (differenceDb > headroomDb) { - headroomDb = headroomDb * ATTACK + differenceDb * (1.0f - ATTACK); - } else { - headroomDb = headroomDb * DECAY + differenceDb * (1.0f - DECAY); - } - headroomDb = Math.max(MIN_MARGIN_DB, Math.min(MAX_MARGIN_DB, headroomDb)); - } - } - - private final float initialHeadroomDb; - private final int adjacentSpeechFramesThreshold; - private final State preliminary = new State(); - private final State reliable = new State(); - private int numAdjacentSpeechFrames; - private float headroomDb; - - SaturationProtector(float initialHeadroomDb, int adjacentSpeechFramesThreshold) { - this.initialHeadroomDb = initialHeadroomDb; - this.adjacentSpeechFramesThreshold = adjacentSpeechFramesThreshold; - reset(); - } - - float headroomDb() { - return headroomDb; - } - - void analyze(float speechProbability, float peakDbfs, float speechLevelDbfs) { - if (speechProbability < VAD_CONFIDENCE_THRESHOLD) { - if (adjacentSpeechFramesThreshold > 1) { - if (numAdjacentSpeechFrames >= adjacentSpeechFramesThreshold) { - reliable.copyFrom(preliminary); - } else if (numAdjacentSpeechFrames > 0) { - preliminary.copyFrom(reliable); - } - } - numAdjacentSpeechFrames = 0; - } else { - numAdjacentSpeechFrames++; - preliminary.update(peakDbfs, speechLevelDbfs); - if (numAdjacentSpeechFrames >= adjacentSpeechFramesThreshold) { - headroomDb = preliminary.headroomDb; - } - } - } - - void reset() { - numAdjacentSpeechFrames = 0; - headroomDb = initialHeadroomDb; - preliminary.reset(initialHeadroomDb); - reliable.reset(initialHeadroomDb); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/SpeechLevelEstimator.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/SpeechLevelEstimator.java deleted file mode 100644 index ca51772..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/agc2/SpeechLevelEstimator.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.ts3client.audio.processing.agc2; - -import static com.ts3client.audio.processing.agc2.Agc2Common.FRAME_DURATION_MS; -import static com.ts3client.audio.processing.agc2.Agc2Common.LEVEL_ESTIMATOR_LEAK_FACTOR; -import static com.ts3client.audio.processing.agc2.Agc2Common.LEVEL_ESTIMATOR_TIME_TO_CONFIDENCE_MS; -import static com.ts3client.audio.processing.agc2.Agc2Common.SATURATION_PROTECTOR_INITIAL_HEADROOM_DB; -import static com.ts3client.audio.processing.agc2.Agc2Common.VAD_CONFIDENCE_THRESHOLD; - -/** - * Estimates the speech RMS level, from {@code agc2/speech_level_estimator.cc}: a - * speech-probability-weighted average over confidently voiced frames, which only takes - * effect after a run of adjacent speech frames so short noises don't move it. - */ -final class SpeechLevelEstimator { - - /** A level estimate kept as a weighted ratio, and the time left until it is trusted. */ - private static final class State { - int timeToConfidenceMs; - float numerator; - float denominator; - - void copyFrom(State other) { - timeToConfidenceMs = other.timeToConfidenceMs; - numerator = other.numerator; - denominator = other.denominator; - } - } - - private final float initialSpeechLevelDbfs; - private final int adjacentSpeechFramesThreshold; - private final State preliminary = new State(); - private final State reliable = new State(); - private float levelDbfs; - private boolean confident; - private int numAdjacentSpeechFrames; - - SpeechLevelEstimator(AdaptiveDigitalConfig config, int adjacentSpeechFramesThreshold) { - this.initialSpeechLevelDbfs = clamp(-SATURATION_PROTECTOR_INITIAL_HEADROOM_DB - - config.initialGainDb() - config.headroomDb()); - this.adjacentSpeechFramesThreshold = adjacentSpeechFramesThreshold; - reset(); - } - - float levelDbfs() { - return levelDbfs; - } - - boolean isConfident() { - return confident; - } - - void update(float rmsDbfs, float peakDbfs, float speechProbability) { - if (speechProbability < VAD_CONFIDENCE_THRESHOLD) { - // Not a speech frame: commit or roll back the preliminary estimate. - if (adjacentSpeechFramesThreshold > 1) { - if (numAdjacentSpeechFrames >= adjacentSpeechFramesThreshold) { - reliable.copyFrom(preliminary); - } else if (numAdjacentSpeechFrames > 0) { - preliminary.copyFrom(reliable); - } - } - numAdjacentSpeechFrames = 0; - } else { - numAdjacentSpeechFrames++; - final boolean bufferIsFull = preliminary.timeToConfidenceMs == 0; - if (!bufferIsFull) { - preliminary.timeToConfidenceMs -= FRAME_DURATION_MS; - } - final float leakFactor = bufferIsFull ? LEVEL_ESTIMATOR_LEAK_FACTOR : 1.0f; - preliminary.numerator = preliminary.numerator * leakFactor + rmsDbfs * speechProbability; - preliminary.denominator = preliminary.denominator * leakFactor + speechProbability; - final float level = preliminary.numerator / preliminary.denominator; - if (numAdjacentSpeechFrames >= adjacentSpeechFramesThreshold) { - levelDbfs = clamp(level); - } - } - updateIsConfident(); - } - - private void updateIsConfident() { - if (adjacentSpeechFramesThreshold == 1) { - confident = preliminary.timeToConfidenceMs == 0; - return; - } - confident = reliable.timeToConfidenceMs == 0 - || (numAdjacentSpeechFrames >= adjacentSpeechFramesThreshold - && preliminary.timeToConfidenceMs == 0); - } - - void reset() { - resetState(preliminary); - resetState(reliable); - levelDbfs = initialSpeechLevelDbfs; - numAdjacentSpeechFrames = 0; - } - - private void resetState(State state) { - state.timeToConfidenceMs = (int) LEVEL_ESTIMATOR_TIME_TO_CONFIDENCE_MS; - state.numerator = initialSpeechLevelDbfs; - state.denominator = 1.0f; - } - - private static float clamp(float levelDbfs) { - return Math.max(-90.0f, Math.min(30.0f, levelDbfs)); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/FastMath.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/FastMath.java deleted file mode 100644 index ffdeb47..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/FastMath.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.ts3client.audio.processing.ns; - -/** - * The noise suppressor's approximate log/exp, ported from {@code ns/fast_math.cc}. They are - * deliberately inexact (the log reads the float's exponent bits), and the suppressor's - * statistics were tuned with these errors in place, so they are kept as they are. - */ -final class FastMath { - - private static final float LOG_OF_2 = 0.69314718056f; - private static final float LOG10_OF_E = 0.4342944819f; - - private FastMath() { - } - - /** Reads the float's bits as an integer: the exponent lands in the top, scaled. */ - private static float fastLog2(float in) { - float out = Float.floatToRawIntBits(in); - out *= 1.1920929e-7f; // 1/2^23 - out -= 126.942695f; // exponent bias - return out; - } - - static float sqrt(float f) { - return (float) Math.sqrt(f); - } - - static float pow2(float p) { - return (float) Math.pow(2.0f, p); - } - - static float pow(float x, float p) { - return pow2(p * fastLog2(x)); - } - - static float log(float x) { - return fastLog2(x) * LOG_OF_2; - } - - static void log(float[] x, float[] y) { - for (int k = 0; k < x.length; k++) { - y[k] = log(x[k]); - } - } - - static float exp(float x) { - return pow(10.f, x * LOG10_OF_E); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/NoiseEstimator.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/NoiseEstimator.java deleted file mode 100644 index 5a3eec2..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/NoiseEstimator.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.ts3client.audio.processing.ns; - -import static com.ts3client.audio.processing.ns.NsCommon.FFT_SIZE_BY_2_PLUS_1; -import static com.ts3client.audio.processing.ns.NsCommon.SHORT_STARTUP_PHASE_BLOCKS; - -/** - * The noise spectrum, from {@code ns/noise_estimator.cc}: a quantile estimate, blended during - * the first half second with a parametric white/pink model fitted to the input, then - * refined each block according to how likely each bin holds speech. - */ -final class NoiseEstimator { - - private static final int BINS = FFT_SIZE_BY_2_PLUS_1; - private static final int START_BAND = 5; - - /** Natural log of the bin index; the first five are unused. */ - private static final float[] LOG_TABLE = { - 0.f, 0.f, 0.f, 0.f, 0.f, 1.609438f, 1.791759f, - 1.945910f, 2.079442f, 2.197225f, 2.302585f, 2.397895f, 2.484907f, 2.564949f, - 2.639057f, 2.708050f, 2.772589f, 2.833213f, 2.890372f, 2.944439f, 2.995732f, - 3.044522f, 3.091043f, 3.135494f, 3.178054f, 3.218876f, 3.258097f, 3.295837f, - 3.332205f, 3.367296f, 3.401197f, 3.433987f, 3.465736f, 3.496507f, 3.526361f, - 3.555348f, 3.583519f, 3.610918f, 3.637586f, 3.663562f, 3.688879f, 3.713572f, - 3.737669f, 3.761200f, 3.784190f, 3.806663f, 3.828641f, 3.850147f, 3.871201f, - 3.891820f, 3.912023f, 3.931826f, 3.951244f, 3.970292f, 3.988984f, 4.007333f, - 4.025352f, 4.043051f, 4.060443f, 4.077538f, 4.094345f, 4.110874f, 4.127134f, - 4.143135f, 4.158883f, 4.174387f, 4.189655f, 4.204693f, 4.219508f, 4.234107f, - 4.248495f, 4.262680f, 4.276666f, 4.290460f, 4.304065f, 4.317488f, 4.330733f, - 4.343805f, 4.356709f, 4.369448f, 4.382027f, 4.394449f, 4.406719f, 4.418841f, - 4.430817f, 4.442651f, 4.454347f, 4.465908f, 4.477337f, 4.488636f, 4.499810f, - 4.510859f, 4.521789f, 4.532599f, 4.543295f, 4.553877f, 4.564348f, 4.574711f, - 4.584968f, 4.595119f, 4.605170f, 4.615121f, 4.624973f, 4.634729f, 4.644391f, - 4.653960f, 4.663439f, 4.672829f, 4.682131f, 4.691348f, 4.700480f, 4.709530f, - 4.718499f, 4.727388f, 4.736198f, 4.744932f, 4.753591f, 4.762174f, 4.770685f, - 4.779124f, 4.787492f, 4.795791f, 4.804021f, 4.812184f, 4.820282f, 4.828314f, - 4.836282f, 4.844187f, 4.852030f}; - - private final SuppressionLevel params; - private final QuantileNoiseEstimator quantileNoiseEstimator = new QuantileNoiseEstimator(); - - private float whiteNoiseLevel; - private float pinkNoiseNumerator; - private float pinkNoiseExp; - final float[] prevNoiseSpectrum = new float[BINS]; - final float[] conservativeNoiseSpectrum = new float[BINS]; - final float[] parametricNoiseSpectrum = new float[BINS]; - final float[] noiseSpectrum = new float[BINS]; - - NoiseEstimator(SuppressionLevel params) { - this.params = params; - } - - void prepareAnalysis() { - System.arraycopy(noiseSpectrum, 0, prevNoiseSpectrum, 0, BINS); - } - - /** First-stage estimate for this block, before the speech probability is known. */ - void preUpdate(int numAnalyzedFrames, float[] signalSpectrum, float signalSpectralSum) { - quantileNoiseEstimator.estimate(signalSpectrum, noiseSpectrum); - if (numAnalyzedFrames >= SHORT_STARTUP_PHASE_BLOCKS) return; - - // Fit white and pink noise models to the spectrum while the quantiles settle. - float sumLogILogMagn = 0.f; - float sumLogI = 0.f; - float sumLogISquare = 0.f; - float sumLogMagn = 0.f; - for (int i = START_BAND; i < BINS; i++) { - float logI = LOG_TABLE[i]; - sumLogI += logI; - sumLogISquare += logI * logI; - float logSignal = FastMath.log(signalSpectrum[i]); - sumLogMagn += logSignal; - sumLogILogMagn += logI * logSignal; - } - - final float oneByBins = 1.f / BINS; - whiteNoiseLevel += signalSpectralSum * oneByBins * params.overSubtractionFactor; - - float denom = sumLogISquare * (BINS - START_BAND) - sumLogI * sumLogI; - float num = sumLogISquare * sumLogMagn - sumLogI * sumLogILogMagn; - float pinkNoiseAdjustment = num / denom; - pinkNoiseAdjustment = Math.max(pinkNoiseAdjustment, 0.f); - pinkNoiseNumerator += pinkNoiseAdjustment; - num = sumLogI * sumLogMagn - (BINS - START_BAND) * sumLogILogMagn; - pinkNoiseAdjustment = num / denom; - pinkNoiseAdjustment = Math.max(Math.min(pinkNoiseAdjustment, 1.f), 0.f); - pinkNoiseExp += pinkNoiseAdjustment; - - final float oneByNumAnalyzedFramesPlus1 = 1.f / (numAnalyzedFrames + 1.f); - float parametricExp = 0.f; - float parametricNum = 0.f; - if (pinkNoiseExp > 0.f) { - parametricNum = FastMath.exp(pinkNoiseNumerator * oneByNumAnalyzedFramesPlus1); - parametricNum *= numAnalyzedFrames + 1.f; - parametricExp = pinkNoiseExp * oneByNumAnalyzedFramesPlus1; - } - - for (int i = 0; i < BINS; i++) { - if (pinkNoiseExp == 0.f) { - parametricNoiseSpectrum[i] = whiteNoiseLevel; - } else { - float useBand = i < START_BAND ? START_BAND : i; - parametricNoiseSpectrum[i] = parametricNum / FastMath.pow(useBand, parametricExp); - } - } - - final float oneByShortStartupPhaseBlocks = 1.f / SHORT_STARTUP_PHASE_BLOCKS; - for (int i = 0; i < BINS; i++) { - noiseSpectrum[i] *= numAnalyzedFrames; - float tmp = parametricNoiseSpectrum[i] * (SHORT_STARTUP_PHASE_BLOCKS - numAnalyzedFrames); - noiseSpectrum[i] += tmp * oneByNumAnalyzedFramesPlus1; - noiseSpectrum[i] *= oneByShortStartupPhaseBlocks; - } - } - - /** Refines the estimate, updating slowly where speech is likely. */ - void postUpdate(float[] speechProbability, float[] signalSpectrum) { - final float noiseUpdate = 0.9f; - final float probRange = .2f; - float gamma = noiseUpdate; - for (int i = 0; i < BINS; i++) { - final float probSpeech = speechProbability[i]; - final float probNonSpeech = 1.f - probSpeech; - - float noiseUpdateTmp = gamma * prevNoiseSpectrum[i] - + (1.f - gamma) * (probNonSpeech * signalSpectrum[i] + probSpeech * prevNoiseSpectrum[i]); - - float gammaOld = gamma; - gamma = probSpeech > probRange ? .99f : noiseUpdate; - - if (probSpeech < probRange) { - conservativeNoiseSpectrum[i] += 0.05f * (signalSpectrum[i] - conservativeNoiseSpectrum[i]); - } - - if (gamma == gammaOld) { - noiseSpectrum[i] = noiseUpdateTmp; - } else { - noiseSpectrum[i] = gamma * prevNoiseSpectrum[i] - + (1.f - gamma) * (probNonSpeech * signalSpectrum[i] + probSpeech * prevNoiseSpectrum[i]); - // A downward update is always safe. - noiseSpectrum[i] = Math.min(noiseSpectrum[i], noiseUpdateTmp); - } - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/NoiseSuppressor.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/NoiseSuppressor.java deleted file mode 100644 index f782d26..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/NoiseSuppressor.java +++ /dev/null @@ -1,320 +0,0 @@ -package com.ts3client.audio.processing.ns; - -import static com.ts3client.audio.processing.ns.NsCommon.FFT_SIZE; -import static com.ts3client.audio.processing.ns.NsCommon.FFT_SIZE_BY_2_PLUS_1; -import static com.ts3client.audio.processing.ns.NsCommon.NS_FRAME_SIZE; -import static com.ts3client.audio.processing.ns.NsCommon.OVERLAP_SIZE; - -import com.ts3client.audio.Fft; - -/** - * WebRTC's noise suppressor ({@code ns/noise_suppressor.cc}), the module behind TS3's - * "Remove background noise", for one channel. - * - *

It works on band-split audio in 10 ms frames, samples on the 16-bit scale: the - * lowest band (0–8 kHz at 16 kHz) is filtered per bin, and the upper bands, if - * any, are delayed to match and scaled by one gain derived from the top of the lowest band. - * As in APM, call {@link #analyze} and then {@link #process} on every frame. - */ -public final class NoiseSuppressor { - - private static final int BINS = FFT_SIZE_BY_2_PLUS_1; - - /** Rising half of the hybrid Hann/flat analysis and synthesis window. */ - private static final float[] BLOCKS_160W256_FIRST_HALF = { - 0.00000000f, 0.01636173f, 0.03271908f, 0.04906767f, 0.06540313f, - 0.08172107f, 0.09801714f, 0.11428696f, 0.13052619f, 0.14673047f, - 0.16289547f, 0.17901686f, 0.19509032f, 0.21111155f, 0.22707626f, - 0.24298018f, 0.25881905f, 0.27458862f, 0.29028468f, 0.30590302f, - 0.32143947f, 0.33688985f, 0.35225005f, 0.36751594f, 0.38268343f, - 0.39774847f, 0.41270703f, 0.42755509f, 0.44228869f, 0.45690388f, - 0.47139674f, 0.48576339f, 0.50000000f, 0.51410274f, 0.52806785f, - 0.54189158f, 0.55557023f, 0.56910015f, 0.58247770f, 0.59569930f, - 0.60876143f, 0.62166057f, 0.63439328f, 0.64695615f, 0.65934582f, - 0.67155895f, 0.68359230f, 0.69544264f, 0.70710678f, 0.71858162f, - 0.72986407f, 0.74095113f, 0.75183981f, 0.76252720f, 0.77301045f, - 0.78328675f, 0.79335334f, 0.80320753f, 0.81284668f, 0.82226822f, - 0.83146961f, 0.84044840f, 0.84920218f, 0.85772861f, 0.86602540f, - 0.87409034f, 0.88192126f, 0.88951608f, 0.89687274f, 0.90398929f, - 0.91086382f, 0.91749450f, 0.92387953f, 0.93001722f, 0.93590593f, - 0.94154407f, 0.94693013f, 0.95206268f, 0.95694034f, 0.96156180f, - 0.96592583f, 0.97003125f, 0.97387698f, 0.97746197f, 0.98078528f, - 0.98384601f, 0.98664333f, 0.98917651f, 0.99144486f, 0.99344778f, - 0.99518473f, 0.99665524f, 0.99785892f, 0.99879546f, 0.99946459f, - 0.99986614f}; - - private final int numBands; - private final SuppressionLevel params; - private int numAnalyzedFrames = -1; - - private final SpeechProbabilityEstimator speechProbabilityEstimator = new SpeechProbabilityEstimator(); - private final WienerFilter wienerFilter; - private final NoiseEstimator noiseEstimator; - private final float[] prevAnalysisSignalSpectrum = new float[BINS]; - private final float[] analyzeAnalysisMemory = new float[OVERLAP_SIZE]; - private final float[] processAnalysisMemory = new float[OVERLAP_SIZE]; - private final float[] processSynthesisMemory = new float[OVERLAP_SIZE]; - private final float[][] processDelayMemory; - - // Scratch. - private final float[] extendedFrame = new float[FFT_SIZE]; - private final float[] real = new float[FFT_SIZE]; - private final float[] imag = new float[FFT_SIZE]; - private final double[] fftRe = new double[FFT_SIZE]; - private final double[] fftIm = new double[FFT_SIZE]; - private final float[] signalSpectrum = new float[BINS]; - private final float[] priorSnr = new float[BINS]; - private final float[] postSnr = new float[BINS]; - private final float[] delayedFrame = new float[NS_FRAME_SIZE]; - - /** - * @param level how hard to cut - * @param numBands 1 for 16 kHz audio, 3 for 48 kHz split by the three-band filter bank - */ - public NoiseSuppressor(SuppressionLevel level, int numBands) { - this.params = level; - this.numBands = numBands; - this.wienerFilter = new WienerFilter(level); - this.noiseEstimator = new NoiseEstimator(level); - java.util.Arrays.fill(prevAnalysisSignalSpectrum, 1.f); - this.processDelayMemory = new float[Math.max(0, numBands - 1)][OVERLAP_SIZE]; - } - - public SuppressionLevel level() { - return params; - } - - /** Updates the noise and speech statistics from the lowest band of this frame. */ - public void analyze(float[] band0) { - noiseEstimator.prepareAnalysis(); - - // Leave the statistics alone on digital silence: learning from zeros would make any - // later signal look like speech and nothing would be suppressed for a long while. - if (energyOfExtendedFrame(band0, analyzeAnalysisMemory) <= 0.f) { - return; - } - - if (++numAnalyzedFrames < 0) { - numAnalyzedFrames = 0; - } - - formExtendedFrame(band0, analyzeAnalysisMemory, extendedFrame); - applyFilterBankWindow(extendedFrame); - fft(extendedFrame, real, imag); - computeMagnitudeSpectrum(real, imag, signalSpectrum); - - float signalEnergy = 0.f; - for (int i = 0; i < BINS; i++) { - signalEnergy += real[i] * real[i] + imag[i] * imag[i]; - } - signalEnergy /= BINS; - - float signalSpectralSum = 0.f; - for (int i = 0; i < BINS; i++) { - signalSpectralSum += signalSpectrum[i]; - } - - noiseEstimator.preUpdate(numAnalyzedFrames, signalSpectrum, signalSpectralSum); - computeSnr(wienerFilter.filter, prevAnalysisSignalSpectrum, signalSpectrum, - noiseEstimator.prevNoiseSpectrum, noiseEstimator.noiseSpectrum, priorSnr, postSnr); - speechProbabilityEstimator.update(numAnalyzedFrames, priorSnr, postSnr, - noiseEstimator.conservativeNoiseSpectrum, signalSpectrum, signalSpectralSum, signalEnergy); - noiseEstimator.postUpdate(speechProbabilityEstimator.speechProbability, signalSpectrum); - - System.arraycopy(signalSpectrum, 0, prevAnalysisSignalSpectrum, 0, BINS); - } - - /** - * Suppresses noise in place. {@code bands[0]} is the lowest band; any further bands are - * the upper ones. Each holds {@value NsCommon#NS_FRAME_SIZE} samples on the 16-bit scale. - */ - public void process(float[][] bands) { - float[] band0 = bands[0]; - formExtendedFrame(band0, processAnalysisMemory, extendedFrame); - applyFilterBankWindow(extendedFrame); - float energyBeforeFiltering = energyOfExtendedFrame(extendedFrame); - - fft(extendedFrame, real, imag); - computeMagnitudeSpectrum(real, imag, signalSpectrum); - - wienerFilter.update(numAnalyzedFrames, noiseEstimator.noiseSpectrum, noiseEstimator.prevNoiseSpectrum, - noiseEstimator.parametricNoiseSpectrum, signalSpectrum); - - float upperBandGain = 1.f; - if (numBands > 1) { - upperBandGain = computeUpperBandsGain(params.minimumAttenuatingGain, wienerFilter.filter, - speechProbabilityEstimator.speechProbability, prevAnalysisSignalSpectrum, signalSpectrum); - } - - float[] filter = wienerFilter.filter; - for (int i = 0; i < BINS; i++) { - real[i] *= filter[i]; - imag[i] *= filter[i]; - } - ifft(real, imag, extendedFrame); - - float energyAfterFiltering = energyOfExtendedFrame(extendedFrame); - applyFilterBankWindow(extendedFrame); - - float gainAdjustment = wienerFilter.computeOverallScalingFactor(numAnalyzedFrames, - speechProbabilityEstimator.priorSpeechProbability, energyBeforeFiltering, energyAfterFiltering); - for (int i = 0; i < FFT_SIZE; i++) { - extendedFrame[i] = gainAdjustment * extendedFrame[i]; - } - - overlapAndAdd(extendedFrame, processSynthesisMemory, band0); - - for (int b = 1; b < numBands; b++) { - // Delay the upper bands to line up with the lowest band's filter bank. - float[] band = bands[b]; - delaySignal(band, processDelayMemory[b - 1], delayedFrame); - for (int j = 0; j < NS_FRAME_SIZE; j++) { - band[j] = upperBandGain * delayedFrame[j]; - } - } - - for (int b = 0; b < numBands; b++) { - float[] band = bands[b]; - for (int j = 0; j < NS_FRAME_SIZE; j++) { - band[j] = Math.min(Math.max(band[j], -32768.f), 32767.f); - } - } - } - - private static void applyFilterBankWindow(float[] x) { - for (int i = 0; i < 96; i++) { - x[i] = BLOCKS_160W256_FIRST_HALF[i] * x[i]; - } - for (int i = 161, k = 95; i < FFT_SIZE; i++, k--) { - x[i] = BLOCKS_160W256_FIRST_HALF[k] * x[i]; - } - } - - /** Prepends the kept tail of the previous frames, and keeps this frame's tail. */ - private static void formExtendedFrame(float[] frame, float[] oldData, float[] extended) { - System.arraycopy(oldData, 0, extended, 0, OVERLAP_SIZE); - System.arraycopy(frame, 0, extended, OVERLAP_SIZE, NS_FRAME_SIZE); - System.arraycopy(extended, FFT_SIZE - OVERLAP_SIZE, oldData, 0, OVERLAP_SIZE); - } - - private static void overlapAndAdd(float[] extended, float[] overlapMemory, float[] output) { - for (int i = 0; i < OVERLAP_SIZE; i++) { - output[i] = overlapMemory[i] + extended[i]; - } - System.arraycopy(extended, OVERLAP_SIZE, output, OVERLAP_SIZE, NS_FRAME_SIZE - OVERLAP_SIZE); - System.arraycopy(extended, NS_FRAME_SIZE, overlapMemory, 0, OVERLAP_SIZE); - } - - private static void delaySignal(float[] frame, float[] delayBuffer, float[] delayed) { - final int samplesFromFrame = NS_FRAME_SIZE - OVERLAP_SIZE; - System.arraycopy(delayBuffer, 0, delayed, 0, OVERLAP_SIZE); - System.arraycopy(frame, 0, delayed, OVERLAP_SIZE, samplesFromFrame); - System.arraycopy(frame, samplesFromFrame, delayBuffer, 0, OVERLAP_SIZE); - } - - private static float energyOfExtendedFrame(float[] x) { - float energy = 0.f; - for (float v : x) { - energy += v * v; - } - return energy; - } - - private static float energyOfExtendedFrame(float[] frame, float[] oldData) { - float energy = 0.f; - for (float v : oldData) { - energy += v * v; - } - for (int i = 0; i < NS_FRAME_SIZE; i++) { - energy += frame[i] * frame[i]; - } - return energy; - } - - private static void computeMagnitudeSpectrum(float[] real, float[] imag, float[] spectrum) { - spectrum[0] = Math.abs(real[0]) + 1.f; - spectrum[BINS - 1] = Math.abs(real[BINS - 1]) + 1.f; - for (int i = 1; i < BINS - 1; i++) { - spectrum[i] = FastMath.sqrt(real[i] * real[i] + imag[i] * imag[i]) + 1.f; - } - } - - private static void computeSnr(float[] filter, float[] prevSignalSpectrum, float[] signalSpectrum, - float[] prevNoiseSpectrum, float[] noiseSpectrum, - float[] priorSnr, float[] postSnr) { - for (int i = 0; i < BINS; i++) { - float prevEstimate = prevSignalSpectrum[i] / (prevNoiseSpectrum[i] + 0.0001f) * filter[i]; - if (signalSpectrum[i] > noiseSpectrum[i]) { - postSnr[i] = signalSpectrum[i] / (noiseSpectrum[i] + 0.0001f) - 1.f; - } else { - postSnr[i] = 0.f; - } - // Decision-directed estimate of the prior SNR. - priorSnr[i] = 0.98f * prevEstimate + (1.f - 0.98f) * postSnr[i]; - } - } - - /** One gain for the upper bands, from speech probability and gain at the top of band 0. */ - private static float computeUpperBandsGain(float minimumAttenuatingGain, float[] filter, - float[] speechProbability, - float[] prevAnalysisSignalSpectrum, float[] signalSpectrum) { - final int numAvgBins = 32; - final float oneByNumAvgBins = 1.f / numAvgBins; - float avgProbSpeech = 0.f; - float avgFilterGain = 0.f; - for (int i = BINS - numAvgBins - 1; i < BINS - 1; i++) { - avgProbSpeech += speechProbability[i]; - avgFilterGain += filter[i]; - } - avgProbSpeech = avgProbSpeech * oneByNumAvgBins; - avgFilterGain = avgFilterGain * oneByNumAvgBins; - - // Speech removed between analysis and processing (by an AEC) should not count. - float sumAnalysisSpectrum = 0.f; - float sumProcessingSpectrum = 0.f; - for (int i = 0; i < BINS; i++) { - sumAnalysisSpectrum += prevAnalysisSignalSpectrum[i]; - sumProcessingSpectrum += signalSpectrum[i]; - } - avgProbSpeech *= sumProcessingSpectrum / sumAnalysisSpectrum; - - float gain = 0.5f * (1.f + (float) Math.tanh(2.f * avgProbSpeech - 1.f)); - if (avgProbSpeech >= 0.5f) { - gain = 0.25f * gain + 0.75f * avgFilterGain; - } else { - gain = 0.5f * gain + 0.5f * avgFilterGain; - } - return Math.min(Math.max(gain, minimumAttenuatingGain), 1.f); - } - - private void fft(float[] timeData, float[] re, float[] im) { - for (int i = 0; i < FFT_SIZE; i++) { - fftRe[i] = timeData[i]; - fftIm[i] = 0; - } - Fft.forward(fftRe, fftIm); - for (int i = 0; i < BINS; i++) { - re[i] = (float) fftRe[i]; - im[i] = (float) fftIm[i]; - } - im[0] = 0; - im[BINS - 1] = 0; - } - - private void ifft(float[] re, float[] im, float[] timeData) { - fftRe[0] = re[0]; - fftIm[0] = 0; - fftRe[BINS - 1] = re[BINS - 1]; - fftIm[BINS - 1] = 0; - for (int i = 1; i < BINS - 1; i++) { - fftRe[i] = re[i]; - fftIm[i] = im[i]; - fftRe[FFT_SIZE - i] = re[i]; - fftIm[FFT_SIZE - i] = -im[i]; - } - Fft.inverse(fftRe, fftIm); - for (int i = 0; i < FFT_SIZE; i++) { - timeData[i] = (float) fftRe[i]; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/NsCommon.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/NsCommon.java deleted file mode 100644 index 596eefe..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/NsCommon.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ts3client.audio.processing.ns; - -/** - * Sizes and constants of WebRTC's noise suppressor, mirroring {@code ns/ns_common.h}. - * - *

The suppressor works on the lowest 0–8 kHz band at 16 kHz: 10 ms - * frames of 160 samples, analysed with a 256-point FFT over a 96-sample overlap. - */ -final class NsCommon { - - static final int FFT_SIZE = 256; - static final int FFT_SIZE_BY_2_PLUS_1 = FFT_SIZE / 2 + 1; - static final int NS_FRAME_SIZE = 160; - static final int OVERLAP_SIZE = FFT_SIZE - NS_FRAME_SIZE; - - static final int SHORT_STARTUP_PHASE_BLOCKS = 50; - static final int LONG_STARTUP_PHASE_BLOCKS = 200; - static final int FEATURE_UPDATE_WINDOW_SIZE = 500; - - static final float LTR_FEATURE_THR = 0.5f; - static final float BIN_SIZE_LRT = 0.1f; - static final float BIN_SIZE_SPEC_FLAT = 0.05f; - static final float BIN_SIZE_SPEC_DIFF = 0.1f; - - static final int HISTOGRAM_SIZE = 1000; - - private NsCommon() { - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/QuantileNoiseEstimator.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/QuantileNoiseEstimator.java deleted file mode 100644 index ade8ca3..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/QuantileNoiseEstimator.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.ts3client.audio.processing.ns; - -import static com.ts3client.audio.processing.ns.NsCommon.FFT_SIZE_BY_2_PLUS_1; -import static com.ts3client.audio.processing.ns.NsCommon.LONG_STARTUP_PHASE_BLOCKS; - -import java.util.Arrays; - -/** - * Tracks a low quantile of each bin's log spectrum as the noise floor, from - * {@code ns/quantile_noise_estimator.cc}. Three estimates run staggered so that one of - * them completes a 200-block window every 67 blocks. - */ -final class QuantileNoiseEstimator { - - private static final int SIMULT = 3; - private static final int BINS = FFT_SIZE_BY_2_PLUS_1; - - private final float[] density = new float[SIMULT * BINS]; - private final float[] logQuantile = new float[SIMULT * BINS]; - private final float[] quantile = new float[BINS]; - private final int[] counter = new int[SIMULT]; - private int numUpdates = 1; - - private final float[] logSpectrum = new float[BINS]; - - QuantileNoiseEstimator() { - Arrays.fill(density, 0.3f); - Arrays.fill(logQuantile, 8.f); - final float oneBySimult = 1.f / SIMULT; - for (int i = 0; i < SIMULT; i++) { - counter[i] = (int) Math.floor(LONG_STARTUP_PHASE_BLOCKS * (i + 1.f) * oneBySimult); - } - } - - void estimate(float[] signalSpectrum, float[] noiseSpectrum) { - FastMath.log(signalSpectrum, logSpectrum); - - int quantileIndexToReturn = -1; - for (int s = 0, k = 0; s < SIMULT; s++, k += BINS) { - final float oneByCounterPlus1 = 1.f / (counter[s] + 1.f); - for (int i = 0, j = k; i < BINS; i++, j++) { - final float delta = density[j] > 1.f ? 40.f / density[j] : 40.f; - final float multiplier = delta * oneByCounterPlus1; - if (logSpectrum[i] > logQuantile[j]) { - logQuantile[j] += 0.25f * multiplier; - } else { - logQuantile[j] -= 0.75f * multiplier; - } - - final float width = 0.01f; - final float oneByWidthPlus2 = 1.f / (2.f * width); - if (Math.abs(logSpectrum[i] - logQuantile[j]) < width) { - density[j] = (counter[s] * density[j] + oneByWidthPlus2) * oneByCounterPlus1; - } - } - - if (counter[s] >= LONG_STARTUP_PHASE_BLOCKS) { - counter[s] = 0; - if (numUpdates >= LONG_STARTUP_PHASE_BLOCKS) { - quantileIndexToReturn = k; - } - } - counter[s]++; - } - - // During startup, follow the last estimate so the noise is non-zero from the start. - if (numUpdates < LONG_STARTUP_PHASE_BLOCKS) { - quantileIndexToReturn = BINS * (SIMULT - 1); - numUpdates++; - } - - if (quantileIndexToReturn >= 0) { - for (int i = 0; i < BINS; i++) { - quantile[i] = FastMath.exp(logQuantile[quantileIndexToReturn + i]); - } - } - System.arraycopy(quantile, 0, noiseSpectrum, 0, BINS); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/SignalModelEstimator.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/SignalModelEstimator.java deleted file mode 100644 index e5fdfa2..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/SignalModelEstimator.java +++ /dev/null @@ -1,255 +0,0 @@ -package com.ts3client.audio.processing.ns; - -import static com.ts3client.audio.processing.ns.NsCommon.BIN_SIZE_LRT; -import static com.ts3client.audio.processing.ns.NsCommon.BIN_SIZE_SPEC_DIFF; -import static com.ts3client.audio.processing.ns.NsCommon.BIN_SIZE_SPEC_FLAT; -import static com.ts3client.audio.processing.ns.NsCommon.FEATURE_UPDATE_WINDOW_SIZE; -import static com.ts3client.audio.processing.ns.NsCommon.FFT_SIZE_BY_2_PLUS_1; -import static com.ts3client.audio.processing.ns.NsCommon.HISTOGRAM_SIZE; -import static com.ts3client.audio.processing.ns.NsCommon.LTR_FEATURE_THR; - -import java.util.Arrays; - -/** - * The three speech features the suppressor weighs (likelihood ratio, spectral flatness and - * difference from the noise template) and the prior model that decides how to weigh them, - * re-fitted from feature histograms every 500 blocks. Ports {@code signal_model_estimator.cc}, - * {@code prior_signal_model_estimator.cc}, {@code histograms.cc} and the two model structs. - */ -final class SignalModelEstimator { - - private static final int BINS = FFT_SIZE_BY_2_PLUS_1; - private static final float ONE_BY_BINS = 1.f / BINS; - - // SignalModel. - float lrt = LTR_FEATURE_THR; - float spectralFlatness = 0.5f; - float spectralDiff = 0.5f; - final float[] avgLogLrt = new float[BINS]; - - // PriorSignalModel. - float priorLrt = LTR_FEATURE_THR; - float flatnessThreshold = .5f; - float templateDiffThreshold = .5f; - float lrtWeighting = 1.f; - float flatnessWeighting = 0.f; - float differenceWeighting = 0.f; - - private final int[] lrtHistogram = new int[HISTOGRAM_SIZE]; - private final int[] flatnessHistogram = new int[HISTOGRAM_SIZE]; - private final int[] diffHistogram = new int[HISTOGRAM_SIZE]; - - private float diffNormalization; - private float signalEnergySum; - private int histogramAnalysisCounter = 500; - - SignalModelEstimator() { - Arrays.fill(avgLogLrt, LTR_FEATURE_THR); - } - - void adjustNormalization(int numAnalyzedFrames, float signalEnergy) { - diffNormalization *= numAnalyzedFrames; - diffNormalization += signalEnergy; - diffNormalization /= (numAnalyzedFrames + 1); - } - - void update(float[] priorSnr, float[] postSnr, float[] conservativeNoiseSpectrum, - float[] signalSpectrum, float signalSpectralSum, float signalEnergy) { - updateSpectralFlatness(signalSpectrum, signalSpectralSum); - - float diff = computeSpectralDiff(conservativeNoiseSpectrum, signalSpectrum, signalSpectralSum); - spectralDiff += 0.3f * (diff - spectralDiff); - - signalEnergySum += signalEnergy; - - if (--histogramAnalysisCounter > 0) { - updateHistograms(); - } else { - updatePriorModel(); - Arrays.fill(lrtHistogram, 0); - Arrays.fill(flatnessHistogram, 0); - Arrays.fill(diffHistogram, 0); - histogramAnalysisCounter = FEATURE_UPDATE_WINDOW_SIZE; - - signalEnergySum = signalEnergySum / FEATURE_UPDATE_WINDOW_SIZE; - diffNormalization = 0.5f * (signalEnergySum + diffNormalization); - signalEnergySum = 0.f; - } - - updateSpectralLrt(priorSnr, postSnr); - } - - private float computeSpectralDiff(float[] conservativeNoiseSpectrum, float[] signalSpectrum, - float signalSpectralSum) { - float noiseAverage = 0.f; - for (int i = 0; i < BINS; i++) { - noiseAverage += conservativeNoiseSpectrum[i]; - } - noiseAverage = noiseAverage * ONE_BY_BINS; - float signalAverage = signalSpectralSum * ONE_BY_BINS; - - float covariance = 0.f; - float noiseVariance = 0.f; - float signalVariance = 0.f; - for (int i = 0; i < BINS; i++) { - float signalDiff = signalSpectrum[i] - signalAverage; - float noiseDiff = conservativeNoiseSpectrum[i] - noiseAverage; - covariance += signalDiff * noiseDiff; - noiseVariance += noiseDiff * noiseDiff; - signalVariance += signalDiff * signalDiff; - } - covariance *= ONE_BY_BINS; - noiseVariance *= ONE_BY_BINS; - signalVariance *= ONE_BY_BINS; - - float diff = signalVariance - (covariance * covariance) / (noiseVariance + 0.0001f); - return diff / (diffNormalization + 0.0001f); - } - - private void updateSpectralFlatness(float[] signalSpectrum, float signalSpectralSum) { - final float averaging = 0.3f; - for (int i = 1; i < BINS; i++) { - if (signalSpectrum[i] == 0.f) { - spectralFlatness -= averaging * spectralFlatness; - return; - } - } - float num = 0.f; - for (int i = 1; i < BINS; i++) { - num += FastMath.log(signalSpectrum[i]); - } - float denom = signalSpectralSum - signalSpectrum[0]; - denom = denom * ONE_BY_BINS; - num = num * ONE_BY_BINS; - float tmp = FastMath.exp(num) / denom; - spectralFlatness += averaging * (tmp - spectralFlatness); - } - - private void updateSpectralLrt(float[] priorSnr, float[] postSnr) { - for (int i = 0; i < BINS; i++) { - float tmp1 = 1.f + 2.f * priorSnr[i]; - float tmp2 = 2.f * priorSnr[i] / (tmp1 + 0.0001f); - float besselTmp = (postSnr[i] + 1.f) * tmp2; - avgLogLrt[i] += .5f * (besselTmp - FastMath.log(tmp1) - avgLogLrt[i]); - } - float sum = 0.f; - for (int i = 0; i < BINS; i++) { - sum += avgLogLrt[i]; - } - lrt = sum * ONE_BY_BINS; - } - - private void updateHistograms() { - final float oneByBinSizeLrt = 1.f / BIN_SIZE_LRT; - if (lrt < HISTOGRAM_SIZE * BIN_SIZE_LRT && lrt >= 0.f) { - lrtHistogram[(int) (oneByBinSizeLrt * lrt)]++; - } - final float oneByBinSizeSpecFlat = 1.f / BIN_SIZE_SPEC_FLAT; - if (spectralFlatness < HISTOGRAM_SIZE * BIN_SIZE_SPEC_FLAT && spectralFlatness >= 0.f) { - flatnessHistogram[(int) (spectralFlatness * oneByBinSizeSpecFlat)]++; - } - final float oneByBinSizeSpecDiff = 1.f / BIN_SIZE_SPEC_DIFF; - if (spectralDiff < HISTOGRAM_SIZE * BIN_SIZE_SPEC_DIFF && spectralDiff >= 0.f) { - diffHistogram[(int) (spectralDiff * oneByBinSizeSpecDiff)]++; - } - } - - private void updatePriorModel() { - boolean lowLrtFluctuations = updatePriorLrt(); - - float[] flat = firstOfTwoLargestPeaks(BIN_SIZE_SPEC_FLAT, flatnessHistogram); - float flatPeakPosition = flat[0]; - int flatPeakWeight = (int) flat[1]; - float[] diff = firstOfTwoLargestPeaks(BIN_SIZE_SPEC_DIFF, diffHistogram); - float diffPeakPosition = diff[0]; - int diffPeakWeight = (int) diff[1]; - - // Only use the features whose histograms show a clear peak. - final int useSpecFlat = flatPeakWeight < 0.3f * 500 || flatPeakPosition < 0.6f ? 0 : 1; - final int useSpecDiff = diffPeakWeight < 0.3f * 500 || lowLrtFluctuations ? 0 : 1; - - templateDiffThreshold = 1.2f * diffPeakPosition; - templateDiffThreshold = Math.min(1.f, Math.max(0.16f, templateDiffThreshold)); - - float oneByFeatureSum = 1.f / (1.f + useSpecFlat + useSpecDiff); - lrtWeighting = oneByFeatureSum; - - if (useSpecFlat == 1) { - flatnessThreshold = 0.9f * flatPeakPosition; - flatnessThreshold = Math.min(.95f, Math.max(0.1f, flatnessThreshold)); - flatnessWeighting = oneByFeatureSum; - } else { - flatnessWeighting = 0.f; - } - - differenceWeighting = useSpecDiff == 1 ? oneByFeatureSum : 0.f; - } - - /** Re-fits the prior LRT; returns whether the LRT barely fluctuates. */ - private boolean updatePriorLrt() { - float average = 0.f; - float averageCompl = 0.f; - float averageSquared = 0.f; - int count = 0; - for (int i = 0; i < 10; i++) { - float binMid = (i + 0.5f) * BIN_SIZE_LRT; - average += lrtHistogram[i] * binMid; - count += lrtHistogram[i]; - } - if (count > 0) { - average = average / count; - } - for (int i = 0; i < HISTOGRAM_SIZE; i++) { - float binMid = (i + 0.5f) * BIN_SIZE_LRT; - averageSquared += lrtHistogram[i] * binMid * binMid; - averageCompl += lrtHistogram[i] * binMid; - } - final float oneByWindow = 1.f / FEATURE_UPDATE_WINDOW_SIZE; - averageSquared = averageSquared * oneByWindow; - averageCompl = averageCompl * oneByWindow; - - boolean lowLrtFluctuations = averageSquared - average * averageCompl < 0.05f; - final float maxLrt = 1.f; - final float minLrt = .2f; - if (lowLrtFluctuations) { - priorLrt = maxLrt; - } else { - priorLrt = Math.min(maxLrt, Math.max(minLrt, 1.2f * average)); - } - return lowLrtFluctuations; - } - - /** Returns {position, weight} of the larger peak, merged with the runner-up when adjacent. */ - private static float[] firstOfTwoLargestPeaks(float binSize, int[] histogram) { - int peakValue = 0; - int secondaryPeakValue = 0; - float peakPosition = 0.f; - float secondaryPeakPosition = 0.f; - int peakWeight = 0; - int secondaryPeakWeight = 0; - - for (int i = 0; i < HISTOGRAM_SIZE; i++) { - final float binMid = (i + 0.5f) * binSize; - if (histogram[i] > peakValue) { - secondaryPeakValue = peakValue; - secondaryPeakWeight = peakWeight; - secondaryPeakPosition = peakPosition; - - peakValue = histogram[i]; - peakWeight = histogram[i]; - peakPosition = binMid; - } else if (histogram[i] > secondaryPeakValue) { - secondaryPeakValue = histogram[i]; - secondaryPeakWeight = histogram[i]; - secondaryPeakPosition = binMid; - } - } - - if (Math.abs(secondaryPeakPosition - peakPosition) < 2 * binSize - && secondaryPeakWeight > 0.5f * peakWeight) { - peakWeight += secondaryPeakWeight; - peakPosition = 0.5f * (peakPosition + secondaryPeakPosition); - } - return new float[]{peakPosition, peakWeight}; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/SpeechProbabilityEstimator.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/SpeechProbabilityEstimator.java deleted file mode 100644 index 79d24a1..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/SpeechProbabilityEstimator.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.ts3client.audio.processing.ns; - -import static com.ts3client.audio.processing.ns.NsCommon.FFT_SIZE_BY_2_PLUS_1; -import static com.ts3client.audio.processing.ns.NsCommon.LONG_STARTUP_PHASE_BLOCKS; - -/** - * Per-bin speech presence probability, from {@code ns/speech_probability_estimator.cc}: the - * features are mapped through sigmoids around the prior model's thresholds into a prior - * speech probability, which is then combined with each bin's likelihood ratio. - */ -final class SpeechProbabilityEstimator { - - private static final int BINS = FFT_SIZE_BY_2_PLUS_1; - private static final float WIDTH_PRIOR_0 = 4.f; - private static final float WIDTH_PRIOR_1 = 2.f * WIDTH_PRIOR_0; - - private final SignalModelEstimator model = new SignalModelEstimator(); - float priorSpeechProbability = .5f; - final float[] speechProbability = new float[BINS]; - - void update(int numAnalyzedFrames, float[] priorSnr, float[] postSnr, float[] conservativeNoiseSpectrum, - float[] signalSpectrum, float signalSpectralSum, float signalEnergy) { - if (numAnalyzedFrames < LONG_STARTUP_PHASE_BLOCKS) { - model.adjustNormalization(numAnalyzedFrames, signalEnergy); - } - model.update(priorSnr, postSnr, conservativeNoiseSpectrum, signalSpectrum, signalSpectralSum, - signalEnergy); - - float widthPrior = model.lrt < model.priorLrt ? WIDTH_PRIOR_1 : WIDTH_PRIOR_0; - float indicator0 = 0.5f * ((float) Math.tanh(widthPrior * (model.lrt - model.priorLrt)) + 1.f); - - widthPrior = model.spectralFlatness > model.flatnessThreshold ? WIDTH_PRIOR_1 : WIDTH_PRIOR_0; - float indicator1 = 0.5f * ((float) Math.tanh( - 1.f * widthPrior * (model.flatnessThreshold - model.spectralFlatness)) + 1.f); - - widthPrior = model.spectralDiff < model.templateDiffThreshold ? WIDTH_PRIOR_1 : WIDTH_PRIOR_0; - float indicator2 = 0.5f * ((float) Math.tanh( - widthPrior * (model.spectralDiff - model.templateDiffThreshold)) + 1.f); - - float indPrior = model.lrtWeighting * indicator0 - + model.flatnessWeighting * indicator1 - + model.differenceWeighting * indicator2; - - priorSpeechProbability += 0.1f * (indPrior - priorSpeechProbability); - priorSpeechProbability = Math.max(Math.min(priorSpeechProbability, 1.f), 0.01f); - - float gainPrior = (1.f - priorSpeechProbability) / (priorSpeechProbability + 0.0001f); - for (int i = 0; i < BINS; i++) { - float invLrt = FastMath.exp(-model.avgLogLrt[i]); - speechProbability[i] = 1.f / (1.f + gainPrior * invLrt); - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/SuppressionLevel.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/SuppressionLevel.java deleted file mode 100644 index d0865f6..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/SuppressionLevel.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.ts3client.audio.processing.ns; - -/** - * How hard the noise suppressor cuts, from {@code ns/suppression_params.cc}. TS3's - * {@code denoiser_level} slider (0–3) picks one of these directly, in this order. - */ -public enum SuppressionLevel { - - DB_6(1.f, 0.5f, false), - DB_12(1.f, 0.25f, true), - DB_18(1.1f, 0.125f, true), - DB_21(1.25f, 0.09f, true); - - final float overSubtractionFactor; - final float minimumAttenuatingGain; - final boolean useAttenuationAdjustment; - - SuppressionLevel(float overSubtractionFactor, float minimumAttenuatingGain, - boolean useAttenuationAdjustment) { - this.overSubtractionFactor = overSubtractionFactor; - this.minimumAttenuatingGain = minimumAttenuatingGain; - this.useAttenuationAdjustment = useAttenuationAdjustment; - } - - /** TS3's {@code denoiser_level}: 0 is 6 dB, 3 is 21 dB; out of range is clamped. */ - public static SuppressionLevel fromDenoiserLevel(int level) { - SuppressionLevel[] all = values(); - return all[Math.max(0, Math.min(all.length - 1, level))]; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/WienerFilter.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/WienerFilter.java deleted file mode 100644 index ef14b1e..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/ns/WienerFilter.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.ts3client.audio.processing.ns; - -import static com.ts3client.audio.processing.ns.NsCommon.FFT_SIZE_BY_2_PLUS_1; -import static com.ts3client.audio.processing.ns.NsCommon.LONG_STARTUP_PHASE_BLOCKS; -import static com.ts3client.audio.processing.ns.NsCommon.SHORT_STARTUP_PHASE_BLOCKS; - -import java.util.Arrays; - -/** - * The per-bin suppression gain, from {@code ns/wiener_filter.cc}: a Wiener filter on the - * decision-directed prior SNR, floored at the level's minimum gain, plus the overall - * adjustment that eases the cut when it removed a lot of a likely-speech frame. - */ -final class WienerFilter { - - private static final int BINS = FFT_SIZE_BY_2_PLUS_1; - - private final SuppressionLevel params; - private final float[] spectrumPrevProcess = new float[BINS]; - private final float[] initialSpectralEstimate = new float[BINS]; - final float[] filter = new float[BINS]; - - WienerFilter(SuppressionLevel params) { - this.params = params; - Arrays.fill(filter, 1.f); - } - - void update(int numAnalyzedFrames, float[] noiseSpectrum, float[] prevNoiseSpectrum, - float[] parametricNoiseSpectrum, float[] signalSpectrum) { - for (int i = 0; i < BINS; i++) { - // Previous estimate based on the previous frame with the gain filter. - float prevTsa = spectrumPrevProcess[i] / (prevNoiseSpectrum[i] + 0.0001f) * filter[i]; - - float currentTsa; - if (signalSpectrum[i] > noiseSpectrum[i]) { - currentTsa = signalSpectrum[i] / (noiseSpectrum[i] + 0.0001f) - 1.f; - } else { - currentTsa = 0.f; - } - - float snrPrior = 0.98f * prevTsa + (1.f - 0.98f) * currentTsa; - filter[i] = snrPrior / (params.overSubtractionFactor + snrPrior); - filter[i] = Math.max(Math.min(filter[i], 1.f), params.minimumAttenuatingGain); - } - - if (numAnalyzedFrames < SHORT_STARTUP_PHASE_BLOCKS) { - // Blend in the parametric noise model while the estimates settle. - final float oneByShortStartupPhaseBlocks = 1.f / SHORT_STARTUP_PHASE_BLOCKS; - for (int i = 0; i < BINS; i++) { - initialSpectralEstimate[i] += signalSpectrum[i]; - float filterInitial = initialSpectralEstimate[i] - - params.overSubtractionFactor * parametricNoiseSpectrum[i]; - filterInitial /= initialSpectralEstimate[i] + 0.0001f; - filterInitial = Math.max(Math.min(filterInitial, 1.f), params.minimumAttenuatingGain); - - filterInitial *= SHORT_STARTUP_PHASE_BLOCKS - numAnalyzedFrames; - filter[i] *= numAnalyzedFrames; - filter[i] += filterInitial; - filter[i] *= oneByShortStartupPhaseBlocks; - } - } - - System.arraycopy(signalSpectrum, 0, spectrumPrevProcess, 0, BINS); - } - - float computeOverallScalingFactor(int numAnalyzedFrames, float priorSpeechProbability, - float energyBeforeFiltering, float energyAfterFiltering) { - if (!params.useAttenuationAdjustment || numAnalyzedFrames <= LONG_STARTUP_PHASE_BLOCKS) { - return 1.f; - } - - float gain = FastMath.sqrt(energyAfterFiltering / (energyBeforeFiltering + 1.f)); - - final float bLim = 0.5f; - float scaleFactor1 = 1.f; - if (gain > bLim) { - scaleFactor1 = 1.f + 1.3f * (gain - bLim); - if (gain * scaleFactor1 > 1.f) { - scaleFactor1 = 1.f / gain; - } - } - - float scaleFactor2 = 1.f; - if (gain < bLim) { - // Do not reduce the scale too much for pause regions: attenuation is already - // controlled by the gain floor. - gain = Math.max(gain, params.minimumAttenuatingGain); - scaleFactor2 = 1.f - 0.3f * (bLim - gain); - } - - return priorSpeechProbability * scaleFactor1 + (1.f - priorSpeechProbability) * scaleFactor2; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/transients/TransientDetector.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/transients/TransientDetector.java deleted file mode 100644 index 2ace2c5..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/transients/TransientDetector.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.ts3client.audio.processing.transients; - -import java.util.ArrayDeque; - -/** - * Scores how likely a 10 ms chunk holds a transient such as a key click, from - * {@code transient/transient_detector.cc}. Each wavelet sub-band sample is compared against - * the moving mean and variance of the preceding 30 ms; the summed normalised deviation - * maps through a raised cosine to [0, 1], and the result is the maximum over the last three - * chunks so a click's tail stays covered. - */ -final class TransientDetector { - - private static final int CHUNK_MS = 10; - private static final int TRANSIENT_LENGTH_MS = 30; - private static final int CHUNKS_AT_STARTUP_LEFT_TO_DELETE = TRANSIENT_LENGTH_MS / CHUNK_MS; - private static final float DETECT_THRESHOLD = 16.f; - private static final float PI = 3.14159265358979323846f; - - private final int samplesPerChunk; - private final int leafLength; - private final WaveletPacketTree tree; - private final MovingMoments[] movingMoments = new MovingMoments[WaveletPacketTree.LEAVES]; - private final float[] firstMoments; - private final float[] secondMoments; - private final float[] lastFirstMoment = new float[WaveletPacketTree.LEAVES]; - private final float[] lastSecondMoment = new float[WaveletPacketTree.LEAVES]; - private final ArrayDeque previousResults = new ArrayDeque<>(); - private int chunksAtStartupLeftToDelete = CHUNKS_AT_STARTUP_LEFT_TO_DELETE; - - TransientDetector(int sampleRateHz) { - int perChunk = sampleRateHz * CHUNK_MS / 1000; - int perTransient = sampleRateHz * TRANSIENT_LENGTH_MS / 1000; - perChunk -= perChunk % WaveletPacketTree.LEAVES; - perTransient -= perTransient % WaveletPacketTree.LEAVES; - this.samplesPerChunk = perChunk; - this.tree = new WaveletPacketTree(perChunk); - this.leafLength = tree.leafLength(); - for (int i = 0; i < WaveletPacketTree.LEAVES; i++) { - movingMoments[i] = new MovingMoments(perTransient / WaveletPacketTree.LEAVES); - } - this.firstMoments = new float[leafLength]; - this.secondMoments = new float[leafLength]; - for (int i = 0; i < CHUNKS_AT_STARTUP_LEFT_TO_DELETE; i++) { - previousResults.add(0.f); - } - } - - int samplesPerChunk() { - return samplesPerChunk; - } - - /** Returns a detection score in [0, 1] for the chunk at {@code data[offset..]}. */ - float detect(float[] data, int offset) { - tree.update(data, offset); - - float result = 0.f; - for (int i = 0; i < WaveletPacketTree.LEAVES; i++) { - float[] leaf = tree.leaf(i); - movingMoments[i].calculateMoments(leaf, leafLength, firstMoments, secondMoments); - - // Each sample is judged against the moments of the samples before it. - float unbiased = leaf[0] - lastFirstMoment[i]; - result += unbiased * unbiased / (lastSecondMoment[i] + Float.MIN_NORMAL); - for (int j = 1; j < leafLength; j++) { - unbiased = leaf[j] - firstMoments[j - 1]; - result += unbiased * unbiased / (secondMoments[j - 1] + Float.MIN_NORMAL); - } - - lastFirstMoment[i] = firstMoments[leafLength - 1]; - lastSecondMoment[i] = secondMoments[leafLength - 1]; - } - result /= leafLength; - - // The moments need a full transient length of history before they mean anything. - if (chunksAtStartupLeftToDelete > 0) { - chunksAtStartupLeftToDelete--; - result = 0.f; - } - - if (result >= DETECT_THRESHOLD) { - result = 1.f; - } else { - // Raised cosine from 0 to 1 over [0, threshold), squared. - final float horizontalScaling = PI / DETECT_THRESHOLD; - result = ((float) Math.cos(result * horizontalScaling + PI) + 1.f) * 0.5f; - result *= result; - } - - previousResults.pollFirst(); - previousResults.addLast(result); - float max = 0.f; - for (float r : previousResults) { - max = Math.max(max, r); - } - return max; - } - - /** Running mean and mean square over a fixed window, from {@code moving_moments.cc}. */ - private static final class MovingMoments { - private final int length; - private final float[] queue; - private int head; - private float sum; - private float sumOfSquares; - - MovingMoments(int length) { - this.length = length; - this.queue = new float[length]; - } - - void calculateMoments(float[] in, int n, float[] first, float[] second) { - for (int i = 0; i < n; i++) { - final float oldValue = queue[head]; - queue[head] = in[i]; - head = (head + 1) % length; - - sum += in[i] - oldValue; - sumOfSquares += in[i] * in[i] - oldValue * oldValue; - first[i] = sum / length; - second[i] = Math.max(0.f, sumOfSquares / length); - } - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/transients/TransientSuppressor.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/transients/TransientSuppressor.java deleted file mode 100644 index 3260391..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/transients/TransientSuppressor.java +++ /dev/null @@ -1,186 +0,0 @@ -package com.ts3client.audio.processing.transients; - -import com.ts3client.audio.Fft; - -/** - * WebRTC's transient suppressor ({@code transient/transient_suppressor_impl.cc}), the module - * behind TS3's "Typing attenuation", for one 48 kHz channel. - * - *

It only acts while the user is typing: every key press is reported through - * {@code keyPressed}, the detector switches on with the first press and the suppression - * with the second within about a second; four seconds without a press switch both off. - * While suppressing, spectral peaks that jump above the running spectral mean during a - * detected transient are pulled back towards it. - * - *

TS3 runs it with no analog AGC, so APM hands it a voice probability of 1: the - * suppressor always uses its "soft", voiced restoration, and the unvoiced "hard" path with - * its random phases is never taken. That path is left out here. - * - *

The output is delayed by 544 samples (11.3 ms) whether or not it is suppressing, - * exactly as upstream, so switching on and off doesn't shift the signal. - */ -public final class TransientSuppressor { - - private static final int CHUNK_MS = 10; - private static final float MEAN_IIR_COEFFICIENT = 0.5f; - private static final int MIN_VOICE_BIN = 3; - private static final int MAX_VOICE_BIN = 60; - - private static final int KEYPRESS_PENALTY = 1000 / CHUNK_MS; - private static final int IS_TYPING_THRESHOLD = 1000 / CHUNK_MS; - private static final int CHUNKS_UNTIL_NOT_TYPING = 4000 / CHUNK_MS; - - private static final int DATA_LENGTH = 480; - private static final int ANALYSIS_LENGTH = 1024; - private static final int BUFFER_DELAY = ANALYSIS_LENGTH - DATA_LENGTH; - private static final int COMPLEX_LENGTH = ANALYSIS_LENGTH / 2 + 1; - - /** - * {@code kBlocks480w1024}: a half-sine over [32, 992], zero outside. Upstream stores it - * as a table; this formula reproduces it to within float rounding. - */ - private static final float[] WINDOW = new float[ANALYSIS_LENGTH]; - - static { - for (int i = 32; i < 992; i++) { - WINDOW[i] = (float) Math.sin(Math.PI * (i - 32) / 960.0); - } - } - - private final TransientDetector detector; - private final float[] inBuffer = new float[ANALYSIS_LENGTH]; - private final float[] outBuffer = new float[ANALYSIS_LENGTH]; - private final float[] spectralMean = new float[COMPLEX_LENGTH]; - private final float[] magnitudes = new float[COMPLEX_LENGTH]; - private final float[] meanFactor = new float[COMPLEX_LENGTH]; - private final double[] fftRe = new double[ANALYSIS_LENGTH]; - private final double[] fftIm = new double[ANALYSIS_LENGTH]; - - private float detectorSmoothed; - private int keypressCounter; - private int chunksSinceKeypress; - private boolean detectionEnabled; - private boolean suppressionEnabled; - - /** @param detectionRateHz rate of the detection data passed to {@link #suppress} */ - public TransientSuppressor(int detectionRateHz) { - this.detector = new TransientDetector(detectionRateHz); - // A double sigmoid with its minimum over the voice range (300 Hz - 3 kHz at 16 kHz bins). - final float factorHeight = 10.f; - final float lowSlope = 1.f; - final float highSlope = 0.3f; - for (int i = 0; i < COMPLEX_LENGTH; i++) { - meanFactor[i] = factorHeight / (1.f + (float) Math.exp(lowSlope * (i - MIN_VOICE_BIN))) - + factorHeight / (1.f + (float) Math.exp(highSlope * (MAX_VOICE_BIN - i))); - } - } - - /** - * Processes 10 ms in place. - * - * @param data 480 samples at 48 kHz - * @param detectionData one chunk at the detection rate: APM passes the 0–8 kHz band - * @param keyPressed whether a key went down since the previous call - */ - public void suppress(float[] data, float[] detectionData, boolean keyPressed) { - updateKeypress(keyPressed); - updateBuffers(data); - - if (detectionEnabled) { - float detectorResult = detector.detect(detectionData, 0); - // Rise with the detector, but decay slowly so the ringing of a click is covered. - final float smoothFactor = 0.1f; - detectorSmoothed = detectorResult >= detectorSmoothed - ? detectorResult - : smoothFactor * detectorSmoothed + (1 - smoothFactor) * detectorResult; - suppressChunk(); - } - - // When not suppressing, the input buffer supplies the same delay. - System.arraycopy(suppressionEnabled ? outBuffer : inBuffer, 0, data, 0, DATA_LENGTH); - } - - private void suppressChunk() { - for (int i = 0; i < ANALYSIS_LENGTH; i++) { - fftRe[i] = inBuffer[i] * WINDOW[i]; - fftIm[i] = 0; - } - Fft.forward(fftRe, fftIm); - - for (int i = 0; i < COMPLEX_LENGTH; i++) { - magnitudes[i] = Math.abs((float) fftRe[i]) + Math.abs((float) fftIm[i]); - } - - if (suppressionEnabled) { - softRestoration(); - } - - for (int i = 0; i < COMPLEX_LENGTH; i++) { - spectralMean[i] = (1 - MEAN_IIR_COEFFICIENT) * spectralMean[i] + MEAN_IIR_COEFFICIENT * magnitudes[i]; - } - - // Back to the time domain; the restoration touched the lower half, mirror it. - for (int i = 1; i < COMPLEX_LENGTH - 1; i++) { - fftRe[ANALYSIS_LENGTH - i] = fftRe[i]; - fftIm[ANALYSIS_LENGTH - i] = -fftIm[i]; - } - fftIm[0] = 0; - fftIm[COMPLEX_LENGTH - 1] = 0; - Fft.inverse(fftRe, fftIm); - for (int i = 0; i < ANALYSIS_LENGTH; i++) { - outBuffer[i] += (float) fftRe[i] * WINDOW[i]; - } - } - - /** - * Pulls peaks above the spectral mean back towards it by the detector's confidence, - * skipping those far above the block's voice-band mean: those are more likely voice. - */ - private void softRestoration() { - float blockFrequencyMean = 0; - for (int i = MIN_VOICE_BIN; i < MAX_VOICE_BIN; i++) { - blockFrequencyMean += magnitudes[i]; - } - blockFrequencyMean /= (MAX_VOICE_BIN - MIN_VOICE_BIN); - - for (int i = 0; i < COMPLEX_LENGTH; i++) { - if (magnitudes[i] > spectralMean[i] && magnitudes[i] > 0 - && magnitudes[i] < blockFrequencyMean * meanFactor[i]) { - final float newMagnitude = magnitudes[i] - detectorSmoothed * (magnitudes[i] - spectralMean[i]); - final float ratio = newMagnitude / magnitudes[i]; - fftRe[i] *= ratio; - fftIm[i] *= ratio; - magnitudes[i] = newMagnitude; - } - } - } - - private void updateKeypress(boolean keyPressed) { - if (keyPressed) { - keypressCounter += KEYPRESS_PENALTY; - chunksSinceKeypress = 0; - detectionEnabled = true; - } - keypressCounter = Math.max(0, keypressCounter - 1); - - if (keypressCounter > IS_TYPING_THRESHOLD) { - suppressionEnabled = true; - keypressCounter = 0; - } - - if (detectionEnabled && ++chunksSinceKeypress > CHUNKS_UNTIL_NOT_TYPING) { - detectionEnabled = false; - suppressionEnabled = false; - keypressCounter = 0; - } - } - - private void updateBuffers(float[] data) { - System.arraycopy(inBuffer, DATA_LENGTH, inBuffer, 0, BUFFER_DELAY); - System.arraycopy(data, 0, inBuffer, BUFFER_DELAY, DATA_LENGTH); - if (detectionEnabled) { - System.arraycopy(outBuffer, DATA_LENGTH, outBuffer, 0, BUFFER_DELAY); - java.util.Arrays.fill(outBuffer, BUFFER_DELAY, ANALYSIS_LENGTH, 0.f); - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/processing/transients/WaveletPacketTree.java b/ts3-client/core/src/main/java/com/ts3client/audio/processing/transients/WaveletPacketTree.java deleted file mode 100644 index 9ea7529..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/processing/transients/WaveletPacketTree.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.ts3client.audio.processing.transients; - -/** - * A three-level wavelet packet decomposition with Daubechies-8 filters, ported from - * {@code transient/wpd_tree.cc} and {@code wpd_node.cc}. Each node low- or high-pass - * filters its parent, keeps the odd samples and rectifies them; the eight leaves hand the - * transient detector the signal's envelope in eight sub-bands. - */ -final class WaveletPacketTree { - - static final int LEVELS = 3; - static final int LEAVES = 1 << LEVELS; - - private static final float[] HIGH_PASS = { - -5.44158422430816093862e-02f, 3.12871590914465924627e-01f, - -6.75630736298012846142e-01f, 5.85354683654869090148e-01f, - 1.58291052560238926228e-02f, -2.84015542962428091389e-01f, - -4.72484573997972536787e-04f, 1.28747426620186011803e-01f, - 1.73693010020221083600e-02f, -4.40882539310647192377e-02f, - -1.39810279170155156436e-02f, 8.74609404701565465445e-03f, - 4.87035299301066034600e-03f, -3.91740372995977108837e-04f, - -6.75449405998556772109e-04f, -1.17476784002281916305e-04f}; - - private static final float[] LOW_PASS = { - -1.17476784002281916305e-04f, 6.75449405998556772109e-04f, - -3.91740372995977108837e-04f, -4.87035299301066034600e-03f, - 8.74609404701565465445e-03f, 1.39810279170155156436e-02f, - -4.40882539310647192377e-02f, -1.73693010020221083600e-02f, - 1.28747426620186011803e-01f, 4.72484573997972536787e-04f, - -2.84015542962428091389e-01f, -1.58291052560238926228e-02f, - 5.85354683654869090148e-01f, 6.75630736298012846142e-01f, - 3.12871590914465924627e-01f, 5.44158422430816093862e-02f}; - - /** Heap-ordered: node 1 is the root, node {@code n}'s children are {@code 2n} and {@code 2n+1}. */ - private final Node[] nodes = new Node[(1 << (LEVELS + 1))]; - - WaveletPacketTree(int dataLength) { - nodes[1] = new Node(dataLength, null); - for (int level = 0; level < LEVELS; level++) { - for (int i = 0; i < (1 << level); i++) { - int index = (1 << level) + i; - nodes[2 * index] = new Node(nodes[index].length / 2, LOW_PASS); - nodes[2 * index + 1] = new Node(nodes[index].length / 2, HIGH_PASS); - } - } - } - - void update(float[] data, int offset) { - System.arraycopy(data, offset, nodes[1].data, 0, nodes[1].length); - for (int level = 0; level < LEVELS; level++) { - for (int i = 0; i < (1 << level); i++) { - int index = (1 << level) + i; - nodes[2 * index].update(nodes[index]); - nodes[2 * index + 1].update(nodes[index]); - } - } - } - - /** The data of leaf {@code index}; its first {@link #leafLength()} samples are valid. */ - float[] leaf(int index) { - return nodes[LEAVES + index].data; - } - - int leafLength() { - return nodes[LEAVES].length; - } - - private static final class Node { - final int length; - /** Sized for the parent's length: the filter output lands here before decimation. */ - final float[] data; - private final float[] coefficients; // reversed, as FIRFilterC stores them - private final float[] state; - - Node(int length, float[] coefficients) { - this.length = length; - this.data = new float[2 * length + 1]; - if (coefficients == null) { - this.coefficients = null; - this.state = null; - } else { - int n = coefficients.length; - this.coefficients = new float[n]; - for (int i = 0; i < n; i++) { - this.coefficients[i] = coefficients[n - i - 1]; - } - this.state = new float[n - 1]; - } - } - - void update(Node parent) { - filter(parent.data, parent.length, data); - // Keep the odd samples, then rectify. - for (int i = 0; i < length; i++) { - data[i] = data[2 * i + 1]; - } - for (int i = 0; i < length; i++) { - data[i] = Math.abs(data[i]); - } - } - - /** FIR convolution carrying the last {@code taps - 1} inputs over, as in {@code fir_filter_c.cc}. */ - private void filter(float[] in, int n, float[] out) { - int stateLength = state.length; - for (int i = 0; i < n; i++) { - float acc = 0.f; - int j = 0; - for (; stateLength > i && j < stateLength - i; j++) { - acc += state[i + j] * coefficients[j]; - } - for (; j < coefficients.length; j++) { - acc += in[j + i - stateLength] * coefficients[j]; - } - out[i] = acc; - } - if (n >= stateLength) { - System.arraycopy(in, n - stateLength, state, 0, stateLength); - } else { - System.arraycopy(state, n, state, 0, stateLength - n); - System.arraycopy(in, 0, state, stateLength - n, n); - } - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/vad/LinearPrediction.java b/ts3-client/core/src/main/java/com/ts3client/audio/vad/LinearPrediction.java deleted file mode 100644 index fdc693c..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/vad/LinearPrediction.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.ts3client.audio.vad; - -import static com.ts3client.audio.vad.VadConstants.NUM_LPC_COEFFICIENTS; - -/** - * Linear-prediction analysis for the pitch search, ported from WebRTC's - * {@code rnn_vad/lp_residual.cc}. - * - *

Whitening the signal before searching for a pitch makes the auto-correlation peak at - * the true period rather than at whichever formant happens to dominate. - */ -final class LinearPrediction { - - private final float[] autoCorr = new float[NUM_LPC_COEFFICIENTS]; - private final float[] reflection = new float[NUM_LPC_COEFFICIENTS - 1]; - - /** Computes the 5 post-processed inverse-filter coefficients for {@code x}. */ - void computeLpcCoefficients(float[] x, float[] lpcCoeffs) { - for (int lag = 0; lag < NUM_LPC_COEFFICIENTS; lag++) { - float sum = 0; - for (int i = 0; i < x.length - lag; i++) { - sum += x[i] * x[i + lag]; - } - autoCorr[lag] = sum; - } - if (autoCorr[0] == 0.0f) { // Empty frame. - java.util.Arrays.fill(lpcCoeffs, 0.0f); - return; - } - - // Assume a -40 dB white noise floor. - autoCorr[0] *= 1.0001f; - autoCorr[1] -= autoCorr[1] * 0.000064f; - autoCorr[2] -= autoCorr[2] * 0.000256f; - autoCorr[3] -= autoCorr[3] * 0.000576f; - autoCorr[4] -= autoCorr[4] * 0.001024f; - - java.util.Arrays.fill(reflection, 0.0f); - computeInitialInverseFilterCoefficients(); - - // Bandwidth expansion, then convolution with (1 + 0.8 z^-1). - reflection[0] *= 0.9f; - reflection[1] *= 0.9f * 0.9f; - reflection[2] *= 0.9f * 0.9f * 0.9f; - reflection[3] *= 0.9f * 0.9f * 0.9f * 0.9f; - final float c = 0.8f; - lpcCoeffs[0] = reflection[0] + c; - lpcCoeffs[1] = reflection[1] + c * reflection[0]; - lpcCoeffs[2] = reflection[2] + c * reflection[1]; - lpcCoeffs[3] = reflection[3] + c * reflection[2]; - lpcCoeffs[4] = c * reflection[3]; - } - - /** Levinson–Durbin recursion over {@link #autoCorr}, writing {@link #reflection}. */ - private void computeInitialInverseFilterCoefficients() { - float error = autoCorr[0]; - for (int i = 0; i < NUM_LPC_COEFFICIENTS - 1; i++) { - float reflectionCoeff = 0; - for (int j = 0; j < i; j++) { - reflectionCoeff += reflection[j] * autoCorr[i - j]; - } - reflectionCoeff += autoCorr[i + 1]; - - // Avoid dividing by numbers close to zero. - final float minErrorMagnitude = 1e-6f; - if (Math.abs(error) < minErrorMagnitude) { - error = Math.copySign(minErrorMagnitude, error); - } - reflectionCoeff /= -error; - - reflection[i] = reflectionCoeff; - for (int j = 0; j < ((i + 1) >> 1); j++) { - float tmp1 = reflection[j]; - float tmp2 = reflection[i - 1 - j]; - reflection[j] = tmp1 + reflectionCoeff * tmp2; - reflection[i - 1 - j] = tmp2 + reflectionCoeff * tmp1; - } - error -= reflectionCoeff * reflectionCoeff * error; - if (error < 0.001f * autoCorr[0]) { - break; - } - } - } - - /** - * Applies the inverse filter: {@code y[i] = x[i] + sum_j lpc[j] * x[i - 1 - j]}, - * with the sum truncated near the start of the buffer. - */ - static void computeLpResidual(float[] lpcCoeffs, float[] x, float[] y) { - for (int i = 0; i < x.length; i++) { - float sum = x[i]; - int taps = Math.min(i, NUM_LPC_COEFFICIENTS); - for (int j = 0; j < taps; j++) { - sum += lpcCoeffs[j] * x[i - 1 - j]; - } - y[i] = sum; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/vad/PitchEstimator.java b/ts3-client/core/src/main/java/com/ts3client/audio/vad/PitchEstimator.java deleted file mode 100644 index 6fe4a60..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/vad/PitchEstimator.java +++ /dev/null @@ -1,329 +0,0 @@ -package com.ts3client.audio.vad; - -import static com.ts3client.audio.vad.VadConstants.BUF_SIZE_12K; -import static com.ts3client.audio.vad.VadConstants.FRAME_20MS_12K; -import static com.ts3client.audio.vad.VadConstants.FRAME_20MS_24K; -import static com.ts3client.audio.vad.VadConstants.INITIAL_NUM_LAGS_24K; -import static com.ts3client.audio.vad.VadConstants.MAX_PITCH_24K; -import static com.ts3client.audio.vad.VadConstants.MAX_PITCH_48K; -import static com.ts3client.audio.vad.VadConstants.MIN_PITCH_24K; -import static com.ts3client.audio.vad.VadConstants.MIN_PITCH_48K; -import static com.ts3client.audio.vad.VadConstants.NUM_LAGS_12K; -import static com.ts3client.audio.vad.VadConstants.REFINE_NUM_LAGS_24K; - -/** - * Pitch period estimation for {@code rnn_vad}, ported from WebRTC's - * {@code rnn_vad/pitch_search.cc} and {@code pitch_search_internal.cc}. - * - *

Three stages: a coarse search over the 12 kHz decimated LP residual picks two - * candidates, those are refined against the 24 kHz buffer, and finally sub-harmonics - * of the winner are tested so that an octave error can be corrected. The result is a - * period expressed at 48 kHz, which is what the network was trained on. - * - *

Lags are stored inverted: index 0 corresponds to the maximum pitch period. - */ -final class PitchEstimator { - - /** - * For each divisor k in [2, 15], the multiplier n such that n*T/k is a sub-harmonic - * worth checking alongside T/k, chosen so no multiple is visited twice. - */ - private static final int[] SUB_HARMONIC_MULTIPLIERS = - {3, 2, 3, 2, 5, 2, 3, 2, 3, 2, 5, 2, 3, 2}; - - /** Thresholds on the initial period, computed as {@code [5*k*k for k in range(16)]}. */ - private static final int[] INITIAL_PITCH_PERIOD_THRESHOLDS = - {20, 45, 80, 125, 180, 245, 320, 405, 500, 605, 720, 845, 980, 1125}; - - /** Number of pitch periods analysed either side of a candidate during refinement. */ - private static final int PITCH_NEIGHBORHOOD_RADIUS = 2; - - private final float[] pitchBuffer12k = new float[BUF_SIZE_12K]; - private final float[] autoCorrelation12k = new float[NUM_LAGS_12K]; - private final float[] yEnergy24k = new float[REFINE_NUM_LAGS_24K]; - private final float[] autoCorrelation24k = new float[INITIAL_NUM_LAGS_24K]; - private final int[] invertedLagsIndex = new int[2 * (2 * PITCH_NEIGHBORHOOD_RADIUS + 1)]; - private int invertedLagsCount; - - // Pitch tracking: the previous estimate biases the sub-harmonic decision. - private int lastPeriod48k; - private float lastStrength; - - void reset() { - lastPeriod48k = 0; - lastStrength = 0; - } - - /** Returns the pitch period at 48 kHz for the given 24 kHz LP residual buffer. */ - int estimate(float[] pitchBuffer) { - // Coarse search at 12 kHz. WebRTC decimates without an anti-aliasing filter here; - // the refinement stage below is what recovers the accuracy. - for (int i = 0; i < BUF_SIZE_12K; i++) { - pitchBuffer12k[i] = pitchBuffer[2 * i]; - } - computeAutoCorrelation12k(); - long candidates = computePitchPeriod12kHz(); - int best = (int) (candidates >> 32) * 2; - int secondBest = (int) candidates * 2; - - computeSlidingFrameSquareEnergies24k(pitchBuffer); - int pitchLag48k = computePitchPeriod48kHz(pitchBuffer, best, secondBest); - computeExtendedPitchPeriod48kHz(pitchBuffer, MAX_PITCH_48K - pitchLag48k); - return lastPeriod48k; - } - - /** - * {@code autoCorrelation12k[lag]} is the correlation of the most recent 20 ms with the - * frame starting {@code lag} samples into the buffer. - */ - private void computeAutoCorrelation12k() { - final int refOffset = BUF_SIZE_12K - FRAME_20MS_12K; - for (int lag = 0; lag < NUM_LAGS_12K; lag++) { - float sum = 0; - for (int i = 0; i < FRAME_20MS_12K; i++) { - sum += pitchBuffer12k[refOffset + i] * pitchBuffer12k[lag + i]; - } - autoCorrelation12k[lag] = sum; - } - } - - /** Returns the best and second-best inverted lags packed into a long. */ - private long computePitchPeriod12kHz() { - float denominator = 1.0f; - for (int i = 0; i < FRAME_20MS_12K + 1; i++) { - denominator += pitchBuffer12k[i] * pitchBuffer12k[i]; - } - - int bestLag = 0; - float bestNumerator = -1.0f; - float bestDenominator = 0.0f; - int secondLag = 1; - float secondNumerator = -1.0f; - float secondDenominator = 0.0f; - - for (int invertedLag = 0; invertedLag < NUM_LAGS_12K; invertedLag++) { - // A pitch candidate must have positive correlation. - if (autoCorrelation12k[invertedLag] > 0.0f) { - float numerator = autoCorrelation12k[invertedLag] * autoCorrelation12k[invertedLag]; - // Compare numerator/denominator ratios without dividing. - if (numerator * secondDenominator > secondNumerator * denominator) { - if (numerator * bestDenominator > bestNumerator * denominator) { - secondLag = bestLag; - secondNumerator = bestNumerator; - secondDenominator = bestDenominator; - bestLag = invertedLag; - bestNumerator = numerator; - bestDenominator = denominator; - } else { - secondLag = invertedLag; - secondNumerator = numerator; - secondDenominator = denominator; - } - } - } - // Slide the energy window to the next inverted lag. - float yOld = pitchBuffer12k[invertedLag]; - float yNew = pitchBuffer12k[invertedLag + FRAME_20MS_12K]; - denominator -= yOld * yOld; - denominator += yNew * yNew; - denominator = Math.max(0.0f, denominator); - } - return ((long) bestLag << 32) | (secondLag & 0xffffffffL); - } - - /** Energy of the sliding 20 ms frame for every inverted lag. */ - private void computeSlidingFrameSquareEnergies24k(float[] pitchBuffer) { - float yy = 0; - for (int i = 0; i < FRAME_20MS_24K; i++) { - yy += pitchBuffer[i] * pitchBuffer[i]; - } - yEnergy24k[0] = yy; - for (int invertedLag = 0; invertedLag < MAX_PITCH_24K; invertedLag++) { - yy -= pitchBuffer[invertedLag] * pitchBuffer[invertedLag]; - yy += pitchBuffer[invertedLag + FRAME_20MS_24K] * pitchBuffer[invertedLag + FRAME_20MS_24K]; - yy = Math.max(1.0f, yy); - yEnergy24k[invertedLag + 1] = yy; - } - } - - /** Correlation of the most recent 20 ms with the frame at {@code invertedLag}. */ - private static float autoCorrelation(int invertedLag, float[] pitchBuffer) { - float sum = 0; - for (int i = 0; i < FRAME_20MS_24K; i++) { - sum += pitchBuffer[MAX_PITCH_24K + i] * pitchBuffer[invertedLag + i]; - } - return sum; - } - - /** - * Recomputes the auto-correlation around both candidates at 24 kHz and returns the - * strongest inverted lag, pseudo-interpolated to 48 kHz. - */ - private int computePitchPeriod48kHz(float[] pitchBuffer, int bestCandidate, int secondCandidate) { - invertedLagsCount = 0; - // Order the two neighbourhoods so the first precedes the second. - boolean swap = bestCandidate > secondCandidate; - int firstCenter = swap ? secondCandidate : bestCandidate; - int secondCenter = swap ? bestCandidate : secondCandidate; - int r1min = Math.max(firstCenter - PITCH_NEIGHBORHOOD_RADIUS, 0); - int r1max = Math.min(firstCenter + PITCH_NEIGHBORHOOD_RADIUS, INITIAL_NUM_LAGS_24K - 1); - int r2min = Math.max(secondCenter - PITCH_NEIGHBORHOOD_RADIUS, 0); - int r2max = Math.min(secondCenter + PITCH_NEIGHBORHOOD_RADIUS, INITIAL_NUM_LAGS_24K - 1); - - if (r1max + 1 >= r2min) { // Overlapping or adjacent ranges. - computeAutoCorrelationRange(pitchBuffer, r1min, r2max); - } else { - computeAutoCorrelationRange(pitchBuffer, r1min, r1max); - computeAutoCorrelationRange(pitchBuffer, r2min, r2max); - } - - int bestInvertedLag = 0; - float bestNumerator = -1.0f; - float bestDenominator = 0.0f; - for (int i = 0; i < invertedLagsCount; i++) { - int invertedLag = invertedLagsIndex[i]; - if (autoCorrelation24k[invertedLag] > 0.0f) { - float numerator = autoCorrelation24k[invertedLag] * autoCorrelation24k[invertedLag]; - float denominator = yEnergy24k[invertedLag]; - if (numerator * bestDenominator > bestNumerator * denominator) { - bestInvertedLag = invertedLag; - bestNumerator = numerator; - bestDenominator = denominator; - } - } - } - - if (bestInvertedLag == 0 || bestInvertedLag >= INITIAL_NUM_LAGS_24K - 1) { - return bestInvertedLag * 2; // Cannot interpolate at the boundaries. - } - int offset = pseudoInterpolationOffset( - autoCorrelation24k[bestInvertedLag + 1], - autoCorrelation24k[bestInvertedLag], - autoCorrelation24k[bestInvertedLag - 1]); - return 2 * bestInvertedLag + offset; - } - - private void computeAutoCorrelationRange(float[] pitchBuffer, int min, int max) { - // The pseudo-interpolation reads one lag either side, so zero those rather than - // clearing the whole array. - if (min > 0) { - autoCorrelation24k[min - 1] = 0.0f; - } - if (max < INITIAL_NUM_LAGS_24K - 1) { - autoCorrelation24k[max + 1] = 0.0f; - } - for (int invertedLag = min; invertedLag <= max; invertedLag++) { - autoCorrelation24k[invertedLag] = autoCorrelation(invertedLag, pitchBuffer); - invertedLagsIndex[invertedLagsCount++] = invertedLag; - } - } - - /** Returns a lag correction in {-1, 0, +1} based on the neighbouring correlations. */ - private static int pseudoInterpolationOffset(float prev, float curr, float next) { - if ((next - prev) > 0.7f * (curr - prev)) { - return 1; - } else if ((prev - next) > 0.7f * (curr - next)) { - return -1; - } - return 0; - } - - /** Refines {@code lag} (24 kHz) to a 48 kHz lag using pseudo-interpolation. */ - private static int pseudoInterpolationLagPitchBuf(int lag, float[] pitchBuffer) { - int offset = 0; - if (lag > 0 && lag < MAX_PITCH_24K) { - int invertedLag = MAX_PITCH_24K - lag; - offset = pseudoInterpolationOffset( - autoCorrelation(invertedLag + 1, pitchBuffer), - autoCorrelation(invertedLag, pitchBuffer), - autoCorrelation(invertedLag - 1, pitchBuffer)); - } - return 2 * lag + offset; - } - - /** Same as {@code round(multiplier * pitchPeriod / divisor)}. */ - private static int alternativePitchPeriod(int pitchPeriod, int multiplier, int divisor) { - return (2 * multiplier * pitchPeriod + divisor) / (2 * divisor); - } - - /** - * Tests sub-harmonics of the refined period and keeps the strongest, then stores the - * winner in {@link #lastPeriod48k}/{@link #lastStrength}. - */ - private void computeExtendedPitchPeriod48kHz(float[] pitchBuffer, int initialPeriod48k) { - final float xEnergy = yEnergy24k[MAX_PITCH_24K]; - - int bestPeriod = Math.min(initialPeriod48k / 2, MAX_PITCH_24K - 1); - float bestXy = autoCorrelation(MAX_PITCH_24K - bestPeriod, pitchBuffer); - float bestYEnergy = yEnergy24k[MAX_PITCH_24K - bestPeriod]; - float bestStrength = pitchStrength(bestXy, bestYEnergy, xEnergy); - - final int initialPeriod = bestPeriod; - final float initialStrength = bestStrength; - // The tracked pitch is kept at 48 kHz but compared at 24 kHz. - final int lastPeriod = lastPeriod48k / 2; - - // Largest divisor for which the alternative period is still above the minimum. - int maxPeriodDivisor = (2 * initialPeriod) / (2 * MIN_PITCH_24K - 1); - for (int periodDivisor = 2; periodDivisor <= maxPeriodDivisor; periodDivisor++) { - int alternativePeriod = alternativePitchPeriod(initialPeriod, 1, periodDivisor); - int dualPeriod = alternativePitchPeriod( - initialPeriod, SUB_HARMONIC_MULTIPLIERS[periodDivisor - 2], periodDivisor); - // Special case: for a divisor of 2 the sub-harmonic can exceed the pitch range. - if (periodDivisor == 2 && dualPeriod > MAX_PITCH_24K) { - dualPeriod = initialPeriod; - } - - // Score the candidate together with its sub-harmonic. - float xyPrimary = autoCorrelation(MAX_PITCH_24K - alternativePeriod, pitchBuffer); - float xySecondary = autoCorrelation(MAX_PITCH_24K - dualPeriod, pitchBuffer); - float xy = 0.5f * (xyPrimary + xySecondary); - float yy = 0.5f * (yEnergy24k[MAX_PITCH_24K - alternativePeriod] - + yEnergy24k[MAX_PITCH_24K - dualPeriod]); - float alternativeStrength = pitchStrength(xy, yy, xEnergy); - - if (isAlternativeStronger(lastPeriod, initialPeriod, initialStrength, - alternativePeriod, alternativeStrength, periodDivisor)) { - bestPeriod = alternativePeriod; - bestStrength = alternativeStrength; - bestXy = xy; - bestYEnergy = yy; - } - } - - bestXy = Math.max(0.0f, bestXy); - float finalStrength = (bestYEnergy <= bestXy) ? 1.0f : bestXy / (bestYEnergy + 1.0f); - finalStrength = Math.min(bestStrength, finalStrength); - - lastPeriod48k = Math.max(MIN_PITCH_48K, pseudoInterpolationLagPitchBuf(bestPeriod, pitchBuffer)); - lastStrength = finalStrength; - } - - private static float pitchStrength(float xy, float yEnergy, float xEnergy) { - return xy / (float) Math.sqrt(1.0f + xEnergy * yEnergy); - } - - private boolean isAlternativeStronger(int lastPeriod, int initialPeriod, float initialStrength, - int alternativePeriod, float alternativeStrength, - int periodDivisor) { - // Pitch tracking: a candidate close to the previous estimate clears a lower bar. - float lowerThresholdTerm = 0.0f; - int distance = Math.abs(alternativePeriod - lastPeriod); - if (distance <= 1) { - lowerThresholdTerm = lastStrength; - } else if (distance == 2 - && initialPeriod > INITIAL_PITCH_PERIOD_THRESHOLDS[periodDivisor - 2]) { - lowerThresholdTerm = 0.5f * lastStrength; - } - - // Higher frequencies get a stricter threshold: short-term correlations bias - // the search towards them and cause false positives. - float threshold = Math.max(0.3f, 0.7f * initialStrength - lowerThresholdTerm); - if (alternativePeriod < 3 * MIN_PITCH_24K) { - threshold = Math.max(0.4f, 0.85f * initialStrength - lowerThresholdTerm); - } else if (alternativePeriod < 2 * MIN_PITCH_24K) { - threshold = Math.max(0.5f, 0.9f * initialStrength - lowerThresholdTerm); - } - return alternativeStrength > threshold; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/vad/RealFft.java b/ts3-client/core/src/main/java/com/ts3client/audio/vad/RealFft.java deleted file mode 100644 index e1ce6bb..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/vad/RealFft.java +++ /dev/null @@ -1,224 +0,0 @@ -package com.ts3client.audio.vad; - -/** - * Real-input FFT for the {@code rnn_vad} spectral analysis. - * - *

The transform length is 480 (a 20 ms frame at 24 kHz), which is not a - * power of two, so the shared radix-2 {@code Fft} cannot be used. This is a - * mixed-radix Cooley–Tukey complex FFT (radices 2, 3, 4 and 5, with a generic - * DFT for any other factor) wrapped in the standard real-input trick: an - * {@code n}-point real transform is computed as an {@code n/2}-point complex one - * followed by a split step. - * - *

Output uses the packed layout WebRTC's PFFFT produces, which the band - * correlator indexes directly: - *

- *   out[0]     = Re(X[0])      (DC)
- *   out[1]     = Re(X[n/2])    (Nyquist)
- *   out[2k]    = Re(X[k])
- *   out[2k+1]  = Im(X[k])      for k in [1, n/2)
- * 
- */ -final class RealFft { - - private final int size; - private final int half; - - // Twiddles for the complex sub-transform and for the real split step. - private final float[] halfRe; - private final float[] halfIm; - private final float[] splitCos; - private final float[] splitSin; - - private final ComplexFft complexFft; - - RealFft(int size) { - if (size < 2 || (size & 1) != 0) { - throw new IllegalArgumentException("Real FFT length must be even: " + size); - } - this.size = size; - this.half = size / 2; - this.halfRe = new float[half]; - this.halfIm = new float[half]; - this.complexFft = new ComplexFft(half); - - this.splitCos = new float[half / 2 + 1]; - this.splitSin = new float[half / 2 + 1]; - for (int k = 0; k <= half / 2; k++) { - double angle = -2.0 * Math.PI * k / size; - splitCos[k] = (float) Math.cos(angle); - splitSin[k] = (float) Math.sin(angle); - } - } - - int size() { - return size; - } - - /** - * Transforms {@code in} ({@link #size} real samples) into {@code out} - * ({@link #size} floats in the packed layout described above). - */ - void forward(float[] in, float[] out) { - // Pack the real signal as half/2 complex samples: z[i] = x[2i] + j*x[2i+1]. - for (int i = 0; i < half; i++) { - halfRe[i] = in[2 * i]; - halfIm[i] = in[2 * i + 1]; - } - complexFft.forward(halfRe, halfIm); - - // Split Z into the transforms of the even and odd sample sequences, then - // recombine them into the spectrum of the original real signal. - out[0] = halfRe[0] + halfIm[0]; - out[1] = halfRe[0] - halfIm[0]; - for (int k = 1; k <= half / 2; k++) { - int mirror = half - k; - - // Even part: hermitian-symmetric average; odd part: the difference. - float evenRe = 0.5f * (halfRe[k] + halfRe[mirror]); - float evenIm = 0.5f * (halfIm[k] - halfIm[mirror]); - float oddRe = 0.5f * (halfIm[k] + halfIm[mirror]); - float oddIm = -0.5f * (halfRe[k] - halfRe[mirror]); - - float c = splitCos[k]; - float s = splitSin[k]; - float twRe = oddRe * c - oddIm * s; - float twIm = oddRe * s + oddIm * c; - - float re = evenRe + twRe; - float im = evenIm + twIm; - out[2 * k] = re; - out[2 * k + 1] = im; - - if (mirror != k) { - // X[n/2 - k] is the conjugate-mirrored companion of X[k]. - out[2 * mirror] = evenRe - twRe; - out[2 * mirror + 1] = -(evenIm - twIm); - } - } - } - - /** - * Mixed-radix complex FFT, decimation in time. - * - *

A transform of length {@code n = r * m} is computed by transforming the {@code r} - * interleaved subsequences of length {@code m} and combining them: - * {@code X[k1*m + k2] = sum_j (W_n^(j*k2) * X_j[k2]) * W_r^(j*k1)}. - * - *

The recursion is expressed directly rather than as an iterative digit-reversed - * loop, which keeps it correct for any factorisation. Scratch buffers are allocated - * once per recursion level so no transform allocates. - */ - static final class ComplexFft { - - private final int n; - private final float[] cosTable; - private final float[] sinTable; - private final float[][] scratchRe; - private final float[][] scratchIm; - private final float[] dftRe; - private final float[] dftIm; - - ComplexFft(int n) { - this.n = n; - this.cosTable = new float[n]; - this.sinTable = new float[n]; - for (int i = 0; i < n; i++) { - double angle = -2.0 * Math.PI * i / n; - cosTable[i] = (float) Math.cos(angle); - sinTable[i] = (float) Math.sin(angle); - } - int depth = 0; - int maxRadix = 1; - for (int rest = n; rest > 1; depth++) { - int r = smallestFactor(rest); - maxRadix = Math.max(maxRadix, r); - rest /= r; - } - this.scratchRe = new float[depth + 1][n]; - this.scratchIm = new float[depth + 1][n]; - this.dftRe = new float[maxRadix]; - this.dftIm = new float[maxRadix]; - } - - /** Transforms {@code re}/{@code im} of length {@code n} in place. */ - void forward(float[] re, float[] im) { - transform(re, im, 0, 1, n, scratchRe[0], scratchIm[0], 0, 1); - System.arraycopy(scratchRe[0], 0, re, 0, n); - System.arraycopy(scratchIm[0], 0, im, 0, n); - } - - /** - * Transforms the {@code len} samples starting at {@code inOff} with the given - * {@code stride}, writing the spectrum to {@code outRe}/{@code outIm} at - * {@code outOff}. - */ - private void transform(float[] inRe, float[] inIm, int inOff, int stride, int len, - float[] outRe, float[] outIm, int outOff, int depth) { - if (len == 1) { - outRe[outOff] = inRe[inOff]; - outIm[outOff] = inIm[inOff]; - return; - } - int r = smallestFactor(len); - int m = len / r; - - // Sub-transforms of the r interleaved subsequences, laid out end to end. - float[] subRe = scratchRe[depth]; - float[] subIm = scratchIm[depth]; - for (int j = 0; j < r; j++) { - transform(inRe, inIm, inOff + j * stride, stride * r, m, - subRe, subIm, outOff + j * m, depth + 1); - } - - // Twiddle step for this transform size, expressed in top-level table units. - int unit = n / len; - for (int k2 = 0; k2 < m; k2++) { - for (int j = 0; j < r; j++) { - int idx = outOff + j * m + k2; - int t = (j * k2 * unit) % n; - float c = cosTable[t]; - float s = sinTable[t]; - dftRe[j] = subRe[idx] * c - subIm[idx] * s; - dftIm[j] = subRe[idx] * s + subIm[idx] * c; - } - combine(outRe, outIm, outOff + k2, m, r); - } - } - - /** Length-{@code r} DFT of {@code dftRe}/{@code dftIm}, written with stride {@code m}. */ - private void combine(float[] outRe, float[] outIm, int outOff, int m, int r) { - switch (r) { - case 2 -> { - outRe[outOff] = dftRe[0] + dftRe[1]; - outIm[outOff] = dftIm[0] + dftIm[1]; - outRe[outOff + m] = dftRe[0] - dftRe[1]; - outIm[outOff + m] = dftIm[0] - dftIm[1]; - } - default -> { - int unit = n / r; - for (int k1 = 0; k1 < r; k1++) { - float sumRe = 0; - float sumIm = 0; - for (int j = 0; j < r; j++) { - int t = (j * k1 % r) * unit; - float c = cosTable[t]; - float s = sinTable[t]; - sumRe += dftRe[j] * c - dftIm[j] * s; - sumIm += dftRe[j] * s + dftIm[j] * c; - } - outRe[outOff + k1 * m] = sumRe; - outIm[outOff + k1 * m] = sumIm; - } - } - } - } - - private static int smallestFactor(int v) { - for (int f = 2; f * f <= v; f++) { - if (v % f == 0) return f; - } - return v; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/vad/RnnNetwork.java b/ts3-client/core/src/main/java/com/ts3client/audio/vad/RnnNetwork.java deleted file mode 100644 index ea08670..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/vad/RnnNetwork.java +++ /dev/null @@ -1,203 +0,0 @@ -package com.ts3client.audio.vad; - -/** - * The {@code rnn_vad} network: a 42→24 dense layer, a 24-unit GRU and a 24→1 - * dense output. Ported from WebRTC's {@code rnn_vad/rnn.cc}, {@code rnn_fc.cc} and - * {@code rnn_gru.cc}, using the activation approximations from RNNoise. - * - *

The GRU carries state between frames, so the caller must feed frames in order and - * {@link #reset()} on a discontinuity. Silence resets the state, matching WebRTC. - */ -final class RnnNetwork { - - private static final int INPUT_SIZE = 42; - private static final int FC1_SIZE = 24; - private static final int GRU_SIZE = 24; - private static final int NUM_GATES = 3; // update, reset, output - - private final float[] fc1Weights; // [output][input] - private final float[] fc1Bias; - private final float[] fc2Weights; - private final float[] fc2Bias; - - private final float[] gruWeights; // [gate][output][input] - private final float[] gruRecurrentWeights; // [gate][output][output] - private final float[] gruBias; // [gate][output] - - private final float[] fc1Output = new float[FC1_SIZE]; - private final float[] state = new float[GRU_SIZE]; - private final float[] update = new float[GRU_SIZE]; - private final float[] resetGate = new float[GRU_SIZE]; - private final float[] resetTimesState = new float[GRU_SIZE]; - - RnnNetwork() { - fc1Weights = transposeAndScale(RnnVadWeights.INPUT_DENSE_WEIGHTS, INPUT_SIZE, FC1_SIZE); - fc1Bias = scale(RnnVadWeights.INPUT_DENSE_BIAS); - // The output layer is 24x1, so its stored layout already matches. - fc2Weights = scale(RnnVadWeights.OUTPUT_DENSE_WEIGHTS); - fc2Bias = scale(RnnVadWeights.OUTPUT_DENSE_BIAS); - gruWeights = transposeGruTensor(RnnVadWeights.HIDDEN_GRU_WEIGHTS, FC1_SIZE, GRU_SIZE); - gruRecurrentWeights = - transposeGruTensor(RnnVadWeights.HIDDEN_GRU_RECURRENT_WEIGHTS, GRU_SIZE, GRU_SIZE); - gruBias = transposeGruTensor(RnnVadWeights.HIDDEN_GRU_BIAS, 1, GRU_SIZE); - } - - void reset() { - java.util.Arrays.fill(state, 0.0f); - } - - /** - * Returns the speech probability for a feature vector. When {@code silence} is set the - * state is cleared and zero is returned without running the network. - */ - float computeVadProbability(float[] featureVector, boolean silence) { - if (silence) { - reset(); - return 0.0f; - } - for (int o = 0; o < FC1_SIZE; o++) { - float x = fc1Bias[o] + dot(featureVector, fc1Weights, o * INPUT_SIZE, INPUT_SIZE); - fc1Output[o] = tansigApproximated(x); - } - computeGruOutput(fc1Output); - float x = fc2Bias[0] + dot(state, fc2Weights, 0, GRU_SIZE); - return sigmoidApproximated(x); - } - - private void computeGruOutput(float[] input) { - final int strideWeights = FC1_SIZE * GRU_SIZE; - final int strideRecurrent = GRU_SIZE * GRU_SIZE; - - // u = sigmoid(W_u.i + R_u.s + b_u) - computeGate(input, 0, 0, 0, update); - // r = sigmoid(W_r.i + R_r.s + b_r) - computeGate(input, GRU_SIZE, strideWeights, strideRecurrent, resetGate); - - // s' = u.s + (1 - u).ReLU(W_s.i + R_s.(s.r) + b_s) - for (int o = 0; o < GRU_SIZE; o++) { - resetTimesState[o] = state[o] * resetGate[o]; - } - for (int o = 0; o < GRU_SIZE; o++) { - float x = gruBias[2 * GRU_SIZE + o]; - x += dot(input, gruWeights, 2 * strideWeights + o * FC1_SIZE, FC1_SIZE); - x += dot(resetTimesState, gruRecurrentWeights, - 2 * strideRecurrent + o * GRU_SIZE, GRU_SIZE); - state[o] = update[o] * state[o] + (1.0f - update[o]) * Math.max(0.0f, x); - } - } - - private void computeGate(float[] input, int biasOffset, int weightsOffset, - int recurrentOffset, float[] gate) { - for (int o = 0; o < GRU_SIZE; o++) { - float x = gruBias[biasOffset + o]; - x += dot(input, gruWeights, weightsOffset + o * FC1_SIZE, FC1_SIZE); - x += dot(state, gruRecurrentWeights, recurrentOffset + o * GRU_SIZE, GRU_SIZE); - gate[o] = sigmoidApproximated(x); - } - } - - private static float dot(float[] a, float[] weights, int weightsOffset, int len) { - float sum = 0; - for (int i = 0; i < len; i++) { - sum += a[i] * weights[weightsOffset + i]; - } - return sum; - } - - // ---- weight layout ---- - - private static float[] scale(byte[] src) { - float[] out = new float[src.length]; - for (int i = 0; i < src.length; i++) { - out[i] = RnnVadWeights.SCALE * src[i]; - } - return out; - } - - /** Stored as {@code [input][output]}; the dot products want {@code [output][input]}. */ - private static float[] transposeAndScale(byte[] src, int inputSize, int outputSize) { - float[] out = new float[src.length]; - for (int o = 0; o < outputSize; o++) { - for (int i = 0; i < inputSize; i++) { - out[o * inputSize + i] = RnnVadWeights.SCALE * src[i * outputSize + o]; - } - } - return out; - } - - /** - * GRU tensors are stored as {@code [n][gate][output]} and are wanted as - * {@code [gate][output][n]}, where {@code n} is the input size (1 for the bias). - */ - private static float[] transposeGruTensor(byte[] src, int n, int outputSize) { - float[] out = new float[src.length]; - int strideSrc = NUM_GATES * outputSize; - int strideDst = n * outputSize; - for (int g = 0; g < NUM_GATES; g++) { - for (int o = 0; o < outputSize; o++) { - for (int i = 0; i < n; i++) { - out[g * strideDst + o * n + i] = - RnnVadWeights.SCALE * src[i * strideSrc + g * outputSize + o]; - } - } - } - return out; - } - - // ---- activations (RNNoise approximations, bit-compatible with WebRTC) ---- - - /** tanh sampled every 0.04, copied verbatim from RNNoise's {@code rnn_activations.h}. */ - private static final float[] TANSIG_TABLE = { - 0.000000f, 0.039979f, 0.079830f, 0.119427f, 0.158649f, 0.197375f, 0.235496f, 0.272905f, - 0.309507f, 0.345214f, 0.379949f, 0.413644f, 0.446244f, 0.477700f, 0.507977f, 0.537050f, - 0.564900f, 0.591519f, 0.616909f, 0.641077f, 0.664037f, 0.685809f, 0.706419f, 0.725897f, - 0.744277f, 0.761594f, 0.777888f, 0.793199f, 0.807569f, 0.821040f, 0.833655f, 0.845456f, - 0.856485f, 0.866784f, 0.876393f, 0.885352f, 0.893698f, 0.901468f, 0.908698f, 0.915420f, - 0.921669f, 0.927473f, 0.932862f, 0.937863f, 0.942503f, 0.946806f, 0.950795f, 0.954492f, - 0.957917f, 0.961090f, 0.964028f, 0.966747f, 0.969265f, 0.971594f, 0.973749f, 0.975743f, - 0.977587f, 0.979293f, 0.980869f, 0.982327f, 0.983675f, 0.984921f, 0.986072f, 0.987136f, - 0.988119f, 0.989027f, 0.989867f, 0.990642f, 0.991359f, 0.992020f, 0.992631f, 0.993196f, - 0.993718f, 0.994199f, 0.994644f, 0.995055f, 0.995434f, 0.995784f, 0.996108f, 0.996407f, - 0.996682f, 0.996937f, 0.997172f, 0.997389f, 0.997590f, 0.997775f, 0.997946f, 0.998104f, - 0.998249f, 0.998384f, 0.998508f, 0.998623f, 0.998728f, 0.998826f, 0.998916f, 0.999000f, - 0.999076f, 0.999147f, 0.999213f, 0.999273f, 0.999329f, 0.999381f, 0.999428f, 0.999472f, - 0.999513f, 0.999550f, 0.999585f, 0.999617f, 0.999646f, 0.999673f, 0.999699f, 0.999722f, - 0.999743f, 0.999763f, 0.999781f, 0.999798f, 0.999813f, 0.999828f, 0.999841f, 0.999853f, - 0.999865f, 0.999875f, 0.999885f, 0.999893f, 0.999902f, 0.999909f, 0.999916f, 0.999923f, - 0.999929f, 0.999934f, 0.999939f, 0.999944f, 0.999948f, 0.999952f, 0.999956f, 0.999959f, - 0.999962f, 0.999965f, 0.999968f, 0.999970f, 0.999973f, 0.999975f, 0.999977f, 0.999978f, - 0.999980f, 0.999982f, 0.999983f, 0.999984f, 0.999986f, 0.999987f, 0.999988f, 0.999989f, - 0.999990f, 0.999990f, 0.999991f, 0.999992f, 0.999992f, 0.999993f, 0.999994f, 0.999994f, - 0.999994f, 0.999995f, 0.999995f, 0.999996f, 0.999996f, 0.999996f, 0.999997f, 0.999997f, - 0.999997f, 0.999997f, 0.999997f, 0.999998f, 0.999998f, 0.999998f, 0.999998f, 0.999998f, - 0.999998f, 0.999999f, 0.999999f, 0.999999f, 0.999999f, 0.999999f, 0.999999f, 0.999999f, - 0.999999f, 0.999999f, 0.999999f, 0.999999f, 0.999999f, 0.999999f, 1.000000f, 1.000000f, - 1.000000f, 1.000000f, 1.000000f, 1.000000f, 1.000000f, 1.000000f, 1.000000f, 1.000000f, - 1.000000f - }; - - private static float tansigApproximated(float x) { - // Tests are reversed to catch NaNs. - if (!(x < 8.0f)) { - return 1.0f; - } - if (!(x > -8.0f)) { - return -1.0f; - } - float sign = 1.0f; - if (x < 0.0f) { - x = -x; - sign = -1.0f; - } - int i = (int) Math.floor(0.5f + 25 * x); - float y = TANSIG_TABLE[i]; - // Newton step back to x's own scale (undoing the table's factor of 25). - x -= 0.04f * i; - y = y + x * (1.0f - y * y) * (1.0f - y * x); - return sign * y; - } - - private static float sigmoidApproximated(float x) { - return 0.5f + 0.5f * tansigApproximated(0.5f * x); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/vad/RnnSpeechDetector.java b/ts3-client/core/src/main/java/com/ts3client/audio/vad/RnnSpeechDetector.java deleted file mode 100644 index 2e21a31..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/vad/RnnSpeechDetector.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.ts3client.audio.vad; - -import com.ts3client.audio.SpeechProbabilityDetector; - -/** - * {@link SpeechProbabilityDetector} backed by {@link RnnVad}, adapting an arbitrary - * capture rate and frame size to the detector's fixed 10 ms frames at 24 kHz. - * - *

Capture frames rarely divide into 10 ms chunks exactly, so leftover samples are - * carried into the next call. The reported probability is that of the most recent complete - * 10 ms frame; a capture frame long enough to span several of them advances the - * detector several times, exactly as feeding it directly would. - */ -public final class RnnSpeechDetector implements SpeechProbabilityDetector { - - /** Half-band FIR used when decimating; long enough to keep aliasing out of the passband. */ - private static final int FILTER_TAPS = 32; - - private final RnnVad vad = new RnnVad(); - - private final int sampleRate; - private final boolean decimateByTwo; - private final float[] filterCoeffs; - private final float[] filterState; - private int filterPos; - - /** Resampled samples not yet consumed as a whole 10 ms frame. */ - private final float[] pending = new float[RnnVad.FRAME_SIZE]; - private int pendingCount; - - /** Fractional read position, for capture rates that are not a multiple of 24 kHz. */ - private double resamplePos; - - public RnnSpeechDetector(int sampleRate) { - this.sampleRate = sampleRate; - this.decimateByTwo = sampleRate == 2 * RnnVad.SAMPLE_RATE; - if (decimateByTwo) { - this.filterCoeffs = lowPass(FILTER_TAPS, 0.25); - this.filterState = new float[FILTER_TAPS]; - } else { - this.filterCoeffs = null; - this.filterState = null; - } - } - - @Override - public double process(float[] frame, int length) { - if (sampleRate == RnnVad.SAMPLE_RATE) { - feed(frame, 0, length, 1); - } else if (decimateByTwo) { - decimateAndFeed(frame, length); - } else { - resampleAndFeed(frame, length); - } - return vad.probability(); - } - - @Override - public double probability() { - return vad.probability(); - } - - @Override - public void reset() { - vad.reset(); - pendingCount = 0; - resamplePos = 0; - filterPos = 0; - if (filterState != null) { - java.util.Arrays.fill(filterState, 0.0f); - } - } - - /** See {@link RnnVad#resetNetwork()}. */ - public void resetNetwork() { - vad.resetNetwork(); - } - - /** Appends samples (taking every {@code step}-th) and runs the detector per full frame. */ - private void feed(float[] src, int offset, int length, int step) { - for (int i = offset; i < offset + length; i += step) { - push(src[i]); - } - } - - /** 48 kHz (the common case): low-pass, then keep every other sample. */ - private void decimateAndFeed(float[] frame, int length) { - for (int i = 0; i < length; i++) { - filterState[filterPos] = frame[i]; - filterPos = (filterPos + 1) % FILTER_TAPS; - if ((i & 1) == 1) { - float acc = 0; - int idx = filterPos; - for (int t = 0; t < FILTER_TAPS; t++) { - acc += filterCoeffs[t] * filterState[idx]; - idx = (idx + 1) % FILTER_TAPS; - } - push(acc); - } - } - } - - /** - * Any other capture rate. Linear interpolation is enough here: the detector's own - * analysis is far coarser than the resampling error. - */ - private void resampleAndFeed(float[] frame, int length) { - double ratio = (double) sampleRate / RnnVad.SAMPLE_RATE; - while (resamplePos < length) { - int i = (int) resamplePos; - double frac = resamplePos - i; - float a = frame[i]; - float b = frame[Math.min(i + 1, length - 1)]; - push((float) ((1 - frac) * a + frac * b)); - resamplePos += ratio; - } - resamplePos -= length; - } - - private void push(float sample) { - pending[pendingCount++] = sample; - if (pendingCount == RnnVad.FRAME_SIZE) { - vad.process(pending, 0); - pendingCount = 0; - } - } - - /** Windowed-sinc low-pass with the given normalised cutoff, scaled to unit DC gain. */ - private static float[] lowPass(int taps, double cutoff) { - float[] h = new float[taps]; - double centre = (taps - 1) / 2.0; - double sum = 0; - for (int i = 0; i < taps; i++) { - double t = i - centre; - double sinc = (t == 0) ? 2 * cutoff : Math.sin(2 * Math.PI * cutoff * t) / (Math.PI * t); - double window = 0.54 - 0.46 * Math.cos(2 * Math.PI * i / (taps - 1)); // Hamming - h[i] = (float) (sinc * window); - sum += h[i]; - } - for (int i = 0; i < taps; i++) { - h[i] /= (float) sum; - } - return h; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/vad/RnnVad.java b/ts3-client/core/src/main/java/com/ts3client/audio/vad/RnnVad.java deleted file mode 100644 index 5d649d9..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/vad/RnnVad.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.ts3client.audio.vad; - -import static com.ts3client.audio.vad.VadConstants.BUF_SIZE_24K; -import static com.ts3client.audio.vad.VadConstants.FEATURE_VECTOR_SIZE; -import static com.ts3client.audio.vad.VadConstants.FRAME_10MS_24K; -import static com.ts3client.audio.vad.VadConstants.FRAME_20MS_24K; -import static com.ts3client.audio.vad.VadConstants.MAX_PITCH_24K; -import static com.ts3client.audio.vad.VadConstants.NUM_LPC_COEFFICIENTS; - -/** - * WebRTC's {@code rnn_vad} speech-probability detector, ported to Java. - * - *

This is the detector the TeamSpeak 3 client uses for its "Automatic" and "Hybrid" - * voice-activation modes: TS3 links the same network with byte-identical weights, so at a - * given threshold this gates on the same frames theirs does. - * - *

Feed exactly {@link VadConstants#FRAME_10MS_24K} samples of 24 kHz mono audio in - * [-1, 1] per call, in order. Combines {@code features_extraction.cc} and {@code rnn.cc}. - */ -public final class RnnVad { - - /** Samples per call: 10 ms at 24 kHz. */ - public static final int FRAME_SIZE = FRAME_10MS_24K; - - /** Sample rate this detector expects. */ - public static final int SAMPLE_RATE = VadConstants.SAMPLE_RATE_24K; - - /** - * WebRTC's audio processing carries float samples on the 16-bit integer scale, and the - * network's thresholds (the silence cut-off, the pitch energy floor) are calibrated for - * it. Callers pass [-1, 1], so scale on the way in. - */ - private static final float INT16_SCALE = 32768.0f; - - /** - * Rolling window of 24 kHz samples: one maximum pitch period of history followed by - * the most recent 20 ms. - */ - private final float[] pitchBuffer = new float[BUF_SIZE_24K]; - private final float[] lpResidual = new float[BUF_SIZE_24K]; - private final float[] lpcCoeffs = new float[NUM_LPC_COEFFICIENTS]; - private final float[] featureVector = new float[FEATURE_VECTOR_SIZE]; - - private final LinearPrediction linearPrediction = new LinearPrediction(); - private final PitchEstimator pitchEstimator = new PitchEstimator(); - private final SpectralFeatures spectralFeatures = new SpectralFeatures(); - private final RnnNetwork network = new RnnNetwork(); - - private float probability; - private int pitchPeriod48k; - - /** Clears all history. Call on a capture discontinuity. */ - public void reset() { - java.util.Arrays.fill(pitchBuffer, 0.0f); - pitchEstimator.reset(); - pitchPeriod48k = 0; - spectralFeatures.reset(); - network.reset(); - probability = 0.0f; - } - - /** - * Clears only the network's recurrent state, keeping the feature history. AGC2 does this - * every 1.5 s so its detector cannot latch. - */ - public void resetNetwork() { - network.reset(); - } - - /** Speech probability in [0, 1] from the most recent {@link #process} call. */ - public float probability() { - return probability; - } - - /** - * Pitch period of the most recent frame, expressed at 48 kHz as the network's - * feature is. Exposed for diagnostics and tests. - */ - public int pitchPeriod48kHz() { - return pitchPeriod48k; - } - - /** - * Analyses one 10 ms frame and returns the speech probability in [0, 1]. - * - * @param frame mono samples in [-1, 1] - * @param offset index of the first sample - */ - public float process(float[] frame, int offset) { - System.arraycopy(pitchBuffer, FRAME_10MS_24K, pitchBuffer, 0, BUF_SIZE_24K - FRAME_10MS_24K); - int start = BUF_SIZE_24K - FRAME_10MS_24K; - for (int i = 0; i < FRAME_10MS_24K; i++) { - pitchBuffer[start + i] = frame[offset + i] * INT16_SCALE; - } - - // Search the pitch on the whitened signal so formants don't dominate the peak. - linearPrediction.computeLpcCoefficients(pitchBuffer, lpcCoeffs); - LinearPrediction.computeLpResidual(lpcCoeffs, pitchBuffer, lpResidual); - pitchPeriod48k = pitchEstimator.estimate(lpResidual); - // Normalisation based on the training-set statistics. - featureVector[FEATURE_VECTOR_SIZE - 2] = 0.01f * (pitchPeriod48k - 300); - - // Compare the most recent 20 ms against the 20 ms one pitch period earlier. - int laggedOffset = MAX_PITCH_24K - pitchPeriod48k / 2; - boolean silence = spectralFeatures.checkSilenceComputeFeatures( - pitchBuffer, BUF_SIZE_24K - FRAME_20MS_24K, pitchBuffer, laggedOffset, featureVector); - - probability = network.computeVadProbability(featureVector, silence); - return probability; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/vad/RnnVadWeights.java b/ts3-client/core/src/main/java/com/ts3client/audio/vad/RnnVadWeights.java deleted file mode 100644 index 836d0cc..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/vad/RnnVadWeights.java +++ /dev/null @@ -1,273 +0,0 @@ -package com.ts3client.audio.vad; - -/** - * Quantised weights of WebRTC's {@code rnn_vad} network, copied verbatim from - * {@code third_party/rnnoise/src/rnn_vad_weights.cc} (BSD, Xiph/Jean-Marc Valin). - * - *

These are the same 4585 bytes the TeamSpeak 3 client links in, so our detector - * produces the same speech probabilities theirs does. - * - *

Values are stored quantised; {@link #SCALE} converts them to float. - */ -final class RnnVadWeights { - - /** Dequantisation factor applied to every table below. */ - static final float SCALE = 1.0f / 256.0f; - - /** FC1 weights, laid out as [input][output] (42 x 24). */ - static final byte[] INPUT_DENSE_WEIGHTS = { - -10, 0, -3, 1, -8, -6, 3, -13, 1, 0, -3, -7, -5, -3, 6, -1, -6, 0, -6, -4, -1, -2, 1, 1, -7, 2, - 21, 10, -5, -20, 24, 23, 37, 8, -2, 33, -6, 22, 13, -2, 50, 8, 13, 1, -15, 30, -10, 30, 0, 3, 5, - 27, 1, 4, -3, 41, 56, 35, -2, 49, -13, 11, 13, -2, -47, 5, -16, -60, -15, 77, -17, 26, -3, 14, - -21, 19, -5, -19, -13, 0, 10, 14, 9, 31, -13, -41, -10, 4, 22, 18, -48, -6, -10, 62, -3, -18, - -14, 12, 26, -28, 3, 14, 25, -13, -19, 6, 5, 36, -3, -65, -12, 0, 31, -7, -9, 101, -4, 26, 16, - 17, -12, -12, 14, -36, -3, 5, -15, 21, 2, 30, -3, 38, -4, 1, -6, 7, -7, 14, 38, -22, -30, -3, - -7, 3, -39, -70, -126, 25, 34, 94, -67, -22, -33, 83, -47, -118, 4, 70, 33, 25, 62, -128, -76, - -118, -113, 49, -12, -100, -18, -114, -33, 43, 32, 61, 40, -9, -106, 2, 36, -100, -40, -5, 20, - -75, 61, -51, -9, 126, -27, -52, 5, -24, -21, -126, -114, -12, 15, 106, -2, 73, -125, 50, 13, - -120, 35, 35, 4, -61, 29, -124, 6, -53, -69, -125, 64, -89, 36, -107, -103, -7, 27, 121, 69, 77, - -35, 35, 95, -125, -49, 97, -45, -43, -23, 23, -28, -65, -118, 2, 8, -126, 27, -97, 92, 5, 55, - 82, 17, -57, -115, 37, 8, -106, -46, 41, -2, 21, -44, 8, -73, -58, -39, 34, 89, -95, 95, -117, - 120, -58, 31, 123, 1, -32, -109, -110, 60, -120, -43, -74, 5, 91, 26, 21, 114, 82, -83, -126, - 123, 22, -16, -67, 25, -83, 46, 48, -34, -121, -124, -63, -35, -9, 31, 82, 123, 6, -3, 117, 93, - -2, -13, -36, 124, -112, -6, -102, -5, -33, -15, 44, -69, -127, -23, -40, -34, -85, 68, 83, -1, - 40, 8, 84, 118, -58, -55, -102, 123, -55, -14, -123, 44, -63, -14, 21, 35, 16, 24, -126, -13, - -114, 35, 20, -36, 61, -9, 97, 34, 19, -32, -109, 76, -104, 99, -119, 45, -125, -51, -28, -8, - -69, -8, 125, -45, -93, 113, 103, -41, -82, 52, 7, 126, 0, -40, 104, 55, -58, 17, -124, -93, - -58, 8, -45, 1, 56, -123, 108, -47, -23, 115, 127, 17, -68, -13, 116, -82, -44, 45, 67, -120, - -101, -15, -125, 120, -113, 17, -48, -73, 126, -64, -86, -118, -19, 112, -1, -66, -27, -62, 121, - -86, -58, 50, 89, -38, -75, 95, -111, 12, -113, 2, -68, 2, -94, -121, 91, -5, 0, 79, 43, -7, - -18, 79, 35, -38, 47, 1, -45, 83, -50, 102, 32, 55, -96, 15, -122, -69, 45, -27, 91, -62, -30, - 46, -95, 22, -72, -97, -1, 14, -122, 28, 127, 61, -126, 121, 9, 68, -120, 49, -60, 90, 3, 43, - 68, 54, 34, -10, 28, 21, -24, -54, 22, -113, -12, 82, -2, -17, -9, 127, 8, 116, -92, 0, -70, - -33, 123, 66, 116, -74, -4, 74, -72, -22, -47, 1, -83, -60, -124, 1, 122, -57, -43, 49, 40, - -126, -128, -8, -29, 28, -24, -123, -121, -70, -93, -37, -126, 11, -125, -37, 11, -31, -51, - -124, 116, -128, 8, -25, 109, 75, -12, 7, 8, 10, 117, 124, -128, -128, 29, -26, 101, 21, -128, - 87, 8, -39, 23, -128, 127, -127, 74, -55, 74, 112, 127, 4, 55, 44, -92, 123, 34, -93, 47, -21, - -92, 17, 49, -121, 92, 7, -126, -125, 124, -74, 3, -59, 18, -91, 3, -9, 9, 56, 116, 7, -29, 33, - 87, -21, -128, -13, 57, 74, 9, -29, -61, -97, -21, -95, -12, -114, 16, 82, 125, -7, 10, -24, 9, - 77, -128, -102, -25, 3, -126, 10, 13, -18, 51, 26, 127, -79, 35, 51, 12, -50, -24, 1, -7, 22, - 81, 65, 120, -30, -38, 85, 122, -4, -106, -11, 27, 53, 41, 8, -104, -66, -38, -124, 10, 12, 76, - 117, -109, 9, 11, 2, -18, 3, 113, -16, -79, -39, -123, -20, -128, 2, 13, -33, -58, 10, 84, -104, - 13, 64, 109, 1, 54, -12, 28, 24, 63, -126, 118, -82, 46, -12, -15, 14, -43, 60, 22, -32, -19, - -46, 91, -107, 24, -94, 26, -47, 125, 6, 58, -15, -75, -26, -38, -35, 103, -16, -17, -13, 63, - -2, 45, -45, -73, -23, 70, -87, 51, -17, 53, 76, 14, -18, -31, -14, 103, 8, 21, -28, -33, -20, - -47, 6, 39, 40, -30, 7, -76, 55, 31, -20, -21, -59, 1, 25, -11, 17, 5, -13, -39, 0, -76, 50, - -33, -29, -50, -16, -11, -12, -1, -46, 40, -10, 65, -19, 21, -41, -32, -83, -19, -4, 49, -60, - 118, -24, -46, 9, 102, -20, 8, -19, 25, 31, -3, -37, 0, 25, 7, 29, 2, -39, 127, -64, -20, 64, - 115, -30, 36, 100, 35, 122, 127, 127, -127, 127, -127, 19, 127, -89, -79, -32, 39, -127, 125, - -80, 126, -127, 26, 8, 98, -8, -57, -90, -50, 126, 61, 127, -126, 40, -106, -68, 104, -125, - -119, 11, 10, -127, 66, -56, -12, -126, -104, 27, 75, 38, -124, -126, -125, 84, -123, -45, -114, - -128, 127, 103, -101, -124, 127, -11, -23, -123, 92, -123, 24, 126, 41, -2, -39, -27, -94, 40, - -112, -48, 127, 58, 14, 38, -75, -64, 73, 117, 100, -119, -11, 6, 32, -126, -14, 35, 121, -10, - 54, -60, 89, -3, 69, -25, -20, 43, -86, -34, 24, 27, 7, -81, -99, -23, -16, -26, 13, 35, -97, - 80, -29, -13, -121, -12, -65, -94, 70, -89, -126, -95, 88, 33, 96, 29, -90, 69, 114, -78, 65, - 90, -47, -47, 89, 1, -12, 3, 8, 30, 5, 2, -30, -1, 6, -7, 10, -4, 46, -27, -40, 22, -6, -17, 45, - 24, -9, 23, -14, -63, -26, -12, -57, 27, 25, 55, -76, -47, 21, 34, 33, 26, 17, 14, 6, 9, 26, 25, - -25, -25, -18 - }; - - /** FC1 bias (24). */ - static final byte[] INPUT_DENSE_BIAS = { - 38, -6, 127, 127, 127, -43, -127, 78, 127, 5, 127, 123, 127, 127, -128, -76, -126, 28, 127, 125, - -30, 127, -89, -20 - }; - - /** GRU1 input weights, [input][gate][output] (24 x 3 x 24). */ - static final byte[] HIDDEN_GRU_WEIGHTS = { - -124, 23, -123, -33, -95, -4, 8, -84, 4, 101, -119, 116, -4, 123, 103, -51, 29, -124, -114, -49, - 31, 9, 75, -128, 0, -49, 37, -50, 46, -21, -63, -104, 54, 82, 33, 21, 70, 127, -9, -79, -39, - -23, -127, 107, 122, -96, -46, -18, -39, 13, -28, -48, 14, 56, -52, 49, -1, -121, 25, -18, -36, - -52, -57, -30, 54, -124, -26, -47, 10, 39, 12, 2, 9, -127, -128, 102, 21, 11, -64, -71, 89, - -113, -111, 54, 31, 94, 121, -40, 30, 40, -109, 73, -9, 108, -92, 2, -127, 116, 127, 127, -122, - 95, 127, -37, -127, 28, 89, 10, 24, -104, -62, -67, -14, 38, 14, -71, 22, -41, 20, -50, 39, 63, - 86, 127, -18, 79, 4, -51, 2, 33, 117, -113, -78, 56, -91, 37, 34, -45, -44, -22, 21, -16, 56, - 30, -84, -79, 38, -74, 127, 9, -25, 2, 82, 61, 25, -26, 26, 11, 117, -65, 12, -58, 42, -62, -93, - 11, 11, 124, -123, 80, -125, 11, -90, 42, 94, 4, -109, -1, 85, -52, 45, -26, -27, 77, -5, 30, - 90, 0, 95, -7, 53, 29, -82, 22, -9, 74, 2, -12, -73, 114, 97, -64, 122, -77, 43, 91, 86, 126, - 106, 72, 90, -43, 46, 96, -51, 21, 22, 68, 22, 41, 79, 75, -46, -105, 23, -116, 127, -123, 102, - 57, 85, 10, -29, 34, 125, 126, 124, 81, -15, 54, 96, -128, 39, -124, 103, 74, 126, 127, -50, - -71, -122, -64, 93, -75, 71, 105, 122, 123, 126, 122, -127, 33, -63, -74, 124, -71, 33, 41, -56, - 19, 6, 65, 41, 90, -116, -3, -46, 75, -13, 98, -74, -42, 74, -95, -96, 81, 24, 32, -19, -123, - 74, 55, 109, 115, 0, 32, 33, 12, -20, 9, 127, 127, -61, 79, -48, -54, -49, 101, -9, 27, -106, - 74, 119, 77, 87, -126, -24, 127, 124, 31, 34, 127, 40, 3, -90, 127, 23, 57, -53, 127, -69, -88, - -33, 127, 19, -46, -9, -125, 13, -126, -113, 127, -41, 46, 106, -62, 3, -10, 111, 49, -34, -24, - -20, -112, 11, 101, -50, -34, 50, 65, -64, -106, 70, -48, 60, 9, -122, -45, 15, -112, -26, -4, - 1, 39, 23, 58, -45, -80, 127, 82, 58, 30, -94, -119, 51, -89, 95, -107, 30, 127, 125, 58, -52, - -42, -38, -20, -122, 115, 39, -26, 5, 73, 13, -39, 43, -23, -20, -125, 23, 35, 53, -61, -66, 72, - -20, 33, 8, 35, 4, 7, 18, 19, 16, -45, -50, -71, 31, -29, -41, -27, 10, 14, 27, 9, -23, 98, 6, - -94, 92, 127, -114, 59, -26, -100, -62, -127, -17, -85, -60, 126, -42, -6, 33, -120, -26, -126, - -127, -35, -114, -31, 25, -126, -100, -126, -64, -46, -31, 30, 25, -74, -111, -97, -81, -104, - -114, -19, -9, -116, -69, 22, 30, 59, 8, -51, 16, -97, 18, -4, -89, 80, -50, 3, 36, -67, 56, 69, - -26, 107, -10, 58, -28, -4, -57, -72, -111, 0, -75, -119, 14, -75, -49, -66, -49, 8, -121, 22, - -54, 121, 30, 54, -26, -126, -123, 56, 5, 48, 21, -127, -11, 23, 25, -82, 6, -25, 119, 78, 4, - -104, 27, 61, -48, 37, -13, -52, 50, -50, 44, -1, -22, -43, -59, -78, -67, -32, -26, 9, -3, 40, - 16, 19, 3, -9, 20, -6, -37, 28, 39, 17, -19, -10, 1, 6, -59, 74, 47, 3, -119, 0, -128, -107, - -25, -22, -69, -23, -111, -42, -93, -120, 90, -85, -54, -118, 76, -79, 124, 101, -77, -75, -17, - -71, -114, 68, 55, 79, -1, -123, -20, 127, -65, -123, -128, -87, 123, 9, -115, -14, 7, -4, 127, - -79, -115, 125, -28, 89, -83, 49, 89, 119, -69, -5, 12, -49, 60, 57, -24, -99, -110, 76, -83, - 125, 73, 81, 11, 8, -45, 1, 83, 13, -70, -2, 97, 112, -97, 53, -9, -94, 124, 44, -49, -24, 52, - 76, -110, -70, -114, -12, 72, -4, -114, 43, -43, 81, 102, -84, -27, 62, -40, 52, 58, 124, -35, - -51, -123, -43, 56, -75, -34, -35, -106, 93, -43, 14, -16, 46, 62, -97, 21, 30, -53, 21, -11, - -33, -20, -95, 4, -126, 12, 45, 20, 108, 85, 11, 20, -40, 99, 4, -25, -18, -23, -12, -126, -55, - -20, -44, -51, 91, -127, 127, -44, 7, 127, 78, 38, 125, -6, -94, -103, 73, 126, -126, 18, 59, - -46, 106, 76, 116, -31, 75, -4, 92, 102, 32, -31, 73, 42, -21, -28, 57, 127, -8, -107, 115, 124, - -94, -4, -128, 29, -57, 70, -82, 50, -13, -44, 38, 67, -93, 6, -39, -46, 56, 68, 27, 61, 26, 18, - -72, 127, 22, 18, -31, 127, 61, -65, -38, 1, -67, -1, 8, -73, 46, -116, -94, 58, -49, 71, -40, - -63, -82, -20, -60, 93, 76, 69, -106, 34, -31, 4, -25, 107, -18, 45, 4, -61, 126, 54, -126, - -125, 41, 19, 44, 32, -98, 125, -24, 125, -96, -125, 15, 87, -4, -90, 18, -40, 28, -69, 67, 22, - 41, 39, 7, -48, -44, 12, 69, -13, 2, 44, -38, 111, -7, -126, -22, -9, 74, -128, -36, -7, -123, - -15, -79, -91, -37, -127, -122, 104, 30, 7, 98, -37, 111, -116, -47, 127, -45, 118, -111, -123, - -120, -77, -64, -125, 124, 77, 111, 77, 18, -113, 117, -9, 67, -77, 126, 49, -20, -124, 39, 41, - -124, -34, 114, -87, -126, 98, -20, 59, -17, -24, 125, 107, 54, 35, 33, -44, 12, -29, 125, -71, - -28, -63, -114, 28, -17, 121, -36, 127, 89, -122, -49, -18, -48, 17, 24, 19, -64, -128, 13, 86, - 45, 13, -49, 55, 84, 48, 80, -39, 99, -127, 70, -33, 30, 50, 126, -65, -117, -13, -20, -24, 127, - 115, -72, -104, 63, 126, -42, 57, 17, 46, 21, 119, 110, -100, -60, -112, 62, -33, 28, 26, -22, - -60, -33, -54, 78, 25, 32, -114, 86, 44, 26, 43, 76, 121, 19, 97, -2, -3, -73, -68, 6, -116, 6, - -43, -97, 46, -128, -120, -31, -119, -29, 16, 16, -126, -128, -126, -46, -9, -3, 92, -31, -76, - -126, -3, -107, -12, -23, -69, 5, 51, 27, -42, 23, -70, -128, -29, 22, 29, -126, -55, 50, -71, - -3, 127, 44, -27, -70, -63, -66, -70, 104, 86, 115, 29, -92, 41, -90, 44, -11, -28, 20, -11, - -63, -16, 43, 31, 17, -73, -31, -1, -17, -11, -39, 56, 18, 124, 72, -14, 28, 69, -121, -125, 34, - 127, 63, 86, -80, -126, -125, -124, -47, 124, 77, 124, -19, 23, -7, -50, 96, -128, -93, 102, - -53, -36, -87, 119, -125, 92, -126, 118, 102, 72, -2, 125, 10, 97, 124, -125, 125, 71, -20, -47, - -116, -121, -4, -9, -32, 79, -124, -36, 33, -128, -74, 125, 23, 127, -29, -115, -32, 124, -89, - 32, -107, 43, -17, 24, 24, 18, 29, -13, -15, -36, 62, -91, 4, -41, 95, 28, -23, 6, 46, 84, 66, - 77, 68, -70, -1, -23, -6, 65, 70, -21, 9, 77, -12, 2, -118, 4, 9, -108, 84, 52, 2, 52, 13, -10, - 58, -110, 18, 66, -95, -23, 70, 31, -3, 56, 56, -3, -7, 1, -27, -48, -61, 41, -4, 10, -62, 32, - -7, -24, 9, -48, -60, -4, 79, -20, -38, -76, 68, -49, -97, 0, -15, 5, -100, -49, -95, -99, -115, - -9, -40, 10, 104, 13, 56, 127, -27, -109, -94, -118, -102, -44, -85, 52, 127, -4, 14, 62, 121, - -122, -26, -79, -42, -34, 1, 25, -38, -79, -58, -31, -31, -90, -30, -123, 32, -56, 125, 66, 124, - -1, 3, 91, -103, -7, 23, 78, -18, 9, 69, -69, 76, -38, -33, -2, -98, 18, 106, 84, 55, 87, -47, - 35, -124, 64, 41, -14, 46, 25, -2, 120, -21, 82, 19, -79, -37, -3, -8, -16, 21, 19, -5, -28, - -112, 39, -6, -30, 53, -69, 53, 46, 127, 123, 78, 20, 28, -7, 73, 72, 17, -40, 41, 111, 57, 32, - -95, 29, 28, -39, -65, 54, -20, -63, 29, -67, 3, 44, -57, -47, 11, 61, -22, -44, 61, 48, -100, - 20, 125, 96, -24, -16, 3, -69, -126, 74, -125, 9, 45, -67, -123, -59, -72, 118, 69, 45, 50, -57, - 67, 13, -66, -106, 47, 62, 22, -1, -22, -25, -40, -125, 3, 125, 32, 102, -56, -25, -75, -30, - 122, 60, -13, 36, -73, 7, -84, 124, 40, -118, 17, -87, -118, -8, 3, -27, 111, -40, 40, -51, 127, - 125, -45, -30, -54, 46, 80, -1, -30, 101, -17, 18, 26, 54, 7, -12, 1, -127, 123, -122, -27, -75, - 64, 10, 25, -15, -44, 127, -127, 5, -84, -81, -7, 19, -26, 126, 15, 116, -126, 14, -76, 44, 62, - -110, -124, 125, -29, -87, -3, -69, 82, 90, 57, -123, 123, 100, -19, -51, -32, 69, 37, -57, - -128, -124, -72, -13, 51, -7, -45, -73, 5, 99, -26, -117, -96, -109, 4, -31, -12, 0, 31, -42, - -27, 12, -81, 118, 39, 83, 14, 41, -126, 107, -82, 94, -116, -122, -47, -109, -84, -128, -35, - -56, 66, 8, -65, 19, 42, -46, -72, -109, 41, 43, -127, -113, 58, 127, 42, -75, -1, 65, 117, -55, - -113, -123, 124, 43, -96, -115, -19, 68, 15, 94, 3, 75, 0, 34, 9, 42, 110, -48, 92, -76, 99, - -17, 27, 32, 13, 125, 50, -17, 56, 4, 53, 34, -8, 99, 80, -126, -21, -65, -11, -46, 44, -81, -3, - -121, 123, 66, -81, -84, 119, 127, 84, 105, 45, -66, -42, -23, 32, -25, 12, 111, 127, 88, 125, - 30, 24, -127, -9, -54, 127, -116, -119, 88, 70, 94, -120, 35, -93, 15, 22, -21, 25, -110, -123, - -45, 8, -109, 125, -122, -86, -126, 8, -14, -120, -45, -45, 69, -125, -122, 6, 81, 86, 125, 95, - 54, 77, 54, -123, 126, -85, -117, 56, 11, 0, -61, -91, -12, -2, -113, -3, -15, -122, -63, -91, - 10, 84, -111, 125, 93, 21, 62, -78, -116, 13, -57, 28, -124, 126, 110, 12, 15, 95, 15, -19, - -125, -97, 52, -7, 101, 9, 20, -125, -26, -56, 72, 77, 12, -126, 22, -29, 47, 62, 95, 112, 69, - 32, 97, -83, -8, -5, 67, -63, -123, 79, 59, 0, -6, -17, 4, -111, -52, 27, 65, 0 - }; - - /** GRU1 recurrent weights, same layout (24 x 3 x 24). */ - static final byte[] HIDDEN_GRU_RECURRENT_WEIGHTS = { - 65, 83, 35, 56, 24, -34, -28, -2, 125, 19, 42, -9, 124, -53, 24, -87, 11, 35, -81, -35, -125, - -31, 123, -21, 33, -91, 113, -93, 45, -6, 53, 38, -92, 8, -27, 87, 4, 43, 43, 10, -128, -128, - -46, 127, -38, -45, 25, -87, 19, 5, 52, -96, -23, -29, 121, -126, -24, -20, -2, 69, -50, 6, 71, - -81, -125, 90, -94, 1, -38, 36, 89, 17, -60, 71, -48, 18, -15, 44, -18, 59, 11, 114, -51, 32, - 110, 1, 4, 109, -24, 127, 27, 60, 88, 24, 45, -59, 75, -36, 8, 57, -32, -25, 13, 126, -89, -61, - -76, 127, 18, -62, -68, 23, -113, 5, 126, 43, -88, 26, -78, 18, 75, 21, 9, -74, 20, 41, 126, - -118, -15, 9, 116, 126, -127, 34, -6, 126, -128, -53, -54, -55, -121, 70, 127, -12, -68, 82, - -25, 104, -126, 126, -21, -26, 124, -75, -127, -120, 13, 61, -64, -108, -63, -65, -44, -35, -61, - -39, 109, -74, 113, -3, 108, -30, 125, 120, 39, 125, -128, -95, -99, 111, 9, 25, 114, -75, -92, - -54, -12, -32, -38, 10, 31, 10, 63, 51, 40, -99, 74, 4, 50, -128, -36, -35, -11, -28, -126, -7, - 66, -58, -126, -22, -83, -61, -127, 49, 126, -8, 7, 62, 36, -11, -32, -44, 63, 116, 41, 65, - -127, 126, 63, -30, -96, 74, -92, 127, 38, -18, -128, 68, -5, 101, -4, 85, 58, 79, 0, -58, 8, - 119, -70, -1, -79, -68, 114, -28, -90, -6, -112, 2, 127, -8, 10, 55, -59, -126, 127, 125, 80, - 72, 35, -54, 95, -124, -124, 79, 23, -46, -61, -127, -100, 99, -77, 8, -87, 5, -2, 49, 85, 7, - -71, 82, 53, -41, 22, -22, -93, -103, 6, 52, -56, 14, -8, -111, 85, 16, 54, 32, -118, -24, 61, - -53, 96, -70, -5, -17, -67, -84, -7, -82, -107, -96, 21, -83, -58, 50, 12, -126, -1, -28, 34, - -126, 115, 17, 91, 1, -127, 72, 11, 126, -81, 6, 96, -8, 77, 15, -6, 63, -27, 20, -123, -109, - 85, -79, -17, 126, -92, 2, -61, 20, 14, 17, 121, 123, 30, 57, 120, 127, 57, 42, 117, 98, 67, 39, - -20, -70, 100, 7, 125, 122, 40, 16, -79, 125, 83, 41, -106, -57, 24, 55, 27, -66, -111, -44, -7, - -43, -66, 121, 42, -128, -45, 35, 15, -127, 34, -35, -34, -40, -18, -6, 63, 111, 31, 116, 127, - 19, 24, -71, -39, 34, 11, 19, -40, 27, 12, 106, -10, 56, -82, -106, -2, -50, -52, 114, -126, - -34, -43, -68, 10, 76, 57, -118, -128, 37, -104, 76, 125, 3, -76, 127, -29, 84, -94, -15, 55, - 125, 79, 127, -57, -125, 104, -68, 126, 126, -77, 51, 45, 33, -109, 115, -11, 1, 95, -121, -5, - -9, -126, -114, 39, 68, -126, -107, -51, -42, 24, -8, 51, -27, -43, 66, -45, 62, -98, -109, 69, - 67, 0, -125, -128, 49, 31, 126, -122, 2, -55, -67, -126, -70, -128, -125, -77, 25, 16, -8, -102, - 11, -75, 82, 38, -5, 5, 19, 34, 47, -127, -93, 21, 24, -97, -18, 31, 39, 34, -20, 22, 123, 7, - -77, -81, -46, -9, 1, 23, 39, -127, -43, -8, -50, 10, -21, 59, -9, -4, -13, -27, 44, 127, 52, - -47, 70, -43, 52, 101, -49, 27, 45, 49, 33, -125, 55, 114, 20, -1, 76, -24, -96, 105, 24, 126, - 75, -21, -105, 13, -42, 40, 126, -30, -39, -95, 125, -63, 11, 6, 125, 125, -14, 5, 42, -61, -4, - 49, 88, 6, -107, -28, 19, -29, 47, 126, 6, -46, -89, -18, 91, -20, -6, 118, -21, -22, 39, 115, - 11, -42, 54, 73, -55, -77, 62, -27, -59, -99, -12, -127, -40, 56, -3, -124, -91, 71, -111, 6, - -19, 82, -24, -35, 102, -42, 7, -126, -126, -125, 18, 98, -52, 127, 105, -52, 40, -83, 126, - -122, 109, 5, 127, 48, 6, 5, -125, 100, -16, 29, 85, -89, 8, 4, 41, 62, -127, 62, 122, 85, 122, - -107, 8, -125, 93, -127, 127, 102, 19, 19, -66, 41, -42, 114, 127, -48, -117, -29, -6, -73, - -102, -3, -19, 0, 88, 42, 87, -117, -20, 2, 122, 28, 63, 71, 66, 120, 93, 124, -43, 49, 103, 31, - 90, -91, -22, -126, 26, -24, -21, 51, -126, 87, -103, -69, -10, -66, -23, 20, 97, 36, 25, -127, - 30, -20, -63, 30, 51, -116, 23, 40, -39, 36, -83, -77, -25, -50, 110, 14, 13, -109, 125, -65, - -55, -87, 124, -126, -32, -72, -108, 127, 127, -125, -124, 61, 121, 102, -128, -127, 16, 100, - 127, -124, -68, 72, -93, -128, 43, -93, -19, -125, -97, -113, -33, 83, 127, -44, 127, -75, 127, - 16, 44, 50, -122, 23, 118, 46, 19, 26, -128, 10, 4, 99, -14, -82, -13, 30, 125, 57, 65, 60, -71, - 35, 98, 28, 7, 1, 43, 89, 70, 75, 121, -59, 82, -126, -53, -16, -116, -65, 52, -52, 0, 80, 35, - 45, -61, 46, 8, 107, 27, -26, -118, 90, 57, -10, 7, -15, 0, -39, -4, 12, 29, -1, 116, 84, 79, - 119, 125, -59, 28, -6, -25, -43, 2, 90, 79, 67, 103, -82, 2, -6, 125, 19, 73, 0, -105, 112, -17, - 104, 107, 124, 106, 19, 56, -44, 55, -112, 6, -39, -83, 126, -93, -98, 57, -120, -23, -38, 2, - -31, -48, 106, 127, 127, 69, 16, 110, 71, 104, 62, -12, -22, 42, -37, -94, 34, -1, -32, -12, - -124, -47, -13, 60, -75, -66, 58, -127, -2, 64, 76, -106, 73, -49, -31, 127, 126, 31, 16, 127, - -110, 107, -16, -53, 20, 69, -14, -125, 59, -44, 15, 120, 125, 125, 43, 6, 19, -58, 127, 127, - 43, 16, 82, 97, -127, 127, -93, -41, 88, 0, 77, -15, 116, 16, -124, -31, -3, 95, -40, -126, -54, - -126, -83, -8, -59, 6, 67, -29, 4, 124, -10, 112, -28, -8, 85, -21, 45, 84, 6, -8, 11, 72, 32, - 84, -62, 77, 2, -36, 75, 31, -50, 116, 126, 119, -88, -55, -14, -37, 126, 40, -108, -6, -6, 57, - 64, -28, -76, 30, -117, -93, 31, -92, -44, -64, 94, 58, 65, 114, 41, 47, 71, 42, -26, 99, -126, - 57, -5, 74, -19, -113, -1, 67, -21, 126, 1, -3, 33, 60, -82, 37, -48, 89, 114, -38, 127, -114, - 35, 58, -5, 21, -46, 121, -123, -43, 127, 115, 123, 122, -101, 126, 127, 81, 52, 89, -127, 102, - 42, 117, -9, -2, 125, 127, 110, 96, 120, 66, 70, 124, 55, 84, -38, -58, 119, -127, -16, -79, - 123, 18, -127, -50, -38, 120, -85, 1, 7, -56, 108, -77, -2, 21, 37, 1, 13, -105, -69, 28, -87, - 33, -104, -51, 126, 41, 3, -121, 28, 71, 58, 86, -8, 127, 94, -55, 125, 40, -19, 127, -33, -87, - -23, 7, -111, -68, 9, 84, -119, 55, -82, 78, -37, -20, -9, -23, 53, -13, 15, -46, 116, 126, - -127, 56, -126, 125, -7, -1, 45, 26, 125, 121, 29, 47, -86, 30, 10, 76, -125, -7, 23, 92, -12, - -39, -18, 92, -97, -8, -85, -41, 49, -50, 123, -37, -126, -30, 14, 79, -49, -65, 9, -36, -38, - -96, 85, -24, -13, 37, -25, -5, -64, -127, 55, -60, -18, -61, -63, 127, 56, 67, 15, 124, 72, - 120, 127, 40, -10, 114, 24, -23, 46, 78, -53, 125, 86, 124, 86, 0, 38, 93, 21, 127, 123, 75, - -72, 13, 48, 33, 83, -51, 15, -32, -49, -33, 120, 64, 7, 9, 65, 60, 21, -21, -61, -53, -113, 84, - -97, 101, 37, -114, -27, 41, 73, 126, -10, 59, 61, -15, 70, -13, 82, -4, 69, 56, 94, -91, -50, - 92, -74, -48, 53, -7, -107, 127, 28, 30, -26, -21, -61, 77, 82, 64, -91, -125, 122, -104, 127, - 123, 122, 123, 76, -126, 127, -6, -80, 7, 40, -66, -65, 54, -2, 23, 96, -64, 74, 2, -53, -12, - -123, 39, 60, -20, 16, -17, -97, 23, -4, -53, -122, 32, -16, -54, -95, 43, 71, -1, -67, -33, 41, - 18, 72, 28, -83, 31, -100, -91, -27, 10, -128, -106, 2, 76, -13, 42, 34, 112, -19, 44, 40, -9, - -11, 65, 92, -43, -125, 2, 47, -32, 25, 122, -29, 12, 101, -8, -126, -23, 43, 7, 125, -20, -124, - 82, -2, 13, -73, -106, 115, 31, 116, -23, -44, -71, 84, 3, 47, 91, 127, 127, -15, 95, 7, 93, 5, - 113, -50, 54, 11, 13, -127, 17, 72, 43, -23, 5, -70, 20, 15, -27, 99, 69, -109, -122, -94, 16, - 127, 0, 116, 104, 45, 108, -34, 87, 72, -14, 118, 46, 42, 109, -26, 95, 93, 127, 60, 127, -93, - -54, -122, 34, -105, 56, 55, 103, 125, -71, -50, 95, -72, 127, 107, 21, 73, 126, 61, 127, 127, - 24, -62, 90, 73, 90, -46, -78, -124, 72, 123, -42, 50, -107, 17, -32, -62, -89, 124, 1, 80, -2, - 117, 119, -65, -127, -95, -121, -52, 103, 66, 75, -3, -62, -127, 127, -74, 124, 79, 49, 40, 105, - -67, -71, -70, 43, 127, 119, -4, 66, 43, 23, 91, -126, 15, 63, -119, 112, 103, 15, -99, 31, - -127, 69, 116, -46, -67, 2, -126, -29, 30, 30, -69, -98, -47, -87, -70, -127, 23, -73, 30, -7, - 94, -52, -65, 98, -45, 97, 53, 23, -9, -22, -52, -47, 6, -1, -85, -15, -61, -14, 68, 110, -10, - -121, -25, -35, -15, -94, -123, 27, 75, 48, -66, -56, -44, 93, 109, 67, -36, 24, 70, -126, 8, - -127, 126, 52, 11, -32, 120, -13, -26, -28, -125, 127, 106, -50, 124, 36, -126, -12, 0, -23, 76, - -71, -126, -12, -17, -82, 12, 124, 57, 33, 4, 77, -46, 71, -34, 72, 125, -128, 124, -24, -128, - 75, -120, 69, -45, 55, 33, 127, -33, 4, -105, -41, -59, -91, 123, 44, -127, 127, -67, 52, 25, - -125, -65, 100, -25, 123, 6, 11, -123, -92, -33, 126, -17, -4, 29, 33, 127, 96, 3, 87, -48, -18, - -70, 123, 58, -127, -3, -52, -1, -36, -41, 127, 51, -52, -27, 46, -83, 57, 9, 126, 127, 94, 79, - -37, -127, -40, 67, 52, 82, -66, 122, -13, -73, 127, -8, -80, 46, -48, 4, -54 - }; - - /** GRU1 bias, [gate][output] (3 x 24). */ - static final byte[] HIDDEN_GRU_BIAS = { - 124, 125, -57, -126, 53, 123, 127, -75, 68, 102, -2, 116, 124, 127, 124, 125, 126, 123, -16, 48, - 125, 126, 78, 85, 11, 126, -30, -30, -64, -3, -105, -29, -17, 69, 63, 2, -32, -10, -62, 113, - -52, 112, -109, 112, 7, -40, 73, 53, 62, 6, -2, 0, 0, 100, -16, 26, -24, 56, 26, -10, -33, 41, - 70, 109, -29, 127, 34, -66, 49, 53, 27, 62 - }; - - /** FC2 weights (24 x 1). */ - static final byte[] OUTPUT_DENSE_WEIGHTS = { - 127, 127, 127, 127, 127, 20, 127, -126, -126, -54, 14, 125, -126, -126, 127, -125, -126, 127, - -127, -127, -57, -30, 127, 80 - }; - - /** FC2 bias (1). */ - static final byte[] OUTPUT_DENSE_BIAS = { - -50 - }; - - private RnnVadWeights() { - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/vad/SpectralFeatures.java b/ts3-client/core/src/main/java/com/ts3client/audio/vad/SpectralFeatures.java deleted file mode 100644 index 52a5013..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/vad/SpectralFeatures.java +++ /dev/null @@ -1,281 +0,0 @@ -package com.ts3client.audio.vad; - -import static com.ts3client.audio.vad.VadConstants.CEPSTRAL_HISTORY; -import static com.ts3client.audio.vad.VadConstants.FRAME_20MS_24K; -import static com.ts3client.audio.vad.VadConstants.NUM_BANDS; -import static com.ts3client.audio.vad.VadConstants.NUM_LOWER_BANDS; -import static com.ts3client.audio.vad.VadConstants.OPUS_BANDS_24K; - -/** - * Band-wise spectral features for {@code rnn_vad}, ported from WebRTC's - * {@code rnn_vad/spectral_features.cc} and {@code spectral_features_internal.cc}. - * - *

A 20 ms Vorbis-windowed FFT is folded into 22 Opus-scale bands, log-compressed - * and DCT'd into a cepstrum. The network is fed the higher cepstral coefficients, the - * running average and first two derivatives of the lower ones, the cepstrum of the - * band-wise correlation between the current frame and the frame one pitch period earlier, - * and a measure of how much the cepstrum has been varying. - */ -final class SpectralFeatures { - - /** Total band energy below which the frame is treated as silence. */ - private static final float SILENCE_THRESHOLD = 0.04f; - - /** FFT bins per Opus band at 24 kHz for a 20 ms frame. */ - private static final int[] OPUS_BAND_SIZES = - {4, 4, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8, 16, 16, 16, 24, 24, 32, 48}; - - /** sqrt(2 / NUM_BANDS), applied after the DCT. */ - private static final float DCT_SCALING_FACTOR = 0.301511345f; - - private final RealFft fft = new RealFft(FRAME_20MS_24K); - private final float[] halfWindow = new float[FRAME_20MS_24K / 2]; - private final float[] bandWeights = new float[FRAME_20MS_24K / 2]; - private final float[] dctTable = new float[NUM_BANDS * NUM_BANDS]; - - private final float[] windowed = new float[FRAME_20MS_24K]; - private final float[] referenceFft = new float[FRAME_20MS_24K]; - private final float[] laggedFft = new float[FRAME_20MS_24K]; - private final float[] referenceBandsEnergy = new float[OPUS_BANDS_24K]; - private final float[] laggedBandsEnergy = new float[OPUS_BANDS_24K]; - private final float[] bandsCrossCorr = new float[OPUS_BANDS_24K]; - private final float[] logBandsEnergy = new float[NUM_BANDS]; - private final float[] cepstrum = new float[NUM_BANDS]; - private final float[] crossCorrCepstrum = new float[NUM_LOWER_BANDS]; - - /** Ring buffer of the last {@link VadConstants#CEPSTRAL_HISTORY} cepstra. */ - private final float[][] cepstralHistory = new float[CEPSTRAL_HISTORY][NUM_BANDS]; - private int cepstralTail; - - /** - * Upper-right triangle of pairwise cepstral distances, stored as a square matrix so a - * new frame can be shifted in with a single array copy. - */ - private final float[] cepstralDiffs = new float[(CEPSTRAL_HISTORY - 1) * (CEPSTRAL_HISTORY - 1)]; - private final float[] newDistances = new float[CEPSTRAL_HISTORY - 1]; - - SpectralFeatures() { - int halfSize = FRAME_20MS_24K / 2; - float scaling = 1.0f / FRAME_20MS_24K; - for (int i = 0; i < halfSize; i++) { - double inner = Math.sin(0.5 * Math.PI * (i + 0.5) / halfSize); - halfWindow[i] = (float) (scaling * Math.sin(0.5 * Math.PI * inner * inner)); - } - // Each band overlaps its neighbour with a triangular response; the weight is the - // fractional position of the bin within its band. - int bin = 0; - for (int bandSize : OPUS_BAND_SIZES) { - for (int j = 0; j < bandSize; j++) { - bandWeights[bin++] = (float) j / bandSize; - } - } - double k = Math.sqrt(0.5); - for (int i = 0; i < NUM_BANDS; i++) { - for (int j = 0; j < NUM_BANDS; j++) { - dctTable[i * NUM_BANDS + j] = (float) Math.cos((i + 0.5) * j * Math.PI / NUM_BANDS); - } - dctTable[i * NUM_BANDS] *= (float) k; - } - } - - void reset() { - for (float[] row : cepstralHistory) { - java.util.Arrays.fill(row, 0.0f); - } - cepstralTail = 0; - java.util.Arrays.fill(cepstralDiffs, 0.0f); - } - - /** - * Writes the spectral part of the feature vector and returns {@code true} if the - * reference frame is silence, in which case the vector is only partially written. - * - * @param reference buffer holding the most recent 20 ms at 24 kHz - * @param referenceOffset offset of that frame within {@code reference} - * @param lagged buffer holding the 20 ms one pitch period earlier - * @param laggedOffset offset of that frame within {@code lagged} - */ - boolean checkSilenceComputeFeatures(float[] reference, int referenceOffset, - float[] lagged, int laggedOffset, - float[] featureVector) { - forwardFft(reference, referenceOffset, referenceFft); - crossCorrelation(referenceFft, referenceFft, referenceBandsEnergy); - - float totalEnergy = 0; - for (float e : referenceBandsEnergy) { - totalEnergy += e; - } - if (totalEnergy < SILENCE_THRESHOLD) { - return true; - } - - forwardFft(lagged, laggedOffset, laggedFft); - crossCorrelation(laggedFft, laggedFft, laggedBandsEnergy); - - smoothedLogMagnitudeSpectrum(referenceBandsEnergy, logBandsEnergy); - dct(logBandsEnergy, NUM_BANDS, cepstrum, NUM_BANDS); - // Ad-hoc correction terms for the first two cepstral coefficients. - cepstrum[0] -= 12.0f; - cepstrum[1] -= 4.0f; - - pushCepstrum(cepstrum); - - // Higher bands go in as-is; the lower ones are summarised over time instead. - System.arraycopy(cepstrum, NUM_LOWER_BANDS, featureVector, NUM_LOWER_BANDS, - NUM_BANDS - NUM_LOWER_BANDS); - computeAverageAndDerivatives(featureVector); - computeNormalizedCepstralCorrelation(featureVector); - featureVector[VadConstants.FEATURE_VECTOR_SIZE - 1] = computeVariability(); - return false; - } - - /** Windows a 20 ms frame and transforms it, zeroing the unused Nyquist coefficient. */ - private void forwardFft(float[] frame, int offset, float[] out) { - int halfSize = FRAME_20MS_24K / 2; - for (int i = 0, j = FRAME_20MS_24K - 1; i < halfSize; i++, j--) { - windowed[i] = frame[offset + i] * halfWindow[i]; - windowed[j] = frame[offset + j] * halfWindow[i]; - } - fft.forward(windowed, out); - out[1] = 0.0f; - } - - /** - * Folds the interleaved spectra into Opus bands. Each bin contributes to the band it - * sits in and to the next one, split by the triangular weight. - */ - private void crossCorrelation(float[] x, float[] y, float[] out) { - int k = 0; - out[0] = 0.0f; - for (int i = 0; i < OPUS_BANDS_24K - 1; i++) { - out[i + 1] = 0.0f; - for (int j = 0; j < OPUS_BAND_SIZES[i]; j++) { - float v = x[2 * k] * y[2 * k] + x[2 * k + 1] * y[2 * k + 1]; - float tmp = bandWeights[k] * v; - out[i] += v - tmp; - out[i + 1] += tmp; - k++; - } - } - out[0] *= 2.0f; // The first band only receives half a triangle. - } - - /** Log magnitude with smoothing over frequency and a decaying floor. */ - private static void smoothedLogMagnitudeSpectrum(float[] bandsEnergy, float[] out) { - final float logOneByHundred = -2.0f; - float logMax = logOneByHundred; - float follow = logOneByHundred; - for (int i = 0; i < out.length; i++) { - float x = (i < bandsEnergy.length) - ? (float) Math.log10(0.01f + bandsEnergy[i]) - : logOneByHundred; - x = Math.max(logMax - 7.0f, Math.max(follow - 1.5f, x)); - logMax = Math.max(logMax, x); - follow = Math.max(follow - 1.5f, x); - out[i] = x; - } - } - - /** DCT-II of the first {@code inSize} values of {@code in}, truncated to {@code outSize}. */ - private void dct(float[] in, int inSize, float[] out, int outSize) { - for (int i = 0; i < outSize; i++) { - float sum = 0; - for (int j = 0; j < inSize; j++) { - sum += in[j] * dctTable[j * NUM_BANDS + i]; - } - out[i] = sum * DCT_SCALING_FACTOR; - } - } - - private void pushCepstrum(float[] newCepstrum) { - // Distance from the new cepstrum to each older one, nearest first. - for (int i = 0; i < CEPSTRAL_HISTORY - 1; i++) { - float[] old = cepstralHistoryAt(i); - float sum = 0; - for (int k = 0; k < NUM_BANDS; k++) { - float c = newCepstrum[k] - old[k]; - sum += c * c; - } - newDistances[i] = sum; - } - System.arraycopy(newCepstrum, 0, cepstralHistory[cepstralTail], 0, NUM_BANDS); - cepstralTail = (cepstralTail + 1) % CEPSTRAL_HISTORY; - pushCepstralDistances(); - } - - /** Returns the cepstrum pushed {@code delay} frames ago (0 = most recent). */ - private float[] cepstralHistoryAt(int delay) { - int offset = cepstralTail - 1 - delay; - if (offset < 0) { - offset += CEPSTRAL_HISTORY; - } - return cepstralHistory[offset]; - } - - /** Shifts the distance matrix up-left by one and writes the new column. */ - private void pushCepstralDistances() { - final int s = CEPSTRAL_HISTORY; - System.arraycopy(cepstralDiffs, s, cepstralDiffs, 0, cepstralDiffs.length - s); - for (int i = 0; i < newDistances.length; i++) { - cepstralDiffs[(s - 1 - i) * (s - 1) - 1] = newDistances[i]; - } - } - - private float cepstralDistance(int delay1, int delay2) { - int row = CEPSTRAL_HISTORY - 1 - delay1; - int col = CEPSTRAL_HISTORY - 1 - delay2; - if (row > col) { // Only the upper-right triangle is stored. - int tmp = row; - row = col; - col = tmp; - } - return cepstralDiffs[row * (CEPSTRAL_HISTORY - 1) + (col - 1)]; - } - - private void computeAverageAndDerivatives(float[] featureVector) { - float[] curr = cepstralHistoryAt(0); - float[] prev1 = cepstralHistoryAt(1); - float[] prev2 = cepstralHistoryAt(2); - for (int i = 0; i < NUM_LOWER_BANDS; i++) { - featureVector[i] = curr[i] + prev1[i] + prev2[i]; // kernel [1, 1, 1] - featureVector[NUM_BANDS + i] = curr[i] - prev2[i]; // kernel [1, 0, -1] - featureVector[NUM_BANDS + NUM_LOWER_BANDS + i] = - curr[i] - 2 * prev1[i] + prev2[i]; // kernel [1, -2, 1] - } - } - - /** Band correlation between the current frame and the one a pitch period earlier. */ - private void computeNormalizedCepstralCorrelation(float[] featureVector) { - crossCorrelation(referenceFft, laggedFft, bandsCrossCorr); - for (int i = 0; i < bandsCrossCorr.length; i++) { - bandsCrossCorr[i] /= (float) Math.sqrt( - 0.001f + referenceBandsEnergy[i] * laggedBandsEnergy[i]); - } - dct(bandsCrossCorr, OPUS_BANDS_24K, crossCorrCepstrum, NUM_LOWER_BANDS); - // Ad-hoc correction terms, as for the frame cepstrum. - crossCorrCepstrum[0] -= 1.3f; - crossCorrCepstrum[1] -= 0.9f; - System.arraycopy(crossCorrCepstrum, 0, featureVector, - NUM_BANDS + 2 * NUM_LOWER_BANDS, NUM_LOWER_BANDS); - } - - /** - * How far the current cepstrum sits from its nearest neighbour in the recent history, - * averaged over the history. Steady tones score low, speech scores high. - */ - private float computeVariability() { - float variability = 0; - for (int delay1 = 0; delay1 < CEPSTRAL_HISTORY; delay1++) { - float minDist = Float.MAX_VALUE; - for (int delay2 = 0; delay2 < CEPSTRAL_HISTORY; delay2++) { - if (delay1 == delay2) { - continue; // The distance would be 0. - } - minDist = Math.min(minDist, cepstralDistance(delay1, delay2)); - } - variability += minDist; - } - // Normalised against training-set statistics. - return variability / CEPSTRAL_HISTORY - 2.1f; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/audio/vad/VadConstants.java b/ts3-client/core/src/main/java/com/ts3client/audio/vad/VadConstants.java deleted file mode 100644 index a59ac37..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/audio/vad/VadConstants.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.ts3client.audio.vad; - -/** - * Sizes and pitch-search bounds of WebRTC's {@code rnn_vad}, mirroring - * {@code modules/audio_processing/agc2/rnn_vad/common.h}. - * - *

The detector analyses 10 ms frames at 24 kHz. Spectral analysis uses the - * most recent 20 ms; pitch search additionally needs one maximum pitch period of - * history, hence the 864-sample buffer. - */ -final class VadConstants { - - static final int SAMPLE_RATE_24K = 24_000; - static final int FRAME_10MS_24K = SAMPLE_RATE_24K / 100; // 240 - static final int FRAME_20MS_24K = FRAME_10MS_24K * 2; // 480 - - /** Pitch range at 24 kHz: 0.00125 s to 0.016 s. */ - static final int MIN_PITCH_24K = SAMPLE_RATE_24K / 800; // 30 - static final int MAX_PITCH_24K = 384; // 24000 / 62.5 - static final int BUF_SIZE_24K = MAX_PITCH_24K + FRAME_20MS_24K; // 864 - - /** - * The coarse search skips very short periods; a refinement step recovers them, so the - * initial pass starts three minimum periods in. - */ - static final int INITIAL_MIN_PITCH_24K = 3 * MIN_PITCH_24K; // 90 - static final int INITIAL_NUM_LAGS_24K = MAX_PITCH_24K - INITIAL_MIN_PITCH_24K; // 294 - static final int REFINE_NUM_LAGS_24K = MAX_PITCH_24K + 1; // 385 - - // 12 kHz analysis, used for the coarse pitch search. - static final int FRAME_20MS_12K = 240; - static final int BUF_SIZE_12K = BUF_SIZE_24K / 2; // 432 - static final int INITIAL_MIN_PITCH_12K = INITIAL_MIN_PITCH_24K / 2; // 45 - static final int MAX_PITCH_12K = MAX_PITCH_24K / 2; // 192 - static final int NUM_LAGS_12K = MAX_PITCH_12K - INITIAL_MIN_PITCH_12K; // 147 - - // The pitch period fed to the network is expressed at 48 kHz. - static final int MIN_PITCH_48K = MIN_PITCH_24K * 2; // 60 - static final int MAX_PITCH_48K = MAX_PITCH_24K * 2; // 768 - - // Spectral features. - static final int NUM_BANDS = 22; - static final int NUM_LOWER_BANDS = 6; - static final int CEPSTRAL_HISTORY = 8; - /** Opus bands that fall below the 24 kHz Nyquist frequency. */ - static final int OPUS_BANDS_24K = 20; - - static final int NUM_LPC_COEFFICIENTS = 5; - - static final int FEATURE_VECTOR_SIZE = 42; - - private VadConstants() { - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/chatlog/ChatLogScope.java b/ts3-client/core/src/main/java/com/ts3client/chatlog/ChatLogScope.java deleted file mode 100644 index e1fd0ac..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/chatlog/ChatLogScope.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.ts3client.chatlog; - -public enum ChatLogScope { - SERVER, - CHANNEL, - PRIVATE -} diff --git a/ts3-client/core/src/main/java/com/ts3client/chatlog/ChatLogStore.java b/ts3-client/core/src/main/java/com/ts3client/chatlog/ChatLogStore.java deleted file mode 100644 index da7da14..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/chatlog/ChatLogStore.java +++ /dev/null @@ -1,321 +0,0 @@ -package com.ts3client.chatlog; - -import com.ts3client.config.AppDirs; -import com.ts3client.text.BBCode; -import com.ts3client.text.HtmlText; -import com.ts3client.text.TextQuery; -import com.ts3client.text.TsLink; - -import java.io.BufferedWriter; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.SeekableByteChannel; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardOpenOption; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Base64; -import java.util.Collections; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Reads and writes TeamSpeak-compatible chat logs. The file layout and HTML - * records match the native client closely enough for both clients to consume - * each other's logs. - */ -public final class ChatLogStore { - public static final int HISTORY_LIMIT = 1000; - /** - * How much of the end of a log history is read from: far more than {@link #HISTORY_LIMIT} - * entries take, without reading years of log on every connect. - */ - private static final int HISTORY_TAIL_BYTES = 4 << 20; - - private static final DateTimeFormatter BEGIN = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("HH:mm:ss"); - private static final String HTML_HEADER = - "
"; - private static final Pattern TEXT_MESSAGE = Pattern.compile("^<([0-9]{2}:[0-9]{2}:[0-9]{2})> ([^:]+): (.*)$"); - - private final Path serverDir; - - public ChatLogStore(String serverUniqueId) { - this(defaultRoot(), serverUniqueId); - } - - public ChatLogStore(Path root, String serverUniqueId) { - this.serverDir = root.resolve(encode(serverUniqueId == null || serverUniqueId.isBlank() - ? "unknown" : serverUniqueId)); - } - - public Path serverDir() { - return serverDir; - } - - public synchronized void begin() throws IOException { - LocalDateTime now = LocalDateTime.now(); - appendRaw(log(ChatLogScope.SERVER), "*** Log begins " + BEGIN.format(now), beginHtml("Log", now)); - appendRaw(log(ChatLogScope.CHANNEL), "*** Chat begins " + BEGIN.format(now), beginHtml("Chat", now)); - } - - public List serverHtmlHistory() throws IOException { - return last(readHtml(log(ChatLogScope.SERVER), HISTORY_TAIL_BYTES), HISTORY_LIMIT); - } - - public List channelHtmlHistory() throws IOException { - return last(readTextMessages(log(ChatLogScope.CHANNEL), ChatLogScope.CHANNEL, HISTORY_TAIL_BYTES), - HISTORY_LIMIT); - } - - public List privateHtmlHistory(String clientUniqueId) throws IOException { - return last(readTextMessages(privateLog(clientUniqueId), ChatLogScope.PRIVATE, HISTORY_TAIL_BYTES), - HISTORY_LIMIT); - } - - /** Entries of a whole log that match a query, in the order they were written. */ - public record SearchResult(List entries, int total) { - public boolean truncated() { - return total > entries.size(); - } - } - - /** - * Searches a whole log, not only the part {@link #HISTORY_LIMIT} loads into a chat. - * - * @param clientUniqueId the peer, for {@link ChatLogScope#PRIVATE}; ignored otherwise - * @param limit how many of the newest matches to return - */ - public SearchResult search(ChatLogScope scope, String clientUniqueId, TextQuery query, int limit) - throws IOException { - List all = scope == ChatLogScope.SERVER - ? readHtml(log(scope), Long.MAX_VALUE) - : readTextMessages(scope == ChatLogScope.PRIVATE ? privateLog(clientUniqueId) : log(scope), scope, - Long.MAX_VALUE); - List hits = new ArrayList<>(); - for (String entry : all) { - if (query.matches(HtmlText.plain(entry))) hits.add(entry); - } - return new SearchResult(last(hits, limit), hits.size()); - } - - /** Logs a message; a private one goes to the log of the client it came from. */ - public synchronized String appendMessage(ChatLogScope scope, boolean outgoing, int clientId, String uniqueId, - String nickname, String message) throws IOException { - LogFiles files = scope == ChatLogScope.PRIVATE ? privateLog(uniqueId) : log(scope); - return append(files, scope, outgoing, clientId, uniqueId, nickname, message); - } - - /** Logs a private message in the conversation with {@code peerUniqueId}, whoever wrote it. */ - public synchronized String appendPrivateMessage(String peerUniqueId, boolean outgoing, int clientId, - String uniqueId, String nickname, String message) - throws IOException { - return append(privateLog(peerUniqueId), ChatLogScope.PRIVATE, outgoing, clientId, uniqueId, nickname, - message); - } - - private String append(LogFiles files, ChatLogScope scope, boolean outgoing, int clientId, String uniqueId, - String nickname, String message) throws IOException { - LocalDateTime now = LocalDateTime.now(); - String text = "<" + TIME.format(now) + "> " + safe(nickname) + ": " + safe(message); - String html = messageHtml(scope, outgoing, now, clientId, uniqueId, nickname, message); - appendRaw(files, text, html); - return html; - } - - public synchronized String appendServerEvent(String message) throws IOException { - LocalDateTime now = LocalDateTime.now(); - String text = "<" + TIME.format(now) + "> " + safe(message); - String html = eventHtml(now, BBCode.linksToHtml(message)); - appendRaw(log(ChatLogScope.SERVER), text, html); - return html; - } - - public static Path defaultRoot() { - return AppDirs.chatLogs(); - } - - public static String decodePathComponent(String value) { - return new String(Base64.getDecoder().decode(value), StandardCharsets.UTF_8); - } - - private LogFiles log(ChatLogScope scope) { - return switch (scope) { - case SERVER -> new LogFiles(serverDir.resolve("server.txt"), serverDir.resolve("server.html")); - case CHANNEL -> new LogFiles(serverDir.resolve("channel.txt"), serverDir.resolve("channel.html")); - case PRIVATE -> throw new IllegalArgumentException("private log needs a client uid"); - }; - } - - private LogFiles privateLog(String clientUniqueId) { - return new LogFiles( - serverDir.resolve("clients").resolve(encode(safe(clientUniqueId)) + ".txt"), - serverDir.resolve("clients").resolve(encode(safe(clientUniqueId)) + ".html")); - } - - private void appendRaw(LogFiles files, String textLine, String htmlLine) throws IOException { - ensure(files); - try (BufferedWriter txt = Files.newBufferedWriter(files.txt, StandardCharsets.UTF_8, - StandardOpenOption.CREATE, StandardOpenOption.APPEND); - BufferedWriter html = Files.newBufferedWriter(files.html, StandardCharsets.UTF_8, - StandardOpenOption.CREATE, StandardOpenOption.APPEND)) { - txt.write(textLine); - txt.newLine(); - html.write(htmlLine); - html.newLine(); - } - } - - private static void ensure(LogFiles files) throws IOException { - Files.createDirectories(files.txt.getParent()); - Files.createDirectories(files.html.getParent()); - if (!Files.exists(files.html)) { - // Android < API 36.1 lacks Files.writeString; original: - // Files.writeString(files.html, HTML_HEADER + System.lineSeparator(), StandardCharsets.UTF_8, - // StandardOpenOption.CREATE, StandardOpenOption.APPEND); - Files.write(files.html, (HTML_HEADER + System.lineSeparator()).getBytes(StandardCharsets.UTF_8), - StandardOpenOption.CREATE, StandardOpenOption.APPEND); - } - if (!Files.exists(files.txt)) Files.createFile(files.txt); - } - - /** @param tailBytes how much of the end of the log to read */ - private static List readHtml(LogFiles files, long tailBytes) throws IOException { - if (!Files.isRegularFile(files.html)) return Collections.emptyList(); - List entries = new ArrayList<>(); - for (String line : readLines(files.html, tailBytes)) { - if (line.startsWith("

readTextMessages(LogFiles files, ChatLogScope scope, long tailBytes) - throws IOException { - if (!Files.isRegularFile(files.txt)) return Collections.emptyList(); - List entries = new ArrayList<>(); - Matcher message = null; - StringBuilder text = new StringBuilder(); - for (String line : readLines(files.txt, tailBytes)) { - Matcher m = TEXT_MESSAGE.matcher(line); - boolean begin = line.startsWith("*** "); - if (!m.matches() && !begin) { - if (message != null) text.append('\n').append(line); - continue; - } - if (message != null) entries.add(messageLineHtml(message, text, scope)); - message = null; - if (begin) { - entries.add(beginLineHtml(line)); - } else { - message = m; - text.setLength(0); - text.append(m.group(3)); - } - } - if (message != null) entries.add(messageLineHtml(message, text, scope)); - return entries; - } - - /** The lines in the last {@code tailBytes} of a file, less the one that was cut into. */ - private static List readLines(Path file, long tailBytes) throws IOException { - try (SeekableByteChannel channel = Files.newByteChannel(file)) { - long size = channel.size(); - if (size <= tailBytes) return Files.readAllLines(file, StandardCharsets.UTF_8); - ByteBuffer tail = ByteBuffer.allocate((int) tailBytes); - channel.position(size - tailBytes); - int read = 0; - while (tail.hasRemaining() && read >= 0) read = channel.read(tail); - String text = new String(tail.array(), 0, tail.position(), StandardCharsets.UTF_8); - List lines = new ArrayList<>(List.of(text.split("\r?\n", -1))); - lines.remove(0); - return lines; - } - } - - private static List last(List entries, int limit) { - if (entries.size() <= limit) return entries; - return new ArrayList<>(entries.subList(entries.size() - limit, entries.size())); - } - - private static String beginLineHtml(String line) { - return "

" - + BBCode.escape(line) + "
"; - } - - private static String messageLineHtml(Matcher m, CharSequence text, ChatLogScope scope) { - String target = switch (scope) { - case PRIVATE -> "Private"; - case CHANNEL -> "Channel"; - case SERVER -> "Server"; - }; - return "
" - + "<" + m.group(1) + "> " - + """ + BBCode.escape(m.group(2)) + "": " - + "" + BBCode.toHtml(text.toString().stripTrailing()) - + "
"; - } - - private static String beginHtml(String kind, LocalDateTime timestamp) { - return "

" + infoIcon() - + "*** " + kind + " begins " + BEGIN.format(timestamp) + "

"; - } - - private static String messageHtml(ChatLogScope scope, boolean outgoing, LocalDateTime timestamp, - int clientId, String uniqueId, String nickname, String message) { - String target = switch (scope) { - case PRIVATE -> "Private"; - case CHANNEL -> "Channel"; - case SERVER -> "Server"; - }; - return "

" - + (outgoing ? outgoingIcon() : incomingIcon()) - + "<" + TIME.format(timestamp) + "> " - + userLink(clientId, uniqueId, nickname) - + ": " + BBCode.toHtml(message) + "

"; - } - - private static String eventHtml(LocalDateTime timestamp, String html) { - return "

" + infoIcon() - + "<" + TIME.format(timestamp) + "> " - + "" + html + "

"; - } - - private static String userLink(int clientId, String uniqueId, String nickname) { - if (clientId <= 0) return """ + BBCode.escape(nickname) + """; - return """ - + BBCode.escape(nickname) + """; - } - - private static String infoIcon() { - return ""; - } - - private static String incomingIcon() { - return ""; - } - - private static String outgoingIcon() { - return ""; - } - - private static String encode(String value) { - return Base64.getEncoder().encodeToString(safe(value).getBytes(StandardCharsets.UTF_8)); - } - - private static String safe(String value) { - return value == null ? "" : value; - } - - private record LogFiles(Path txt, Path html) { - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/config/AppDirs.java b/ts3-client/core/src/main/java/com/ts3client/config/AppDirs.java deleted file mode 100644 index ca87ea9..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/config/AppDirs.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.ts3client.config; - -import java.io.File; -import java.nio.file.Path; -import java.nio.file.Paths; - -/** - * Where the client keeps its own state. On the desktop that is {@code ~/.ts3jclient}, with chat - * logs in the TeamSpeak 3 client's {@code ~/.ts3client/chats} so both clients share them. A - * platform without a meaningful home directory (Android) calls {@link #init} once at startup, - * before any store is loaded. - */ -public final class AppDirs { - - private static volatile File profile; - private static volatile Path chatLogs; - - private AppDirs() { - } - - public static void init(File profileDir, Path chatLogDir) { - profile = profileDir; - chatLogs = chatLogDir; - } - - /** The directory holding all persistent client state (settings, identities, caches). */ - public static File profile() { - File dir = profile; - if (dir == null) { - dir = new File(System.getProperty("user.home", "."), ".ts3jclient"); - profile = dir; - } - return dir; - } - - public static File file(String name) { - return new File(profile(), name); - } - - /** - * Creates the profile directory if it does not exist yet, readable by the user only; call - * before writing into it. - */ - public static void createProfile() { - File dir = profile(); - //noinspection ResultOfMethodCallIgnored - dir.mkdirs(); - ProfileFiles.makePrivate(dir); - } - - public static Path chatLogs() { - Path dir = chatLogs; - if (dir == null) { - // Android < API 34 lacks Path.of; original: - // dir = Path.of(System.getProperty("user.home", "."), ".ts3client", "chats"); - dir = Paths.get(System.getProperty("user.home", "."), ".ts3client", "chats"); - chatLogs = dir; - } - return dir; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/config/AwayMessages.java b/ts3-client/core/src/main/java/com/ts3client/config/AwayMessages.java deleted file mode 100644 index fd50b0d..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/config/AwayMessages.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.ts3client.config; - -import java.io.File; -import java.io.FileInputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -/** - * Persistent list of away-message presets, stored alongside the settings file. - * Frontend-agnostic: no UI dependencies. - */ -public final class AwayMessages { - - private static File file() { - return AppDirs.file("away.properties"); - } - - private final List entries = new ArrayList<>(); - - public List all() { - return entries; - } - - public void add(String message) { - entries.add(message == null ? "" : message); - } - - public void set(int index, String message) { - if (index >= 0 && index < entries.size()) entries.set(index, message == null ? "" : message); - } - - public void remove(int index) { - if (index >= 0 && index < entries.size()) entries.remove(index); - } - - public static AwayMessages load() { - AwayMessages m = new AwayMessages(); - if (!file().isFile()) return m.withDefaults(); - Properties p = new Properties(); - try (FileInputStream in = new FileInputStream(file())) { - p.load(in); - } catch (Exception e) { - return m.withDefaults(); - } - int count = parseInt(p.getProperty("count"), 0); - for (int i = 0; i < count; i++) { - String text = p.getProperty("message." + i); - if (text != null && !text.isBlank()) m.entries.add(text); - } - return m; - } - - public void save() { - Properties p = new Properties(); - p.setProperty("count", Integer.toString(entries.size())); - for (int i = 0; i < entries.size(); i++) { - p.setProperty("message." + i, entries.get(i)); - } - try { - AppDirs.createProfile(); - ProfileFiles.write(file(), out -> p.store(out, "TS3J client away messages")); - } catch (Exception ignored) { - } - } - - /** First run: seed the presets a fresh client offers. */ - private AwayMessages withDefaults() { - entries.add("Away from keyboard"); - entries.add("Be right back"); - entries.add("Lunch"); - entries.add("Busy"); - return this; - } - - private static int parseInt(String v, int def) { - if (v == null) return def; - try { - return Integer.parseInt(v.trim()); - } catch (NumberFormatException e) { - return def; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/config/BanReasonPresets.java b/ts3-client/core/src/main/java/com/ts3client/config/BanReasonPresets.java deleted file mode 100644 index d67b6e7..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/config/BanReasonPresets.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.ts3client.config; - -import java.io.File; -import java.io.FileInputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Properties; - -/** - * The reasons the ban dialogs offer as presets, stored alongside the settings file. - * Frontend-agnostic: no UI dependencies. - */ -public final class BanReasonPresets { - - private static File file() { - return AppDirs.file("banreasons.properties"); - } - - private final List entries = new ArrayList<>(); - - public List all() { - return Collections.unmodifiableList(entries); - } - - /** Remembers a reason, moving it to the front if it is already known. */ - public void add(String reason) { - if (reason == null || reason.isBlank()) return; - entries.remove(reason.trim()); - entries.add(0, reason.trim()); - } - - public void remove(String reason) { - entries.remove(reason); - } - - public static BanReasonPresets load() { - BanReasonPresets presets = new BanReasonPresets(); - if (!file().isFile()) return presets; - Properties p = new Properties(); - try (FileInputStream in = new FileInputStream(file())) { - p.load(in); - } catch (Exception e) { - return presets; - } - int count = parseInt(p.getProperty("count"), 0); - for (int i = 0; i < count; i++) { - String text = p.getProperty("reason." + i); - if (text != null && !text.isBlank()) presets.entries.add(text); - } - return presets; - } - - public void save() { - Properties p = new Properties(); - p.setProperty("count", Integer.toString(entries.size())); - for (int i = 0; i < entries.size(); i++) { - p.setProperty("reason." + i, entries.get(i)); - } - try { - AppDirs.createProfile(); - ProfileFiles.write(file(), out -> p.store(out, "TS3J client ban reason presets")); - } catch (Exception ignored) { - } - } - - private static int parseInt(String v, int def) { - if (v == null) return def; - try { - return Integer.parseInt(v.trim()); - } catch (NumberFormatException e) { - return def; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/config/Bookmark.java b/ts3-client/core/src/main/java/com/ts3client/config/Bookmark.java deleted file mode 100644 index 8fe8a75..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/config/Bookmark.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.ts3client.config; - -import java.util.UUID; - -/** A saved server for quick connect. */ -public final class Bookmark { - /** Stays the same through edits, for whatever refers to the bookmark from outside, like a launcher shortcut. */ - public String id = UUID.randomUUID().toString(); - public String label; - public String address; - public int port = 9987; - public String nickname; - public String password = ""; - /** Identity to connect with; empty means "use the default identity". */ - public String identityId = ""; - /** - * Channel to join on connect, as a "/"-separated path ("Lobby/Games") or - * "/<channelId>". Empty means the server's default channel. - */ - public String channel = ""; - /** Password for {@link #channel}, if it is protected. */ - public String channelPassword = ""; - /** Connect to this server automatically when the client starts. */ - public boolean connectOnStartup = false; - /** The server's icon as last seen there, 0 for none or not yet known. */ - public long iconId = 0; - - public Bookmark() { - } - - public Bookmark(String label, String address, int port, String nickname, String password) { - this.label = label; - this.address = address; - this.port = port; - this.nickname = nickname; - this.password = password == null ? "" : password; - } - - /** A bookmark of its own with the same fields, to change without touching this one. */ - public Bookmark copy() { - Bookmark b = new Bookmark(label, address, port, nickname, password); - b.id = id; - b.identityId = identityId; - b.channel = channel; - b.channelPassword = channelPassword; - b.connectOnStartup = connectOnStartup; - b.iconId = iconId; - return b; - } - - /** Whether this bookmark leads to the server at {@code address}:{@code port}. */ - public boolean pointsAt(String address, int port) { - return this.port == port && this.address != null && this.address.trim().equalsIgnoreCase(address.trim()); - } - - /** Display name, falling back to "address:port" when no label is set. */ - public String displayName() { - if (label != null && !label.isBlank()) return label; - return address + ":" + port; - } - - @Override - public String toString() { - return displayName(); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/config/Bookmarks.java b/ts3-client/core/src/main/java/com/ts3client/config/Bookmarks.java deleted file mode 100644 index 0bc7d20..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/config/Bookmarks.java +++ /dev/null @@ -1,143 +0,0 @@ -package com.ts3client.config; - -import java.io.File; -import java.io.FileInputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -/** - * Persistent list of {@link Bookmark}s, stored alongside the settings file. - * Frontend-agnostic: no UI dependencies. - */ -public final class Bookmarks { - - private static File file() { - return AppDirs.file("bookmarks.properties"); - } - - private final List entries = new ArrayList<>(); - - public List all() { - return entries; - } - - public void add(Bookmark b) { - entries.add(b); - } - - public void remove(int index) { - if (index >= 0 && index < entries.size()) entries.remove(index); - } - - /** - * Takes on the icon a server shows now for every bookmark leading to it. - * - * @return whether any bookmark changed, and so needs saving and redrawing - */ - public boolean rememberServerIcon(String address, int port, long iconId) { - if (address == null || address.isBlank()) return false; - boolean changed = false; - for (Bookmark b : entries) { - if (b.pointsAt(address, port) && b.iconId != iconId) { - b.iconId = iconId; - changed = true; - } - } - return changed; - } - - /** The bookmark with this {@link Bookmark#id}, or null. */ - public Bookmark find(String id) { - for (Bookmark b : entries) { - if (b.id.equals(id)) return b; - } - return null; - } - - /** Bookmarks flagged to connect at startup, each in its own tab. */ - public List startupBookmarks() { - List out = new ArrayList<>(); - for (Bookmark b : entries) { - if (b.connectOnStartup) out.add(b); - } - return out; - } - - public static Bookmarks load() { - Bookmarks b = new Bookmarks(); - if (!file().isFile()) return b; - Properties p = new Properties(); - try (FileInputStream in = new FileInputStream(file())) { - p.load(in); - } catch (Exception e) { - return b; - } - int count = parseInt(p.getProperty("count"), 0); - for (int i = 0; i < count; i++) { - String prefix = "bookmark." + i + "."; - Bookmark bm = new Bookmark(); - String id = p.getProperty(prefix + "id", ""); - if (!id.isBlank()) bm.id = id; - bm.label = p.getProperty(prefix + "label", ""); - bm.address = p.getProperty(prefix + "address", ""); - bm.port = parseInt(p.getProperty(prefix + "port"), 9987); - bm.nickname = p.getProperty(prefix + "nickname", ""); - bm.password = p.getProperty(prefix + "password", ""); - bm.identityId = p.getProperty(prefix + "identityId", ""); - bm.channel = p.getProperty(prefix + "channel", ""); - bm.channelPassword = p.getProperty(prefix + "channelPassword", ""); - bm.connectOnStartup = Boolean.parseBoolean(p.getProperty(prefix + "connectOnStartup", "false")); - bm.iconId = parseLong(p.getProperty(prefix + "iconId")); - if (bm.address != null && !bm.address.isBlank()) b.entries.add(bm); - } - return b; - } - - public void save() { - Properties p = new Properties(); - p.setProperty("count", Integer.toString(entries.size())); - for (int i = 0; i < entries.size(); i++) { - Bookmark bm = entries.get(i); - String prefix = "bookmark." + i + "."; - p.setProperty(prefix + "id", bm.id); - p.setProperty(prefix + "label", nullToEmpty(bm.label)); - p.setProperty(prefix + "address", nullToEmpty(bm.address)); - p.setProperty(prefix + "port", Integer.toString(bm.port)); - p.setProperty(prefix + "nickname", nullToEmpty(bm.nickname)); - p.setProperty(prefix + "password", nullToEmpty(bm.password)); - p.setProperty(prefix + "identityId", nullToEmpty(bm.identityId)); - p.setProperty(prefix + "channel", nullToEmpty(bm.channel)); - p.setProperty(prefix + "channelPassword", nullToEmpty(bm.channelPassword)); - p.setProperty(prefix + "connectOnStartup", Boolean.toString(bm.connectOnStartup)); - p.setProperty(prefix + "iconId", Long.toString(bm.iconId)); - } - try { - AppDirs.createProfile(); - ProfileFiles.write(file(), out -> p.store(out, "TS3J client bookmarks")); - } catch (Exception ignored) { - } - } - - private static int parseInt(String v, int def) { - if (v == null) return def; - try { - return Integer.parseInt(v.trim()); - } catch (NumberFormatException e) { - return def; - } - } - - private static long parseLong(String v) { - if (v == null) return 0; - try { - return Long.parseLong(v.trim()); - } catch (NumberFormatException e) { - return 0; - } - } - - private static String nullToEmpty(String s) { - return s == null ? "" : s; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/config/ClientRowColors.java b/ts3-client/core/src/main/java/com/ts3client/config/ClientRowColors.java deleted file mode 100644 index 1f68e43..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/config/ClientRowColors.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.ts3client.config; - -import com.ts3client.net.ClientStatus; - -import java.util.List; -import java.util.Properties; - -/** - * Background colours of client rows in the channel tree: one for every client, overridden - * by one while they talk and one while they are muted or away. Colours are ARGB; 0 is none. - */ -public final class ClientRowColors { - - public record Preset(String name, int argb) { - } - - /** See-through, so they tint the light and dark themes alike and the names stay readable. */ - public static final List PRESETS = List.of( - new Preset("Green", 0x594CAF50), - new Preset("Teal", 0x5926A69A), - new Preset("Blue", 0x5942A5F5), - new Preset("Purple", 0x59AB47BC), - new Preset("Pink", 0x59EC407A), - new Preset("Red", 0x59EF5350), - new Preset("Orange", 0x59FFA726), - new Preset("Yellow", 0x59FFEE58), - new Preset("Grey", 0x599E9E9E)); - - private static final String PREFIX = "clientRowColor."; - - public int any; - public int talking; - public int mutedAway; - - /** The colour of a row showing {@code status}; 0 for none. */ - public int of(ClientStatus status) { - int own = switch (status) { - case TALKING, COMMANDER_TALKING -> talking; - case SPEAKERS_DISABLED, SPEAKERS_MUTED, MIC_DISABLED, MIC_MUTED, AWAY -> mutedAway; - default -> 0; - }; - return own != 0 ? own : any; - } - - /** The preset named for {@code argb}, or {@code null} for a custom colour or none. */ - public static Preset presetOf(int argb) { - for (Preset p : PRESETS) { - if (p.argb() == argb) return p; - } - return null; - } - - void load(Properties p) { - any = parse(p.getProperty(PREFIX + "any")); - talking = parse(p.getProperty(PREFIX + "talking")); - mutedAway = parse(p.getProperty(PREFIX + "mutedAway")); - } - - void store(Properties p) { - p.setProperty(PREFIX + "any", format(any)); - p.setProperty(PREFIX + "talking", format(talking)); - p.setProperty(PREFIX + "mutedAway", format(mutedAway)); - } - - private static int parse(String v) { - if (v == null || v.isBlank()) return 0; - try { - return (int) Long.parseLong(v.trim().replace("#", ""), 16); - } catch (NumberFormatException e) { - return 0; - } - } - - private static String format(int argb) { - return argb == 0 ? "" : String.format("#%08X", argb); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/config/ClientVersion.java b/ts3-client/core/src/main/java/com/ts3client/config/ClientVersion.java deleted file mode 100644 index f8428b3..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/config/ClientVersion.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.ts3client.config; - -import java.util.List; - -/** - * The version, platform and signature a client reports to the server in - * {@code clientinit}. Other clients see the version and platform in the info - * panel ("3.6.2 on Windows"). - * - *

The signature is TeamSpeak's, over the version and platform strings - * together, so the three only work as a set. Servers answer "client is modified" - * for a version they do not accept — an invented one, or one older than their - * configured minimum — which is why {@link #PRESETS} holds genuine triples taken - * from released clients, newest first per platform. - * - * @param label human-readable name, e.g. "3.6.2 on Windows" - * @param version {@code client_version}, e.g. "3.6.2 [Build: 1695203293]" - * @param platform {@code client_platform}, e.g. "Windows" - * @param sign {@code client_version_sign}, base64 - */ -public record ClientVersion(String label, String version, String platform, String sign) { - - /** Platform names the official clients report. */ - public static final List PLATFORMS = - List.of("Windows", "Linux", "OS X", "Android", "iOS"); - - /** - * Signed triples from released TeamSpeak clients. "3.?.?" is the version the - * SDK-based clients report; it is signed for every platform and is what this - * client uses by default. - */ - public static final List PRESETS = List.of( - new ClientVersion("3.?.? on Windows", "3.?.? [Build: 5680278000]", "Windows", - "DX5NIYLvfJEUjuIbCidnoeozxIDRRkpq3I9vVMBmE9L2qnekOoBzSenkzsg2lC9CMv8K5hkEzhr2TYUYSwUXCg=="), - new ClientVersion("3.6.3 on Windows", "3.6.3 [Build: 1701166057]", "Windows", - "ML3yE6pV0QGyhc8o7k1bgqDSj+5gZIQFMjBNhWJ6L0FtJwniBq8l1wivx3DzgVVCvyRbzfg8MsdV/rjl5sHNCw=="), - new ClientVersion("3.6.2 on Windows", "3.6.2 [Build: 1695203293]", "Windows", - "4BdaZpdgUSMCuIs8qcloJPNxNlJ4o7QKnxMCRO60mSOTtJZyKjOrGLAmeAEtLIJjcjmdSpycMbQOIV92K2vXAw=="), - new ClientVersion("3.6.1 on Windows", "3.6.1 [Build: 1690872913]", "Windows", - "+YmPaYUBL4F9+TgxyFhlT8qIi1Ym+So4NNMcuohla/u4kfJCGabZ1vDF4cIOAghIqWfO+bQ0OkORZrCBdpi2Cw=="), - new ClientVersion("3.6.0 on Windows", "3.6.0 [Build: 1686749764]", "Windows", - "gfzG6CfwNYeqrjT68s7ahPd24A/XS0P8LLAB7hrE54MnrlO12RiflD2w69VZ7EYlqnd9GAiVzdGJHCmCFWtlAQ=="), - - new ClientVersion("3.?.? on Linux", "3.?.? [Build: 5680278000]", "Linux", - "Hjd+N58Gv3ENhoKmGYy2bNRBsNNgm5kpiaQWxOj5HN2DXttG6REjymSwJtpJ8muC2gSwRuZi0R+8Laan5ts5CQ=="), - new ClientVersion("3.6.2 on Linux", "3.6.2 [Build: 1695203293]", "Linux", - "p4iF1jZ3ZOz9MEkKSZ2bvnFtm9WmUcQy9mAP//erFE4PF1sB6K1CSANrr+3X4B0aZR0u+K2pjnv8kiKsWKQCBQ=="), - new ClientVersion("3.6.1 on Linux", "3.6.1 [Build: 1690193193]", "Linux", - "UAcE5h5FgPcdChWTtiO816HX8f2qdoDcDEw6crbJ96Yo7rp1Bt+qx/rkKK9bzlVWMhOd4fI7pr++1XaPkEBnAQ=="), - new ClientVersion("3.6.0 on Linux", "3.6.0 [Build: 1686749764]", "Linux", - "TccRBHwn5LSA0lfpa2B42QmfCOiG+MqqyhlOqy5RcuRQNUGPD0e47lUz+Z/8+Gsdc1TPG4+vYlRl8+v2v+26Aw=="), - new ClientVersion("3.5.8 on Linux", "3.5.8 [Build: 1644595825]", "Linux", - "CK+cWJQESZgUdw1AFHINMbwiLjFGSiupour0Dfj/j1/xwx4L3nW3G+alYtiQw/wQwlWm873HS6PvXUBarz/tCw=="), - - new ClientVersion("3.?.? on OS X", "3.?.? [Build: 5680278000]", "OS X", - "SttEnjoWE8jqIM6BOHSfiZP9DGjW0EP/ajU4bdKqgGMV4aYq/kzwVA9gxbmdIzV4lbaokvXBqrRjfBHrTVh8Cg=="), - new ClientVersion("3.6.2 on OS X", "3.6.2 [Build: 1695203293]", "OS X", - "SOCkLcsxINIGVc+3OQ5Vrmv2BVNNFA9LX5Jj9tqbIiYv2HU6Z5E8AL5+v5G2LDN0F+U55+uW43ezUoYAr1WuBA=="), - new ClientVersion("3.6.1 on OS X", "3.6.1 [Build: 1690193193]", "OS X", - "P+KOw42V8K0nN5FbGItCaJzrDuWcRgfE3MRzrtbYAhRMTXHzRxvwLkoLM7+vKTW135NtWZlKbZuDAvxgwhSLBg=="), - new ClientVersion("3.6.0 on OS X", "3.6.0 [Build: 1686749764]", "OS X", - "g8H7Op8eCrn0wHutuD/SlmUcZPmkSlFUBhvZpSgm9kuQl4dapzKJq2anI5jDwRs/ooBm/wrIlSiWI6HXuOPZDA=="), - - new ClientVersion("3.?.? on Android", "3.?.? [Build: 5680278000]", "Android", - "AWb948BY32Z7bpIyoAlQguSmxOGcmjESPceQe1DpW5IZ4+AW1KfTk2VUIYNfUPsxReDJMCtlhVKslzhR2lf0AA=="), - new ClientVersion("3.8.7 on Android", "3.8.7 [Build: 1785186501]", "Android", - "mbt0WPhXJ+YKJUix5b6t+ZOHTCfvRqhhhrpcS5koM9CUL0BAFQZRG5Di5rJrqipZdk+gEUtpAX9I5nkuL7V9Dw=="), - new ClientVersion("3.8.6 on Android", "3.8.6 [Build: 1774892004]", "Android", - "Hh0oEZupsq8f0BuUHhMKdkXsMmgZZ03dJL8qAwnlH2JAHuefaAZFS/buiH2MLwgdRkZ81ffYk5YOTfc/bJczDw=="), - - new ClientVersion("3.?.? on iOS", "3.?.? [Build: 5680278000]", "iOS", - "XrAf+Buq6Eb0ehEW/niFp06YX+nGGOS0Ke4MoUBzn+cX9q6G5C0A/d5XtgcNMe8r9jJgV/adIYVpsGS3pVlSAA=="), - new ClientVersion("3.8.2 on iOS", "3.8.2 [Build: 1764028963]", "iOS", - "Bc57xjumaioWkouTRqoS6XbSIXysrPH+gxynXgL4/nYr38l4OocUTpQaMMHevmgk/FZxJWFNEhU3Hpg5+M+MAA=="), - new ClientVersion("3.8.1 on iOS", "3.8.1 [Build: 1763403218]", "iOS", - "GM/7isPK6LDKTN3Hdelenbr99dnPyWTccLCOCFKK41321XMsdG02putu+NskCLddlDPu2CPYJ4YABRS2pJ88Ag==")); - - /** The triple used when the user has not chosen one; matches the library's built-in. */ - public static final ClientVersion DEFAULT = PRESETS.get(0); - - /** The preset carrying exactly these three values, or null when the user typed their own. */ - public static ClientVersion match(String version, String platform, String sign) { - return PRESETS.stream() - .filter(v -> v.version.equals(version) && v.platform.equals(platform) && v.sign.equals(sign)) - .findFirst() - .orElse(null); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/config/IdentityEntry.java b/ts3-client/core/src/main/java/com/ts3client/config/IdentityEntry.java deleted file mode 100644 index e4b34d7..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/config/IdentityEntry.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.ts3client.config; - -import com.github.manevolent.ts3j.identity.LocalIdentity; - -import java.io.File; - -/** - * One managed identity: a TS3 key pair plus the user-visible name it is filed - * under. Backed by a TeamSpeak-compatible identity INI file on disk. - */ -public final class IdentityEntry { - - private final String id; - private final File file; - private final LocalIdentity identity; - private String name; - private String nickname = ""; - private String phoneticNickname = ""; - - IdentityEntry(String id, String name, File file, LocalIdentity identity) { - this.id = id; - this.name = name; - this.file = file; - this.identity = identity; - } - - /** Stable key used to reference this identity from settings and bookmarks. */ - public String getId() { - return id; - } - - public String getName() { - return name; - } - - void setName(String name) { - this.name = name; - } - - /** Nickname to connect with, unless a bookmark names its own; empty for the global one. */ - public String getNickname() { - return nickname; - } - - public String getPhoneticNickname() { - return phoneticNickname; - } - - void setNicknames(String nickname, String phoneticNickname) { - this.nickname = nickname == null ? "" : nickname.trim(); - this.phoneticNickname = phoneticNickname == null ? "" : phoneticNickname.trim(); - } - - public File getFile() { - return file; - } - - public LocalIdentity getIdentity() { - return identity; - } - - /** The TeamSpeak unique ID (base64 SHA-1 of the public key). */ - public String getUniqueId() { - return identity.getUid().toBase64(); - } - - /** Current security level ("hash cash" leading-zero bits) of the identity. */ - public int getSecurityLevel() { - return identity.getSecurityLevel(); - } - - @Override - public String toString() { - return name; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/config/IdentityStore.java b/ts3-client/core/src/main/java/com/ts3client/config/IdentityStore.java deleted file mode 100644 index 921c0d9..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/config/IdentityStore.java +++ /dev/null @@ -1,385 +0,0 @@ -package com.ts3client.config; - -import com.github.manevolent.ts3j.identity.LocalIdentity; -import org.ini4j.Ini; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -/** - * Manages the user's TeamSpeak identities, mirroring the official client: - * several identities may coexist, one is the default, and any of them can be - * imported from or exported to a TS3 identity INI file. - * - *

Each identity lives in its own {@code ~/.ts3jclient/identities/<id>.ini} - * file in TeamSpeak's own format, so files can be exchanged with the official - * client verbatim. The display name is kept in the INI's {@code id} key, again - * as TeamSpeak does. - * - *

Safe to share between threads: a connection resolves its identity on its own thread - * while the UI may be managing them. - */ -public final class IdentityStore { - - /** Security level new identities are generated with, matching the TS3 client's default. */ - public static final int DEFAULT_SECURITY_LEVEL = 8; - - /** Keys TeamSpeak keeps next to the key in an identity INI. */ - private static final String KEY_NAME = "id"; - private static final String KEY_NICKNAME = "nickname"; - private static final String KEY_PHONETIC_NICKNAME = "phonetic_nickname"; - - - private final List entries = new ArrayList<>(); - - /** - * Reports progress while improving an identity's security level. - * Returning {@code false} aborts the search, keeping the best result so far. - */ - public interface ImproveProgress { - boolean onProgress(int level, long offset); - } - - private IdentityStore() { - } - - /** Loads all identities from disk, migrating a legacy single-identity file if needed. */ - public static IdentityStore load(Settings settings) { - IdentityStore store = new IdentityStore(); - File[] files = directory().listFiles((d, n) -> n.toLowerCase(Locale.ROOT).endsWith(".ini")); - if (files != null) { - for (File f : files) { - IdentityEntry e = read(f); - if (e != null) store.entries.add(e); - } - } - if (store.entries.isEmpty()) store.migrateLegacy(settings); - store.sort(); - return store; - } - - /** Adopts the pre-multi-identity {@code identity.ini} as the first managed identity. */ - private void migrateLegacy(Settings settings) { - File legacy = settings.identityFile(); - if (legacy == null || !legacy.isFile()) return; - try { - LocalIdentity identity = LocalIdentity.read(legacy); - create("Default", identity); - } catch (Exception ignored) { - // Unreadable legacy identity: start fresh instead. - } - } - - /** A snapshot of the identities, sorted by name. */ - public synchronized List all() { - return new ArrayList<>(entries); - } - - public synchronized boolean isEmpty() { - return entries.isEmpty(); - } - - public synchronized IdentityEntry byId(String id) { - if (id == null || id.isBlank()) return null; - for (IdentityEntry e : entries) { - if (e.getId().equals(id)) return e; - } - return null; - } - - /** The identity with this TeamSpeak unique ID, or {@code null}. */ - public synchronized IdentityEntry byUniqueId(String uniqueId) { - if (uniqueId == null || uniqueId.isBlank()) return null; - for (IdentityEntry e : entries) { - if (e.getUniqueId().equals(uniqueId)) return e; - } - return null; - } - - /** - * Resolves the identity to connect with: the requested one, else the configured - * default, else the first available — generating one when the store is empty. - */ - public synchronized IdentityEntry resolve(Settings settings, String preferredId) throws Exception { - IdentityEntry e = byId(preferredId); - if (e != null) return e; - - e = byId(settings.defaultIdentityId); - if (e == null) { - e = entries.isEmpty() ? generate("Default", DEFAULT_SECURITY_LEVEL) : entries.get(0); - settings.defaultIdentityId = e.getId(); - settings.save(); - } - return e; - } - - /** Generates a brand-new identity. Blocking: key improvement takes time. */ - public IdentityEntry generate(String name, int securityLevel) throws Exception { - return create(name, LocalIdentity.generateNew(securityLevel)); - } - - /** Imports a TeamSpeak identity INI file, keeping its own name unless one is given. */ - public IdentityEntry importFile(File source, String name) throws IOException { - try (InputStream in = new FileInputStream(source)) { - return importStream(in, name, stripExtension(source.getName())); - } - } - - /** Imports a TeamSpeak identity INI from a stream, keeping its own name unless one is given. */ - public IdentityEntry importStream(InputStream in, String name) throws IOException { - return importStream(in, name, "Imported identity"); - } - - private IdentityEntry importStream(InputStream in, String name, String fallbackName) throws IOException { - byte[] ini = in.readAllBytes(); - LocalIdentity identity = LocalIdentity.read(new ByteArrayInputStream(ini)); - Map props = readProperties(new ByteArrayInputStream(ini)); - String label = (name == null || name.isBlank()) ? props.getOrDefault(KEY_NAME, "") : name; - return create(label.isBlank() ? fallbackName : label, identity, - props.getOrDefault(KEY_NICKNAME, ""), props.getOrDefault(KEY_PHONETIC_NICKNAME, "")); - } - - /** - * Parses an identity in the {@code V} form TeamSpeak keeps - * in its INI files and its settings database. - */ - public static LocalIdentity parseIdentityString(String identity) throws IOException { - String ini = "[Identity]\r\nidentity=\"" + identity + "\"\r\n"; - return LocalIdentity.read(new ByteArrayInputStream(ini.getBytes(StandardCharsets.US_ASCII))); - } - - /** Files an existing key pair as a managed identity under the given name. */ - public IdentityEntry add(String name, LocalIdentity identity, String nickname, String phoneticNickname) - throws IOException { - return create(name, identity, nickname, phoneticNickname); - } - - /** Writes an identity out in TeamSpeak's own format, ready to import elsewhere. */ - public void exportTo(IdentityEntry entry, File target) throws IOException { - write(entry, target); - } - - /** Writes an identity out in TeamSpeak's own format; closes {@code out}. */ - public void exportTo(IdentityEntry entry, OutputStream out) throws IOException { - entry.getIdentity().save(out, properties(entry)); - } - - public synchronized void rename(IdentityEntry entry, String name) throws IOException { - if (name == null || name.isBlank()) return; - entry.setName(name.trim()); - write(entry, entry.getFile()); - sort(); - } - - /** Sets the nicknames the identity connects with; empty ones fall back to the global nickname. */ - public synchronized void setNicknames(IdentityEntry entry, String nickname, String phoneticNickname) - throws IOException { - entry.setNicknames(nickname, phoneticNickname); - write(entry, entry.getFile()); - } - - /** Deletes an identity, clearing any settings or bookmarks that referenced it. */ - public synchronized void remove(IdentityEntry entry, Settings settings, Bookmarks bookmarks) { - entries.remove(entry); - //noinspection ResultOfMethodCallIgnored - entry.getFile().delete(); - - if (entry.getId().equals(settings.defaultIdentityId)) { - settings.defaultIdentityId = entries.isEmpty() ? "" : entries.get(0).getId(); - settings.save(); - } - if (bookmarks != null) { - boolean changed = false; - for (Bookmark b : bookmarks.all()) { - if (entry.getId().equals(b.identityId)) { - b.identityId = ""; - changed = true; - } - } - if (changed) bookmarks.save(); - } - } - - /** - * Raises an identity's security level towards {@code target} by searching for a - * better key offset, persisting the result. Returns the level reached. - * - * @param progress called periodically; return {@code false} from it to stop early - */ - public int improveSecurity(IdentityEntry entry, int target, ImproveProgress progress) throws IOException { - LocalIdentity identity = entry.getIdentity(); - byte[] publicKey = identity.getPublicKeyString().getBytes(StandardCharsets.US_ASCII); - MessageDigest sha1 = sha1(); - - int best = identity.getSecurityLevel(); - long offset = Math.max(identity.getKeyOffset(), identity.getLastCheckedKeyOffset()); - try { - while (best < target) { - int level = securityLevel(sha1, publicKey, offset); - if (level > best) { - best = level; - identity.setKeyOffset(offset); - } - offset++; - if ((offset & 0xFFFF) == 0 && progress != null && !progress.onProgress(best, offset)) break; - } - } finally { - identity.setLastCheckedKeyOffset(offset); - write(entry, entry.getFile()); - } - return best; - } - - // ---- persistence ---- - - private IdentityEntry create(String name, LocalIdentity identity) throws IOException { - return create(name, identity, "", ""); - } - - private synchronized IdentityEntry create(String name, LocalIdentity identity, String nickname, - String phoneticNickname) throws IOException { - String id = uniqueId(name); - IdentityEntry entry = new IdentityEntry(id, name, new File(directory(), id + ".ini"), identity); - entry.setNicknames(nickname, phoneticNickname); - write(entry, entry.getFile()); - entries.add(entry); - sort(); - return entry; - } - - private static void write(IdentityEntry entry, File file) throws IOException { - File dir = file.getParentFile(); - if (dir != null && !dir.isDirectory() && !dir.mkdirs()) { - throw new IOException("Cannot create " + dir); - } - ProfileFiles.write(file, out -> entry.getIdentity().save(out, properties(entry))); - } - - private static Map properties(IdentityEntry entry) { - Map props = new HashMap<>(); - props.put(KEY_NAME, entry.getName() == null ? "" : entry.getName()); - props.put(KEY_NICKNAME, entry.getNickname()); - props.put(KEY_PHONETIC_NICKNAME, entry.getPhoneticNickname()); - return props; - } - - private static IdentityEntry read(File file) { - try { - LocalIdentity identity = LocalIdentity.read(file); - String id = stripExtension(file.getName()); - Map props; - try (InputStream in = new FileInputStream(file)) { - props = readProperties(in); - } - String name = props.getOrDefault(KEY_NAME, ""); - IdentityEntry entry = new IdentityEntry(id, name.isBlank() ? id : name, file, identity); - entry.setNicknames(props.get(KEY_NICKNAME), props.get(KEY_PHONETIC_NICKNAME)); - return entry; - } catch (Exception e) { - return null; - } - } - - /** The name and nicknames an identity INI carries besides the key; missing ones are left out. */ - private static Map readProperties(InputStream in) { - Map props = new HashMap<>(); - try { - Ini ini = new Ini(in); - for (String key : new String[]{KEY_NAME, KEY_NICKNAME, KEY_PHONETIC_NICKNAME}) { - String value = unquote(ini.get("Identity", key)); - if (value != null) props.put(key, value); - } - } catch (Exception ignored) { - } - return props; - } - - /** TeamSpeak quotes INI values; ini4j hands them back verbatim. */ - private static String unquote(String value) { - if (value == null) return null; - String s = value.trim(); - if (s.length() >= 2 && s.startsWith("\"") && s.endsWith("\"")) { - s = s.substring(1, s.length() - 1); - } - return s.replace("\\\"", "\""); - } - - /** Derives a filesystem-safe, collision-free key from the display name. */ - private String uniqueId(String name) { - String base = (name == null ? "" : name).trim().toLowerCase(Locale.ROOT) - .replaceAll("[^a-z0-9]+", "-") - .replaceAll("(^-+|-+$)", ""); - if (base.isEmpty()) base = "identity"; - String candidate = base; - for (int i = 2; taken(candidate); i++) { - candidate = base + "-" + i; - } - return candidate; - } - - private boolean taken(String id) { - if (byId(id) != null) return true; - return new File(directory(), id + ".ini").exists(); - } - - private void sort() { - entries.sort(Comparator.comparing(e -> e.getName().toLowerCase(Locale.ROOT))); - } - - private static String stripExtension(String fileName) { - int dot = fileName.lastIndexOf('.'); - return dot > 0 ? fileName.substring(0, dot) : fileName; - } - - // ---- security level search ---- - - private static MessageDigest sha1() { - try { - return MessageDigest.getInstance("SHA-1"); - } catch (NoSuchAlgorithmException e) { - throw new IllegalStateException(e); - } - } - - /** Leading zero bits of SHA-1(publicKey + decimal offset) — TeamSpeak's proof of work. */ - private static int securityLevel(MessageDigest sha1, byte[] publicKey, long offset) { - sha1.reset(); - sha1.update(publicKey); - sha1.update(Long.toString(offset).getBytes(StandardCharsets.US_ASCII)); - return leadingZeroBits(sha1.digest()); - } - - private static int leadingZeroBits(byte[] data) { - int count = 0; - for (byte b : data) { - if (b == 0) { - count += 8; - continue; - } - for (int bit = 0; bit < 8; bit++) { - if ((b & (1 << bit)) == 0) count++; - else break; - } - break; - } - return count; - } - - /** Directory the managed identity files live in. */ - public static File directory() { - return AppDirs.file("identities"); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/config/InstallDirs.java b/ts3-client/core/src/main/java/com/ts3client/config/InstallDirs.java deleted file mode 100644 index 7510ca2..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/config/InstallDirs.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.ts3client.config; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * Locates the folders add-ons (sound packs, icon packs) are loaded from: the - * client's own folder, a folder the user configured, and the matching folder of - * an installed TeamSpeak 3 client, whose add-ons are usable as they are. - */ -public final class InstallDirs { - - /** Overrides the TeamSpeak install location the add-ons are borrowed from. */ - private static final String CLIENT_DIR_PROPERTY = "ts3.client.dir"; - private static final String CLIENT_DIR_ENV = "TS3_CLIENT_DIR"; - - private InstallDirs() { - } - - /** - * @param subfolder the add-on folder inside a TeamSpeak installation ({@code sound}, {@code gfx}) - * @param userDirectory the client's own add-on folder (may not exist yet) - * @param extraDirectory an additional folder chosen by the user, or {@code null} - * @return the folders that exist, most specific first - */ - public static List searchRoots(String subfolder, File userDirectory, String extraDirectory) { - List roots = new ArrayList<>(); - if (userDirectory != null) roots.add(userDirectory); - if (extraDirectory != null && !extraDirectory.isBlank()) roots.add(new File(extraDirectory.trim())); - - String configured = System.getProperty(CLIENT_DIR_PROPERTY, System.getenv(CLIENT_DIR_ENV)); - if (configured != null && !configured.isBlank()) roots.add(new File(configured.trim(), subfolder)); - - String home = System.getProperty("user.home", "."); - for (String candidate : new String[]{ - "TeamSpeak3-Client-linux_amd64", "TeamSpeak3-Client-linux_x86", - ".local/share/TeamSpeak3-Client-linux_amd64", "Applications/TeamSpeak3-Client-linux_amd64"}) { - roots.add(new File(new File(home, candidate), subfolder)); - } - for (String candidate : new String[]{ - "/opt/teamspeak3-client", "/opt/teamspeak3", "/usr/share/teamspeak3", - "/usr/share/teamspeak3-client"}) { - roots.add(new File(candidate, subfolder)); - } - String programFiles = System.getenv("ProgramFiles"); - if (programFiles != null) { - roots.add(new File(programFiles, "TeamSpeak 3 Client" + File.separator + subfolder)); - } - // Running from a checkout that has the official client unpacked next to it. - roots.add(new File("TeamSpeak3-Client-linux_amd64/" + subfolder)); - roots.add(new File("../TeamSpeak3-Client-linux_amd64/" + subfolder)); - - List existing = new ArrayList<>(); - for (File root : roots) { - if (root.isDirectory()) existing.add(root); - } - return existing; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/config/ProfileFiles.java b/ts3-client/core/src/main/java/com/ts3client/config/ProfileFiles.java deleted file mode 100644 index 8ecae80..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/config/ProfileFiles.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.ts3client.config; - -import java.io.File; -import java.io.FilterOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.channels.Channels; -import java.nio.channels.FileChannel; -import java.nio.file.AtomicMoveNotSupportedException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardCopyOption; -import java.nio.file.StandardOpenOption; -import java.nio.file.attribute.PosixFilePermissions; - -/** - * Writes the files in the profile, which hold private keys and server passwords: only the - * user may read them, and a crash mid-write never leaves one cut short. - */ -public final class ProfileFiles { - - /** Produces a file's content. */ - public interface Content { - void writeTo(OutputStream out) throws IOException; - } - - private ProfileFiles() { - } - - /** - * Replaces {@code file} with {@code content} in one step: it is written to a private - * temporary file next to it, flushed to disk, then moved over the old one. - */ - public static void write(File file, Content content) throws IOException { - Path target = file.toPath().toAbsolutePath(); - Path dir = target.getParent(); - Files.createDirectories(dir); - // Created readable by the owner only, where the file system has permissions at all. - Path temp = Files.createTempFile(dir, "." + file.getName() + ".", ".tmp"); - try { - try (FileChannel channel = FileChannel.open(temp, StandardOpenOption.WRITE)) { - content.writeTo(unclosable(Channels.newOutputStream(channel))); - channel.force(true); - } - try { - Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); - } catch (AtomicMoveNotSupportedException e) { - Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING); - } - } finally { - Files.deleteIfExists(temp); - } - } - - /** Some writers close what they are given; the file still has to be synced after them. */ - private static OutputStream unclosable(OutputStream out) { - return new FilterOutputStream(out) { - @Override - public void write(byte[] b, int off, int len) throws IOException { - out.write(b, off, len); - } - - @Override - public void close() { - } - }; - } - - /** Makes a directory accessible to the user only, where the file system supports that. */ - static void makePrivate(File dir) { - try { - Files.setPosixFilePermissions(dir.toPath(), PosixFilePermissions.fromString("rwx------")); - } catch (UnsupportedOperationException | IOException ignored) { - // Not a POSIX file system (Windows): the user's profile folder is private already. - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/config/ServerLogSettings.java b/ts3-client/core/src/main/java/com/ts3client/config/ServerLogSettings.java deleted file mode 100644 index 57feac0..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/config/ServerLogSettings.java +++ /dev/null @@ -1,133 +0,0 @@ -package com.ts3client.config; - -import com.ts3client.net.ServerLogEntry.Level; - -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; -import java.util.Locale; -import java.util.Properties; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * How the Server Log window shows the log: which levels, in which time zone, which lines - * stand out in colour and which are left out — TeamSpeak's ServerLogView settings. - */ -public final class ServerLogSettings { - - /** - * Lines containing {@code keyword} (ignoring case) are drawn in these colours. - * - * @param foreground an RGB colour, or {@code null} for the usual text colour - * @param background an RGB colour, or {@code null} for none - */ - public record Highlight(String keyword, Integer foreground, Integer background) { - } - - private static final String PREFIX = "serverLog."; - - /** The levels the window offers to show; the server's debug levels never reach a virtual server log. */ - public static final List SHOWN_LEVELS = List.of(Level.CRITICAL, Level.ERROR, Level.WARNING, Level.INFO); - - public final Set levels = EnumSet.copyOf(SHOWN_LEVELS); - /** Show times in the local time zone rather than in UTC, as the server writes them. */ - public boolean localTime; - /** Checked in order; the first keyword a line contains decides its colours. */ - public final List highlights = new ArrayList<>(List.of( - new Highlight("Critical", 0xC00000, null), - new Highlight("Error", 0xE03030, null), - new Highlight("Warning", 0xC07000, null))); - /** Lines containing any of these (ignoring case) are not shown. */ - public final List excludes = new ArrayList<>(); - - /** Whether a line passes the level choice and the exclude filter. */ - public boolean shows(Level level, String line) { - if (!levels.contains(level) && SHOWN_LEVELS.contains(level)) return false; - String lower = line.toLowerCase(Locale.ROOT); - for (String term : excludes) { - if (!term.isEmpty() && lower.contains(term.toLowerCase(Locale.ROOT))) return false; - } - return true; - } - - /** The first highlight whose keyword {@code line} contains, or {@code null}. */ - public Highlight highlightFor(String line) { - String lower = line.toLowerCase(Locale.ROOT); - for (Highlight h : highlights) { - if (!h.keyword().isEmpty() && lower.contains(h.keyword().toLowerCase(Locale.ROOT))) return h; - } - return null; - } - - void load(Properties p) { - String lv = p.getProperty(PREFIX + "levels"); - if (lv != null) { - levels.clear(); - for (String name : lv.split(",")) { - try { - levels.add(Level.valueOf(name.trim())); - } catch (IllegalArgumentException ignored) { - // dropped level name - } - } - } - localTime = Boolean.parseBoolean(p.getProperty(PREFIX + "localTime", Boolean.toString(localTime))); - if (p.getProperty(PREFIX + "highlights") != null) { - highlights.clear(); - int n = parseCount(p.getProperty(PREFIX + "highlights")); - for (int i = 0; i < n; i++) { - String keyword = p.getProperty(PREFIX + "highlight." + i + ".keyword"); - if (keyword == null) continue; - highlights.add(new Highlight(keyword, parseColor(p.getProperty(PREFIX + "highlight." + i + ".fg")), - parseColor(p.getProperty(PREFIX + "highlight." + i + ".bg")))); - } - } - if (p.getProperty(PREFIX + "excludes") != null) { - excludes.clear(); - int n = parseCount(p.getProperty(PREFIX + "excludes")); - for (int i = 0; i < n; i++) { - String term = p.getProperty(PREFIX + "exclude." + i); - if (term != null) excludes.add(term); - } - } - } - - void store(Properties p) { - p.stringPropertyNames().stream() - .filter(k -> k.startsWith(PREFIX + "highlight.") || k.startsWith(PREFIX + "exclude.")) - .forEach(p::remove); - p.setProperty(PREFIX + "levels", levels.stream().map(Enum::name).collect(Collectors.joining(","))); - p.setProperty(PREFIX + "localTime", Boolean.toString(localTime)); - p.setProperty(PREFIX + "highlights", Integer.toString(highlights.size())); - for (int i = 0; i < highlights.size(); i++) { - Highlight h = highlights.get(i); - p.setProperty(PREFIX + "highlight." + i + ".keyword", h.keyword()); - p.setProperty(PREFIX + "highlight." + i + ".fg", formatColor(h.foreground())); - p.setProperty(PREFIX + "highlight." + i + ".bg", formatColor(h.background())); - } - p.setProperty(PREFIX + "excludes", Integer.toString(excludes.size())); - for (int i = 0; i < excludes.size(); i++) p.setProperty(PREFIX + "exclude." + i, excludes.get(i)); - } - - private static int parseCount(String v) { - try { - return Math.max(0, Integer.parseInt(v.trim())); - } catch (NumberFormatException e) { - return 0; - } - } - - private static Integer parseColor(String v) { - if (v == null || v.isBlank()) return null; - try { - return Integer.parseInt(v.trim().replace("#", ""), 16) & 0xFFFFFF; - } catch (NumberFormatException e) { - return null; - } - } - - private static String formatColor(Integer rgb) { - return rgb == null ? "" : String.format("#%06X", rgb); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/config/Settings.java b/ts3-client/core/src/main/java/com/ts3client/config/Settings.java deleted file mode 100644 index 061ca36..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/config/Settings.java +++ /dev/null @@ -1,445 +0,0 @@ -package com.ts3client.config; - -import com.ts3client.contacts.ContactDefaults; -import com.ts3client.sound.NotificationSettings; - -import java.io.File; -import java.io.FileInputStream; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Properties; - -/** - * Simple persistent settings backed by a properties file in the user's home - * directory (~/.ts3jclient/settings.properties). - * - *

Holds connection defaults, audio device selection and voice-activation - * parameters. Loaded once at startup and saved whenever the user changes - * something in the options dialog. - */ -public final class Settings { - - /** How the microphone decides when to transmit. */ - public enum InputMode { - /** Transmit whenever voice activation detects speech. */ - VOICE_ACTIVATION, - /** Transmit only while the push-to-talk key is held. */ - PUSH_TO_TALK, - /** Always transmit (continuous). */ - CONTINUOUS - } - - /** Which look-and-feel variant the window is painted with. */ - public enum Appearance { - LIGHT, - DARK - } - - /** Voice-activation strategy, mirroring the TS3 client's VAD modes. */ - public enum VadMode { - /** Speech-probability detector only. */ - AUTOMATIC, - /** Volume gate (RMS threshold) only. */ - VOLUME_GATE, - /** Volume gate combined with speech probability. */ - HYBRID - } - - /** Who may whisper to us, the way TeamSpeak's whisper options put it. */ - public enum WhisperPolicy { - /** Use individual settings in contacts, else allow. */ - ALLOW_UNLESS_DENIED("Use individual settings in contacts, else allow"), - /** Use individual settings in contacts, else deny. */ - DENY_UNLESS_ALLOWED("Use individual settings in contacts, else deny"), - /** Nobody is allowed to whisper to you; individual contact settings are ignored. */ - NOBODY("Nobody"); - - private final String label; - - WhisperPolicy(String label) { - this.label = label; - } - - public String label() { - return label; - } - } - - private static File file() { - return AppDirs.file("settings.properties"); - } - - private final Properties props = new Properties(); - - // ---- connection ---- - public String lastAddress = "localhost"; - public String nickname = System.getProperty("user.name", "TS3J User"); - public String serverPassword = ""; - /** Legacy single-identity file; only used to migrate into the identity store. */ - public String identityFile = AppDirs.file("identity.ini").getAbsolutePath(); - /** Id of the identity used when a server doesn't select one of its own. */ - public String defaultIdentityId = ""; - - // ---- reported client version ---- - /** Report {@link #clientVersion}/{@link #clientPlatform} instead of the built-in ones. */ - public boolean customVersion = false; - /** Version string other clients see, e.g. "3.5.6 [Build: 1603963200]". */ - public String clientVersion = ClientVersion.DEFAULT.version(); - /** Operating system other clients see, e.g. "Windows". */ - public String clientPlatform = ClientVersion.DEFAULT.platform(); - /** TeamSpeak's signature over the version and platform; servers may verify it. */ - public String clientVersionSign = ClientVersion.DEFAULT.sign(); - - // ---- audio devices (mixer names; empty = system default) ---- - public String inputDevice = ""; - public String outputDevice = ""; - - // ---- voice ---- - public InputMode inputMode = InputMode.VOICE_ACTIVATION; - /** Voice-activation strategy used when {@link #inputMode} is VOICE_ACTIVATION. */ - public VadMode vadMode = VadMode.HYBRID; - /** - * Volume-gate threshold on {@link com.ts3client.audio.InputLevel}'s scale, the same one - * the TS3 client's slider uses: -50 (most sensitive) .. +50, defaulting to -40. - */ - public double vadThresholdDb = -40.0; - /** - * Speech-probability threshold (0..1) for Automatic/Hybrid modes. TS3 calls this - * {@code vad_likelihood} and also defaults it to 0.5. - */ - public double speechThreshold = 0.5; - /** Keep voice activation running while in push-to-talk mode. */ - public boolean vadOverPtt = false; - /** Opus target bitrate in bits/sec. */ - public int bitrate = 48000; - /** Opus complexity 0..10. */ - public int complexity = 10; - /** Opus variable bitrate. */ - public boolean vbr = true; - /** Opus in-band forward error correction. */ - public boolean fec = true; - /** Expected packet loss percent (drives FEC). */ - public int packetLoss = 5; - /** Encode as music (OPUS_MUSIC) rather than voice (OPUS_VOICE). */ - public boolean music = false; - /** - * Milliseconds between a voice packet and each of its {@link #redundancyCopies}, 0 for off. - * Listeners' jitter buffers grow to wait for the last copy, so it buys loss resilience with - * about {@code redundancyDelay * redundancyCopies} of latency. - */ - public int redundancyDelay = 0; - /** The {@link #redundancyDelay} choices the settings offer; whole 20 ms voice frames. */ - public static final int[] REDUNDANCY_DELAYS = {0, 20, 40, 60, 80, 120, 200}; - /** How many times every voice packet is sent again. */ - public int redundancyCopies = 1; - public static final int MAX_REDUNDANCY_COPIES = 4; - /** - * Milliseconds of playback delay held on top of what the jitter buffer measures it needs, - * so late packets and error correction copies still make it on a bad connection. - */ - public int receiveBuffer = 0; - /** The {@link #receiveBuffer} choices the settings offer; whole 20 ms voice frames. */ - public static final int[] RECEIVE_BUFFERS = {0, 20, 40, 60, 80, 120, 200, 300, 500}; - /** Master playback gain, 0..1 (may exceed 1 for boost up to 2). */ - public double outputVolume = 1.0; - /** - * Global multiplier on top of {@link #outputVolume} and {@link #soundVolume}, - * controlled from the toolbar's Master Volume slider so both can be ridden - * with one control. 0..2, same boost headroom as the other volumes. - */ - public double masterVolume = 1.0; - /** Microphone input gain multiplier applied before VAD/encode. */ - public double inputVolume = 1.0; - /** Remove steady background noise from the microphone (WebRTC noise suppression). */ - public boolean denoise = true; - /** TS3's {@code denoiser_level}: 0..3 for 6, 12, 18 or 21 dB of suppression. */ - public int denoiserLevel = 1; - /** Attenuate keyboard clicks while typing. */ - public boolean typingAttenuation = true; - /** Automatic gain control: normalise microphone loudness to a target level. */ - public boolean agc = true; - public static final int MAX_AGC_BOOST_DB = 20; - /** How many dB louder AGC may make the background noise to bring up a quiet or distant voice. */ - public int agcBoostDb = 0; - /** Beep when speech is picked up while the microphone is muted. */ - public boolean mutedTalkWarning = true; - - // ---- notification sounds ---- - /** Directory name of the active sound pack; empty picks the first one found. */ - public String soundPack = "default"; - /** Notification sound volume, 0..1. */ - public double soundVolume = 1.0; - /** Extra folder to look for sound packs in, on top of the well-known locations. */ - public String soundPackDir = ""; - /** Whether pokes and private messages show a desktop notification while the window is in the background. */ - public boolean desktopNotifications = true; - // ---- icons ---- - /** File name of the active icon pack; empty uses the built-in icons. */ - public String iconPack = "default_colored_2014.zip"; - /** - * Whether the channel tree shows each client's country flag, as TeamSpeak's EnableCountryFlags; - * their details show it beside their name either way. - */ - public boolean countryFlags = false; - /** Background colours of client rows in the channel tree. */ - public final ClientRowColors clientRowColors = new ClientRowColors(); - /** Extra folder to look for icon packs in, on top of the well-known locations. */ - public String iconPackDir = ""; - - /** Look-and-feel variant; see {@link Appearance}. */ - public Appearance appearance = Appearance.LIGHT; - /** Interface scale factor, 1.0 being 100 %; 0 follows the desktop. Read at startup. */ - public double uiScale = 0; - - // ---- window chrome ---- - /** Whether the status bar at the bottom of the window is shown. */ - public boolean showStatusBar = true; - /** Whether the Master Volume slider is shown on the toolbar. */ - public boolean showMasterVolumeSlider = true; - /** Share of the tree/info column the tree takes, i.e. where their divider sits. */ - public double infoSplitRatio = 0.68; - /** Whether the ban list shows the bans we created ourselves in bold. */ - public boolean banHighlightOwn = true; - /** The ban list columns the user shows, comma-separated column names; empty for the default set. */ - public String banListColumns = ""; - - /** What the Server Log window shows and how. */ - public final ServerLogSettings serverLog = new ServerLogSettings(); - - /** Which actions make a sound, and which ones are important enough to survive muting. */ - public final NotificationSettings notifications = new NotificationSettings(); - - // ---- contacts ---- - /** What a client starts out with when added to the contacts as a friend, blocked or neutral. */ - public final ContactDefaults contactDefaults = new ContactDefaults(); - /** Colour friends and blocked clients in the server tree, as the TeamSpeak client does. */ - public boolean colorContacts = true; - /** Whose whispers are played. */ - public WhisperPolicy whisperPolicy = WhisperPolicy.ALLOW_UNLESS_DENIED; - - /** Keep chat logs, and show their history when a chat opens. */ - public boolean chatLogs = true; - /** Where chat logs go; empty for the TeamSpeak 3 client's own folder, so both share them. */ - public String chatLogDir = ""; - /** The folder recordings were last saved to; empty for {@code ~/Recordings}. */ - public String recordingDir = ""; - /** Whether descriptions show their pictures, fetched from the web, or only links to them. */ - public boolean descriptionPictures = true; - /** Ctrl+wheel zoom of the chat's text and pictures, 1.0 being 100 %. */ - public double chatZoom = 1.0; - /** Ctrl+wheel zoom of the info panel's text and pictures, 1.0 being 100 %. */ - public double infoZoom = 1.0; - - public static Settings load() { - Settings s = new Settings(); - try { - if (file().isFile()) { - try (FileInputStream in = new FileInputStream(file())) { - s.props.load(in); - } - s.applyFromProps(); - } - } catch (Exception ignored) { - // Corrupt/unreadable settings -> fall back to defaults. - } - return s; - } - - public void save() { - try { - AppDirs.createProfile(); - writeToProps(); - ProfileFiles.write(file(), out -> props.store(out, "TS3J Swing Client settings")); - } catch (Exception ignored) { - } - } - - public File identityFile() { - return new File(identityFile); - } - - public Path recordingFolder() { - return recordingDir.isBlank() - ? Paths.get(System.getProperty("user.home", "."), "Recordings") - : Paths.get(recordingDir); - } - - /** {@link #outputVolume} scaled by the Master Volume slider. */ - public double effectiveOutputVolume() { - return outputVolume * masterVolume; - } - - /** {@link #soundVolume} scaled by the Master Volume slider. */ - public double effectiveSoundVolume() { - return soundVolume * masterVolume; - } - - private void applyFromProps() { - lastAddress = props.getProperty("lastAddress", lastAddress); - nickname = props.getProperty("nickname", nickname); - serverPassword = props.getProperty("serverPassword", serverPassword); - identityFile = props.getProperty("identityFile", identityFile); - defaultIdentityId = props.getProperty("defaultIdentityId", defaultIdentityId); - customVersion = parseB(props.getProperty("customVersion"), customVersion); - clientVersion = props.getProperty("clientVersion", clientVersion); - clientPlatform = props.getProperty("clientPlatform", clientPlatform); - clientVersionSign = props.getProperty("clientVersionSign", clientVersionSign); - inputDevice = props.getProperty("inputDevice", inputDevice); - outputDevice = props.getProperty("outputDevice", outputDevice); - inputMode = parseEnum(InputMode.class, props.getProperty("inputMode"), inputMode); - vadMode = parseEnum(VadMode.class, props.getProperty("vadMode"), vadMode); - vadThresholdDb = parseD(props.getProperty("vadLevelDb"), - migrateThreshold(props.getProperty("vadThresholdDb"), vadThresholdDb)); - speechThreshold = parseD(props.getProperty("speechThreshold"), speechThreshold); - vadOverPtt = parseB(props.getProperty("vadOverPtt"), vadOverPtt); - bitrate = parseI(props.getProperty("bitrate"), bitrate); - complexity = parseI(props.getProperty("complexity"), complexity); - vbr = parseB(props.getProperty("vbr"), vbr); - fec = parseB(props.getProperty("fec"), fec); - packetLoss = parseI(props.getProperty("packetLoss"), packetLoss); - music = parseB(props.getProperty("music"), music); - redundancyDelay = parseI(props.getProperty("redundancyDelay"), redundancyDelay); - redundancyCopies = parseI(props.getProperty("redundancyCopies"), redundancyCopies); - receiveBuffer = parseI(props.getProperty("receiveBuffer"), receiveBuffer); - outputVolume = parseD(props.getProperty("outputVolume"), outputVolume); - masterVolume = parseD(props.getProperty("masterVolume"), masterVolume); - inputVolume = parseD(props.getProperty("inputVolume"), inputVolume); - denoise = parseB(props.getProperty("denoise"), denoise); - denoiserLevel = parseI(props.getProperty("denoiserLevel"), denoiserLevel); - typingAttenuation = parseB(props.getProperty("typingAttenuation"), typingAttenuation); - mutedTalkWarning = parseB(props.getProperty("mutedTalkWarning"), mutedTalkWarning); - agc = parseB(props.getProperty("agc"), agc); - agcBoostDb = Math.max(0, Math.min(MAX_AGC_BOOST_DB, parseI(props.getProperty("agcBoostDb"), agcBoostDb))); - soundPack = props.getProperty("soundPack", soundPack); - soundVolume = parseD(props.getProperty("soundVolume"), soundVolume); - soundPackDir = props.getProperty("soundPackDir", soundPackDir); - desktopNotifications = parseB(props.getProperty("desktopNotifications"), desktopNotifications); - iconPack = props.getProperty("iconPack", iconPack); - countryFlags = parseB(props.getProperty("countryFlags"), countryFlags); - clientRowColors.load(props); - iconPackDir = props.getProperty("iconPackDir", iconPackDir); - appearance = parseEnum(Appearance.class, props.getProperty("appearance"), appearance); - uiScale = parseD(props.getProperty("uiScale"), uiScale); - showStatusBar = parseB(props.getProperty("showStatusBar"), showStatusBar); - showMasterVolumeSlider = parseB(props.getProperty("showMasterVolumeSlider"), showMasterVolumeSlider); - infoSplitRatio = parseD(props.getProperty("infoSplitRatio"), infoSplitRatio); - banHighlightOwn = parseB(props.getProperty("banHighlightOwn"), banHighlightOwn); - banListColumns = props.getProperty("banListColumns", banListColumns); - notifications.load(props); - serverLog.load(props); - contactDefaults.load(props); - colorContacts = parseB(props.getProperty("colorContacts"), colorContacts); - descriptionPictures = parseB(props.getProperty("descriptionPictures"), descriptionPictures); - whisperPolicy = parseEnum(WhisperPolicy.class, props.getProperty("whisperPolicy"), whisperPolicy); - chatLogs = parseB(props.getProperty("chatLogs"), chatLogs); - chatLogDir = props.getProperty("chatLogDir", chatLogDir); - recordingDir = props.getProperty("recordingDir", recordingDir); - } - - private void writeToProps() { - props.setProperty("lastAddress", lastAddress); - props.setProperty("nickname", nickname); - props.setProperty("serverPassword", serverPassword); - props.setProperty("identityFile", identityFile); - props.setProperty("defaultIdentityId", defaultIdentityId); - props.setProperty("customVersion", Boolean.toString(customVersion)); - props.setProperty("clientVersion", clientVersion); - props.setProperty("clientPlatform", clientPlatform); - props.setProperty("clientVersionSign", clientVersionSign); - props.setProperty("inputDevice", inputDevice); - props.setProperty("outputDevice", outputDevice); - props.setProperty("inputMode", inputMode.name()); - props.setProperty("vadMode", vadMode.name()); - props.setProperty("vadLevelDb", Double.toString(vadThresholdDb)); - props.remove("vadThresholdDb"); - props.setProperty("speechThreshold", Double.toString(speechThreshold)); - props.setProperty("vadOverPtt", Boolean.toString(vadOverPtt)); - props.setProperty("bitrate", Integer.toString(bitrate)); - props.setProperty("complexity", Integer.toString(complexity)); - props.setProperty("vbr", Boolean.toString(vbr)); - props.setProperty("fec", Boolean.toString(fec)); - props.setProperty("packetLoss", Integer.toString(packetLoss)); - props.setProperty("music", Boolean.toString(music)); - props.setProperty("redundancyDelay", Integer.toString(redundancyDelay)); - props.setProperty("redundancyCopies", Integer.toString(redundancyCopies)); - props.setProperty("receiveBuffer", Integer.toString(receiveBuffer)); - props.setProperty("outputVolume", Double.toString(outputVolume)); - props.setProperty("masterVolume", Double.toString(masterVolume)); - props.setProperty("inputVolume", Double.toString(inputVolume)); - props.setProperty("denoise", Boolean.toString(denoise)); - props.setProperty("denoiserLevel", Integer.toString(denoiserLevel)); - props.setProperty("typingAttenuation", Boolean.toString(typingAttenuation)); - props.setProperty("mutedTalkWarning", Boolean.toString(mutedTalkWarning)); - props.setProperty("agc", Boolean.toString(agc)); - props.setProperty("agcBoostDb", Integer.toString(agcBoostDb)); - props.setProperty("soundPack", soundPack); - props.setProperty("soundVolume", Double.toString(soundVolume)); - props.setProperty("soundPackDir", soundPackDir); - props.setProperty("desktopNotifications", Boolean.toString(desktopNotifications)); - props.setProperty("iconPack", iconPack); - props.setProperty("countryFlags", Boolean.toString(countryFlags)); - clientRowColors.store(props); - props.setProperty("iconPackDir", iconPackDir); - props.setProperty("appearance", appearance.name()); - props.setProperty("uiScale", Double.toString(uiScale)); - props.setProperty("showStatusBar", Boolean.toString(showStatusBar)); - props.setProperty("showMasterVolumeSlider", Boolean.toString(showMasterVolumeSlider)); - props.setProperty("infoSplitRatio", Double.toString(infoSplitRatio)); - props.setProperty("banHighlightOwn", Boolean.toString(banHighlightOwn)); - props.setProperty("banListColumns", banListColumns); - notifications.store(props); - serverLog.store(props); - contactDefaults.store(props); - props.setProperty("colorContacts", Boolean.toString(colorContacts)); - props.setProperty("descriptionPictures", Boolean.toString(descriptionPictures)); - props.setProperty("whisperPolicy", whisperPolicy.name()); - props.setProperty("chatLogs", Boolean.toString(chatLogs)); - props.setProperty("chatLogDir", chatLogDir); - props.setProperty("recordingDir", recordingDir); - } - - private static > E parseEnum(Class type, String v, E def) { - if (v == null) return def; - try { - return Enum.valueOf(type, v.trim()); - } catch (IllegalArgumentException e) { - return def; - } - } - - /** - * Converts a threshold saved under the old {@code vadThresholdDb} key, which was in - * dBFS ({@code 20*log10(rms)}), to {@link com.ts3client.audio.InputLevel}'s scale, so - * upgrading doesn't silently change how sensitive the gate is. - */ - private static double migrateThreshold(String legacy, double def) { - double dbfs = parseD(legacy, Double.NaN); - if (Double.isNaN(dbfs)) { - return def; - } - double converted = com.ts3client.audio.InputLevel.powerToDb(Math.pow(10.0, dbfs / 10.0)); - return Math.min(com.ts3client.audio.InputLevel.MAX_DB, converted); - } - - private static double parseD(String v, double def) { - if (v == null) return def; - try { - return Double.parseDouble(v); - } catch (NumberFormatException e) { - return def; - } - } - - private static int parseI(String v, int def) { - if (v == null) return def; - try { - return Integer.parseInt(v); - } catch (NumberFormatException e) { - return def; - } - } - - private static boolean parseB(String v, boolean def) { - return v == null ? def : Boolean.parseBoolean(v); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/config/WhisperList.java b/ts3-client/core/src/main/java/com/ts3client/config/WhisperList.java deleted file mode 100644 index fa18575..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/config/WhisperList.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.ts3client.config; - -import java.util.ArrayList; -import java.util.List; - -/** A saved set of channels and clients to whisper to, wherever they are on the server we are on. */ -public final class WhisperList { - - /** A client by unique id, so the list finds them under any client id; the nickname is for showing. */ - public record Client(String uniqueId, String nickname) { - } - - public String name = ""; - /** Channel references as {@link Bookmark#channel} holds them: "/"-separated paths or "/<id>". */ - public final List channels = new ArrayList<>(); - public final List clients = new ArrayList<>(); - - public WhisperList() { - } - - public WhisperList(String name) { - this.name = name; - } - - public WhisperList copy() { - WhisperList c = new WhisperList(name); - c.channels.addAll(channels); - c.clients.addAll(clients); - return c; - } - - public boolean isEmpty() { - return channels.isEmpty() && clients.isEmpty(); - } - - @Override - public String toString() { - return name; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/config/WhisperLists.java b/ts3-client/core/src/main/java/com/ts3client/config/WhisperLists.java deleted file mode 100644 index b204ac4..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/config/WhisperLists.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.ts3client.config; - -import java.io.File; -import java.io.FileInputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -/** The saved {@link WhisperList}s, shared by every server. */ -public final class WhisperLists { - - private static File file() { - return AppDirs.file("whisperlists.properties"); - } - - private final List entries = new ArrayList<>(); - - public List all() { - return entries; - } - - /** The list with this name, ignoring case, or null. */ - public WhisperList find(String name) { - for (WhisperList l : entries) { - if (l.name.equalsIgnoreCase(name)) return l; - } - return null; - } - - public static WhisperLists load() { - WhisperLists lists = new WhisperLists(); - if (!file().isFile()) return lists; - Properties p = new Properties(); - try (FileInputStream in = new FileInputStream(file())) { - p.load(in); - } catch (Exception e) { - return lists; - } - int count = parseInt(p.getProperty("count")); - for (int i = 0; i < count; i++) { - String prefix = "list." + i + "."; - WhisperList list = new WhisperList(p.getProperty(prefix + "name", "")); - int channels = parseInt(p.getProperty(prefix + "channels")); - for (int j = 0; j < channels; j++) { - String channel = p.getProperty(prefix + "channel." + j, ""); - if (!channel.isBlank()) list.channels.add(channel); - } - int clients = parseInt(p.getProperty(prefix + "clients")); - for (int j = 0; j < clients; j++) { - String uid = p.getProperty(prefix + "client." + j + ".uid", ""); - if (!uid.isBlank()) { - list.clients.add(new WhisperList.Client(uid, p.getProperty(prefix + "client." + j + ".name", ""))); - } - } - lists.entries.add(list); - } - return lists; - } - - public void save() { - Properties p = new Properties(); - p.setProperty("count", Integer.toString(entries.size())); - for (int i = 0; i < entries.size(); i++) { - WhisperList list = entries.get(i); - String prefix = "list." + i + "."; - p.setProperty(prefix + "name", list.name); - p.setProperty(prefix + "channels", Integer.toString(list.channels.size())); - for (int j = 0; j < list.channels.size(); j++) { - p.setProperty(prefix + "channel." + j, list.channels.get(j)); - } - p.setProperty(prefix + "clients", Integer.toString(list.clients.size())); - for (int j = 0; j < list.clients.size(); j++) { - WhisperList.Client c = list.clients.get(j); - p.setProperty(prefix + "client." + j + ".uid", c.uniqueId()); - p.setProperty(prefix + "client." + j + ".name", c.nickname() == null ? "" : c.nickname()); - } - } - try { - AppDirs.createProfile(); - ProfileFiles.write(file(), out -> p.store(out, "TS3J client whisper lists")); - } catch (Exception ignored) { - } - } - - private static int parseInt(String v) { - if (v == null) return 0; - try { - return Integer.parseInt(v.trim()); - } catch (NumberFormatException e) { - return 0; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/contacts/Contact.java b/ts3-client/core/src/main/java/com/ts3client/contacts/Contact.java deleted file mode 100644 index 395d1cd..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/contacts/Contact.java +++ /dev/null @@ -1,199 +0,0 @@ -package com.ts3client.contacts; - -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.LinkedHashMap; -import java.util.Locale; -import java.util.Map; - -/** - * One entry of the contact list, keyed by the client's unique id. - * - *

The fields are exactly the ones the TeamSpeak 3 client keeps for a contact, - * and {@link #toRecord()} / {@link #parseRecord} use its own {@code Key=Value} - * serialisation (the {@code value} column of its {@code Contacts} table), so - * records can be exchanged with it as they are. - */ -public final class Contact { - - /** TeamSpeak writes {@code LastSeen} as an ISO local date-time without zone. */ - private static final DateTimeFormatter LAST_SEEN = DateTimeFormatter.ISO_LOCAL_DATE_TIME; - - public final String uniqueId; - /** Custom name; TeamSpeak seeds it with the nickname the client had when added. */ - public String nickname = ""; - public String phoneticNickname = ""; - public ContactType type = ContactType.NEUTRAL; - public boolean automute; - public boolean ignorePublicMessages; - public boolean ignorePrivateMessages; - public boolean ignorePokes; - public boolean ignoreAvatar; - public boolean ignoreAwayMessage; - public NicknameDisplay nicknameDisplay = NicknameDisplay.BOTH; - public boolean hasVolumeModifier; - /** Playback gain for this client in dB, applied when {@link #hasVolumeModifier} is set. */ - public double volumeModifier; - public boolean whisperAllowed = true; - /** When the contact was last seen online, or {@code null} for never. */ - public LocalDateTime lastSeen; - public String lastSeenServerName = ""; - public String lastSeenServerAddress = ""; - - public Contact(String uniqueId) { - this.uniqueId = uniqueId == null ? "" : uniqueId; - } - - /** The name the contact is shown under, given the nickname it currently carries. */ - public String displayName(String currentNickname) { - return nicknameDisplay.render(nickname, currentNickname); - } - - /** Playback gain as a linear multiplier, 1.0 when no modifier is set. */ - public double volumeGain() { - return hasVolumeModifier ? Math.pow(10.0, volumeModifier / 20.0) : 1.0; - } - - public Contact copy() { - Contact c = new Contact(uniqueId); - c.copyFrom(this); - return c; - } - - /** Takes over every field but the unique id. */ - public void copyFrom(Contact other) { - nickname = other.nickname; - phoneticNickname = other.phoneticNickname; - type = other.type; - automute = other.automute; - ignorePublicMessages = other.ignorePublicMessages; - ignorePrivateMessages = other.ignorePrivateMessages; - ignorePokes = other.ignorePokes; - ignoreAvatar = other.ignoreAvatar; - ignoreAwayMessage = other.ignoreAwayMessage; - nicknameDisplay = other.nicknameDisplay; - hasVolumeModifier = other.hasVolumeModifier; - volumeModifier = other.volumeModifier; - whisperAllowed = other.whisperAllowed; - lastSeen = other.lastSeen; - lastSeenServerName = other.lastSeenServerName; - lastSeenServerAddress = other.lastSeenServerAddress; - } - - /** Applies the per-type defaults, as done when a client is first added. */ - public void applyDefaults(ContactDefaults.Entry defaults) { - nicknameDisplay = defaults.nicknameDisplay; - automute = defaults.automute; - ignorePublicMessages = defaults.ignorePublicMessages; - ignorePrivateMessages = defaults.ignorePrivateMessages; - ignorePokes = defaults.ignorePokes; - ignoreAvatar = defaults.ignoreAvatar; - ignoreAwayMessage = defaults.ignoreAwayMessage; - whisperAllowed = !defaults.ignoreWhisper; - } - - // ---- TeamSpeak record format ---- - - /** The contact as TeamSpeak's {@code Key=Value} lines, in the order it writes them. */ - public String toRecord() { - StringBuilder sb = new StringBuilder(); - line(sb, "IDS", uniqueId); - line(sb, "Nickname", nickname); - line(sb, "Friend", Integer.toString(type.code())); - line(sb, "Automute", flag(automute)); - line(sb, "IgnorePublicMessages", flag(ignorePublicMessages)); - line(sb, "IgnorePrivateMessages", flag(ignorePrivateMessages)); - line(sb, "IgnorePokes", flag(ignorePokes)); - line(sb, "IgnoreAvatar", flag(ignoreAvatar)); - line(sb, "IgnoreAwayMessage", flag(ignoreAwayMessage)); - line(sb, "NickShowType", Integer.toString(nicknameDisplay.code())); - line(sb, "HaveVolumeModifier", flag(hasVolumeModifier)); - line(sb, "VolumeModifier", formatVolume(volumeModifier)); - line(sb, "WhisperAllow", flag(whisperAllowed)); - line(sb, "PhoneticNickname", phoneticNickname); - line(sb, "LastSeen", lastSeen == null ? "" : LAST_SEEN.format(lastSeen)); - line(sb, "LastSeenServerName", lastSeenServerName); - line(sb, "LastSeenServerAddress", lastSeenServerAddress); - return sb.toString(); - } - - /** Parses a TeamSpeak contact record, or returns {@code null} when it carries no unique id. */ - public static Contact parseRecord(String record) { - if (record == null) return null; - Map fields = new LinkedHashMap<>(); - for (String line : record.split("\r?\n")) { - int eq = line.indexOf('='); - if (eq > 0) fields.put(line.substring(0, eq).trim(), line.substring(eq + 1)); - } - String uid = fields.getOrDefault("IDS", "").trim(); - if (uid.isEmpty()) return null; - - Contact c = new Contact(uid); - c.nickname = fields.getOrDefault("Nickname", ""); - c.type = ContactType.fromCode(parseInt(fields.get("Friend"), ContactType.NEUTRAL.code())); - c.automute = parseFlag(fields.get("Automute")); - c.ignorePublicMessages = parseFlag(fields.get("IgnorePublicMessages")); - c.ignorePrivateMessages = parseFlag(fields.get("IgnorePrivateMessages")); - c.ignorePokes = parseFlag(fields.get("IgnorePokes")); - c.ignoreAvatar = parseFlag(fields.get("IgnoreAvatar")); - c.ignoreAwayMessage = parseFlag(fields.get("IgnoreAwayMessage")); - c.nicknameDisplay = NicknameDisplay.fromCode(parseInt(fields.get("NickShowType"), 0)); - c.hasVolumeModifier = parseFlag(fields.get("HaveVolumeModifier")); - c.volumeModifier = parseDouble(fields.get("VolumeModifier"), 0); - c.whisperAllowed = !fields.containsKey("WhisperAllow") || parseFlag(fields.get("WhisperAllow")); - c.phoneticNickname = fields.getOrDefault("PhoneticNickname", ""); - c.lastSeen = parseLastSeen(fields.get("LastSeen")); - c.lastSeenServerName = fields.getOrDefault("LastSeenServerName", ""); - // TeamSpeak's own writer misspells the key in one of its code paths. - c.lastSeenServerAddress = fields.getOrDefault("LastSeenServerAddress", - fields.getOrDefault("LastSeenServerAddres", "")); - return c; - } - - private static void line(StringBuilder sb, String key, String value) { - sb.append(key).append('=').append(value == null ? "" : value.replace("\n", " ")).append('\n'); - } - - private static String flag(boolean b) { - return b ? "1" : "0"; - } - - private static String formatVolume(double db) { - if (db == Math.rint(db)) return Integer.toString((int) db); - return String.format(Locale.ROOT, "%.2f", db); - } - - private static boolean parseFlag(String v) { - if (v == null) return false; - String t = v.trim(); - return t.equals("1") || t.equalsIgnoreCase("true"); - } - - private static int parseInt(String v, int def) { - if (v == null) return def; - try { - return Integer.parseInt(v.trim()); - } catch (NumberFormatException e) { - return def; - } - } - - private static double parseDouble(String v, double def) { - if (v == null) return def; - try { - return Double.parseDouble(v.trim()); - } catch (NumberFormatException e) { - return def; - } - } - - private static LocalDateTime parseLastSeen(String v) { - if (v == null || v.isBlank()) return null; - try { - return LocalDateTime.parse(v.trim(), LAST_SEEN); - } catch (DateTimeParseException e) { - return null; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/contacts/ContactDefaults.java b/ts3-client/core/src/main/java/com/ts3client/contacts/ContactDefaults.java deleted file mode 100644 index fe9a71f..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/contacts/ContactDefaults.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.ts3client.contacts; - -import java.util.Properties; - -/** - * What a newly added contact starts out with, kept separately for friends, blocked - * and neutral clients — TeamSpeak's "Contact Manager Default Settings". - */ -public final class ContactDefaults { - - /** The defaults for one contact type. */ - public static final class Entry { - public NicknameDisplay nicknameDisplay = NicknameDisplay.BOTH; - public boolean automute; - public boolean ignorePublicMessages; - public boolean ignorePrivateMessages; - public boolean ignorePokes; - public boolean ignoreAvatar; - public boolean ignoreAwayMessage; - public boolean ignoreWhisper; - - public void copyFrom(Entry other) { - nicknameDisplay = other.nicknameDisplay; - automute = other.automute; - ignorePublicMessages = other.ignorePublicMessages; - ignorePrivateMessages = other.ignorePrivateMessages; - ignorePokes = other.ignorePokes; - ignoreAvatar = other.ignoreAvatar; - ignoreAwayMessage = other.ignoreAwayMessage; - ignoreWhisper = other.ignoreWhisper; - } - - private void load(Properties p, String prefix) { - nicknameDisplay = parseDisplay(p.getProperty(prefix + "nicknameDisplay"), nicknameDisplay); - automute = parseB(p.getProperty(prefix + "automute"), automute); - ignorePublicMessages = parseB(p.getProperty(prefix + "ignorePublicMessages"), ignorePublicMessages); - ignorePrivateMessages = parseB(p.getProperty(prefix + "ignorePrivateMessages"), ignorePrivateMessages); - ignorePokes = parseB(p.getProperty(prefix + "ignorePokes"), ignorePokes); - ignoreAvatar = parseB(p.getProperty(prefix + "ignoreAvatar"), ignoreAvatar); - ignoreAwayMessage = parseB(p.getProperty(prefix + "ignoreAwayMessage"), ignoreAwayMessage); - ignoreWhisper = parseB(p.getProperty(prefix + "ignoreWhisper"), ignoreWhisper); - } - - private void store(Properties p, String prefix) { - p.setProperty(prefix + "nicknameDisplay", nicknameDisplay.name()); - p.setProperty(prefix + "automute", Boolean.toString(automute)); - p.setProperty(prefix + "ignorePublicMessages", Boolean.toString(ignorePublicMessages)); - p.setProperty(prefix + "ignorePrivateMessages", Boolean.toString(ignorePrivateMessages)); - p.setProperty(prefix + "ignorePokes", Boolean.toString(ignorePokes)); - p.setProperty(prefix + "ignoreAvatar", Boolean.toString(ignoreAvatar)); - p.setProperty(prefix + "ignoreAwayMessage", Boolean.toString(ignoreAwayMessage)); - p.setProperty(prefix + "ignoreWhisper", Boolean.toString(ignoreWhisper)); - } - } - - private static final String PREFIX = "contacts.defaults."; - - private final Entry friend = new Entry(); - private final Entry blocked = new Entry(); - private final Entry neutral = new Entry(); - - public Entry of(ContactType type) { - switch (type) { - case FRIEND: - return friend; - case BLOCKED: - return blocked; - default: - return neutral; - } - } - - public void copyFrom(ContactDefaults other) { - friend.copyFrom(other.friend); - blocked.copyFrom(other.blocked); - neutral.copyFrom(other.neutral); - } - - public void load(Properties p) { - for (ContactType t : ContactType.values()) of(t).load(p, PREFIX + t.name().toLowerCase() + "."); - } - - public void store(Properties p) { - for (ContactType t : ContactType.values()) of(t).store(p, PREFIX + t.name().toLowerCase() + "."); - } - - private static boolean parseB(String v, boolean def) { - return v == null ? def : Boolean.parseBoolean(v.trim()); - } - - private static NicknameDisplay parseDisplay(String v, NicknameDisplay def) { - if (v == null) return def; - try { - return NicknameDisplay.valueOf(v.trim()); - } catch (IllegalArgumentException e) { - return def; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/contacts/ContactStore.java b/ts3-client/core/src/main/java/com/ts3client/contacts/ContactStore.java deleted file mode 100644 index 223e00a..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/contacts/ContactStore.java +++ /dev/null @@ -1,267 +0,0 @@ -package com.ts3client.contacts; - -import com.ts3client.config.AppDirs; -import com.ts3client.config.ProfileFiles; -import com.ts3client.teamspeak.TeamSpeakSettingsDb; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.time.LocalDateTime; -import java.time.temporal.ChronoUnit; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * The contact list (TeamSpeak's "Friend/Foe manager"): who is a friend, who is - * blocked, and how each of them is displayed and filtered. - * - *

Persisted in {@code ~/.ts3jclient/contacts.txt} as TeamSpeak's own contact - * records separated by blank lines — the same text the official client keeps in - * the {@code Contacts} table of its {@code settings.db}, so entries can be moved - * between the two verbatim. On first run the list is seeded from an installed - * TeamSpeak client's database, when one is found. - * - *

Safe to use from any thread: lookups are lock-free on a snapshot, and - * mutations are serialised and announced to listeners on the calling thread. - */ -public final class ContactStore { - - /** How long a sighting may wait before it is written. */ - static final long SEEN_SAVE_DELAY_S = 30; - - /** Told after the list changed in any way; called on whatever thread made the change. */ - public interface Listener { - void onContactsChanged(); - } - - private static File file() { - return AppDirs.file("contacts.txt"); - } - - private final File file; - private final Map byUid = new LinkedHashMap<>(); - /** Immutable snapshot for readers, replaced under the lock after every change. */ - private volatile List snapshot = List.of(); - private final List listeners = new CopyOnWriteArrayList<>(); - /** Set while a sighting waits for {@link #flush()}; any save takes it along. */ - private final AtomicBoolean savePending = new AtomicBoolean(); - private final ScheduledExecutorService saver = Executors.newSingleThreadScheduledExecutor(r -> { - Thread t = new Thread(r, "contacts-save"); - t.setDaemon(true); - return t; - }); - - ContactStore(File file) { - this.file = file; - } - - /** Loads the list, seeding it from the TeamSpeak 3 client's database the first time round. */ - public static ContactStore load() { - File file = file(); - ContactStore store = new ContactStore(file); - if (file.isFile()) { - store.readFile(); - } else { - List imported = TeamSpeakSettingsDb.readContacts(); - if (!imported.isEmpty()) { - store.replaceAll(imported); - store.save(); - } - } - return store; - } - - void readFile() { - String text; - try { - // Android < API 36.1 lacks Files.readString; original: - // text = Files.readString(file.toPath(), StandardCharsets.UTF_8); - text = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); - } catch (IOException e) { - return; - } - List parsed = new ArrayList<>(); - for (String record : text.split("\\r?\\n\\s*\\r?\\n")) { - Contact c = Contact.parseRecord(record); - if (c != null) parsed.add(c); - } - synchronized (this) { - byUid.clear(); - for (Contact c : parsed) byUid.put(c.uniqueId, c); - snapshot = List.copyOf(byUid.values()); - } - } - - public void save() { - savePending.set(false); - List all = snapshot; - StringBuilder sb = new StringBuilder(); - for (Contact c : all) { - if (sb.length() > 0) sb.append('\n'); - sb.append(c.toRecord()); - } - try { - AppDirs.createProfile(); - ProfileFiles.write(file, out -> out.write(sb.toString().getBytes(StandardCharsets.UTF_8))); - } catch (IOException ignored) { - } - } - - public void addListener(Listener l) { - listeners.add(l); - } - - public void removeListener(Listener l) { - listeners.remove(l); - } - - // ---- lookups ---- - - /** Every contact, in list order. */ - public List all() { - return snapshot; - } - - public Contact find(String uniqueId) { - if (uniqueId == null || uniqueId.isEmpty()) return null; - for (Contact c : snapshot) { - if (c.uniqueId.equals(uniqueId)) return c; - } - return null; - } - - /** The type a client is filed under, {@code null} when it is not a contact. */ - public ContactType typeOf(String uniqueId) { - Contact c = find(uniqueId); - return c == null ? null : c.type; - } - - /** The name a client should be shown under: its contact's custom name, else the nickname. */ - public String displayName(String uniqueId, String nickname) { - Contact c = find(uniqueId); - return c == null ? nickname : c.displayName(nickname); - } - - // ---- mutations ---- - - /** - * Files a client as a contact of the given type, applying the type's defaults to - * a new entry and only re-typing an existing one. - * - * @return the resulting contact - */ - public Contact add(String uniqueId, String nickname, ContactType type, ContactDefaults defaults) { - Contact contact; - synchronized (this) { - contact = byUid.get(uniqueId); - if (contact == null) { - contact = new Contact(uniqueId); - contact.nickname = nickname == null ? "" : nickname; - contact.applyDefaults(defaults.of(type)); - byUid.put(uniqueId, contact); - } - contact.type = type; - snapshot = List.copyOf(byUid.values()); - } - changed(); - return contact; - } - - /** Stores an edited contact, replacing any entry with the same unique id. */ - public void put(Contact contact) { - synchronized (this) { - Contact existing = byUid.get(contact.uniqueId); - if (existing != null && existing != contact) existing.copyFrom(contact); - else byUid.put(contact.uniqueId, contact); - snapshot = List.copyOf(byUid.values()); - } - changed(); - } - - public void remove(String uniqueId) { - synchronized (this) { - if (byUid.remove(uniqueId) == null) return; - snapshot = List.copyOf(byUid.values()); - } - changed(); - } - - /** Takes over a whole list, e.g. one read from the TeamSpeak client. */ - public void replaceAll(Collection contacts) { - synchronized (this) { - byUid.clear(); - for (Contact c : contacts) byUid.put(c.uniqueId, c); - snapshot = List.copyOf(byUid.values()); - } - changed(); - } - - /** - * Merges contacts read from elsewhere: entries for clients not on the list yet are - * added, existing ones are overwritten. - * - * @return how many entries were new - */ - public int merge(Collection contacts) { - int added = 0; - synchronized (this) { - for (Contact c : contacts) { - if (byUid.put(c.uniqueId, c) == null) added++; - } - snapshot = List.copyOf(byUid.values()); - } - changed(); - return added; - } - - /** - * Notes that a contact is online right now. A sighting within the same minute on the - * same server changes nothing. Sightings reach the file in one go, {@link - * #SEEN_SAVE_DELAY_S} later or with the next save, so a busy server does not rewrite it - * per event. - */ - public void markSeen(String uniqueId, String serverName, String serverAddress) { - Contact c = find(uniqueId); - if (c == null) return; - LocalDateTime now = LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS); - synchronized (this) { - if (c.lastSeen != null && ChronoUnit.MINUTES.between(c.lastSeen, now) < 1 - && c.lastSeenServerAddress.equals(orEmpty(serverAddress))) { - return; - } - c.lastSeen = now; - c.lastSeenServerName = orEmpty(serverName); - c.lastSeenServerAddress = orEmpty(serverAddress); - } - if (savePending.compareAndSet(false, true)) saver.schedule(this::flush, SEEN_SAVE_DELAY_S, TimeUnit.SECONDS); - announce(); - } - - /** Writes sightings still waiting to be saved; for when the client goes away. */ - public void flush() { - if (savePending.get()) save(); - } - - private void changed() { - save(); - announce(); - } - - private void announce() { - for (Listener l : listeners) l.onContactsChanged(); - } - - private static String orEmpty(String s) { - return s == null ? "" : s; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/contacts/ContactType.java b/ts3-client/core/src/main/java/com/ts3client/contacts/ContactType.java deleted file mode 100644 index 6a7571d..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/contacts/ContactType.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ts3client.contacts; - -/** How a contact is classed; the codes are the ones TeamSpeak stores in {@code Friend=}. */ -public enum ContactType { - FRIEND(0, "Friend"), - BLOCKED(1, "Blocked"), - NEUTRAL(2, "Neutral"); - - private final int code; - private final String label; - - ContactType(int code, String label) { - this.code = code; - this.label = label; - } - - public int code() { - return code; - } - - public String label() { - return label; - } - - public static ContactType fromCode(int code) { - for (ContactType t : values()) if (t.code == code) return t; - return NEUTRAL; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/contacts/NicknameDisplay.java b/ts3-client/core/src/main/java/com/ts3client/contacts/NicknameDisplay.java deleted file mode 100644 index 6b4df70..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/contacts/NicknameDisplay.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.ts3client.contacts; - -/** Which name a contact is shown under; the codes are TeamSpeak's {@code NickShowType=}. */ -public enum NicknameDisplay { - /** "Custom name and nickname": the custom name with the live nickname in brackets. */ - BOTH(0, "Custom name and nickname"), - ONLY_CUSTOM(1, "Only custom name"), - ONLY_NICKNAME(2, "Only nickname"); - - private final int code; - private final String label; - - NicknameDisplay(int code, String label) { - this.code = code; - this.label = label; - } - - public int code() { - return code; - } - - public String label() { - return label; - } - - public static NicknameDisplay fromCode(int code) { - for (NicknameDisplay d : values()) if (d.code == code) return d; - return BOTH; - } - - /** Renders a nickname the way this mode asks for it; a blank custom name always yields the nickname. */ - public String render(String customName, String nickname) { - if (customName == null || customName.isBlank()) return nickname; - switch (this) { - case ONLY_CUSTOM: - return customName; - case ONLY_NICKNAME: - return nickname; - default: - return customName.equals(nickname) ? nickname : customName + " (" + nickname + ")"; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/gfx/CountryFlags.java b/ts3-client/core/src/main/java/com/ts3client/gfx/CountryFlags.java deleted file mode 100644 index 5fc897b..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/gfx/CountryFlags.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.ts3client.gfx; - -import com.ts3client.config.InstallDirs; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.IllformedLocaleException; -import java.util.Locale; -import java.util.Map; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - -/** - * The flags TeamSpeak shows for the country the server places a client in: the - * {@code .png} files of its {@code countries.zip}, the one the build shipped, else - * a TeamSpeak 3 install's. - */ -public final class CountryFlags { - - private static final String RESOURCE = "/gfx/teamspeak/countries.zip"; - private static final String FILE = "countries.zip"; - - private static volatile Map flags; - - private CountryFlags() { - } - - /** @return the flag's PNG bytes, or {@code null} for an unknown or empty code */ - public static byte[] png(String code) { - if (code == null || code.isEmpty()) return null; - return flags().get(code.toLowerCase(Locale.ROOT)); - } - - /** @return the country's English name, or the code itself when it names none */ - public static String name(String code) { - try { - String name = new Locale.Builder().setRegion(code).build().getDisplayCountry(Locale.ENGLISH); - return name.isEmpty() ? code : name; - } catch (IllformedLocaleException e) { - return code; - } - } - - private static Map flags() { - Map loaded = flags; - if (loaded != null) return loaded; - synchronized (CountryFlags.class) { - if (flags == null) flags = load(); - return flags; - } - } - - private static Map load() { - try (InputStream in = CountryFlags.class.getResourceAsStream(RESOURCE)) { - if (in != null) return read(in); - } catch (IOException ignored) { - // try an install's - } - for (File root : InstallDirs.searchRoots("gfx", null, null)) { - File zip = new File(root, FILE); - if (!zip.isFile()) continue; - try (InputStream in = new FileInputStream(zip)) { - return read(in); - } catch (IOException ignored) { - // try the next - } - } - return Map.of(); - } - - private static Map read(InputStream in) throws IOException { - Map out = new HashMap<>(); - try (ZipInputStream zip = new ZipInputStream(in)) { - for (ZipEntry e; (e = zip.getNextEntry()) != null; ) { - String name = e.getName().toLowerCase(Locale.ROOT); - if (!e.isDirectory() && name.endsWith(".png")) { - out.put(name.substring(name.lastIndexOf('/') + 1, name.length() - 4), zip.readAllBytes()); - } - } - } - return out; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/gfx/IconKeys.java b/ts3-client/core/src/main/java/com/ts3client/gfx/IconKeys.java deleted file mode 100644 index 0b0f1c6..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/gfx/IconKeys.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.ts3client.gfx; - -import com.ts3client.net.ClientStatus; - -/** - * The TeamSpeak icon keys the channel tree is drawn with, so every frontend asks - * the packs for the same icons. - */ -public final class IconKeys { - - private IconKeys() { - } - - /** - * @return the keys to try for a channel, most specific first — packs need not ship - * every variant (none of TeamSpeak's own has a subscribed password channel) - */ - public static String[] channel(boolean password, boolean full, boolean subscribed) { - String base = password ? "CHANNEL_PRIVATE" : full ? "CHANNEL_RED" : "CHANNEL_GREEN"; - return subscribed ? new String[]{base + "_SUBSCRIBED", base} : new String[]{base}; - } - - public static String client(ClientStatus status) { - return switch (status) { - case QUERY -> "SERVER_QUERY"; - case SPEAKERS_DISABLED -> "HARDWARE_OUTPUT_MUTED"; - case SPEAKERS_MUTED -> "OUTPUT_MUTED"; - case MIC_DISABLED -> "HARDWARE_INPUT_MUTED"; - case MIC_MUTED -> "INPUT_MUTED"; - case AWAY -> "AWAY"; - case COMMANDER_TALKING -> "PLAYER_COMMANDER_ON"; - case COMMANDER -> "PLAYER_COMMANDER_OFF"; - case TALKING -> "PLAYER_ON"; - case IDLE -> "PLAYER_OFF"; - }; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/gfx/IconPack.java b/ts3-client/core/src/main/java/com/ts3client/gfx/IconPack.java deleted file mode 100644 index d83bd91..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/gfx/IconPack.java +++ /dev/null @@ -1,388 +0,0 @@ -package com.ts3client.gfx; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.TreeSet; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; -import java.util.zip.ZipInputStream; - -/** - * A TeamSpeak icon pack: a zip (or unpacked directory) of images plus an optional - * {@code settings.ini} naming the file behind every icon of the user interface. - * The format is TeamSpeak's, so the packs shipped with the official client and the - * ones from its add-on site can be used as they are: - * - *

- * [options]
- * FALLBACK=true
- *
- * [gfxfiles]
- * CHANNEL_GREEN = channel_green.svg
- * CONNECT       = connect.svg
- * 
- * - *

Packs without a {@code settings.ini} are the legacy ones (TeamSpeak's own - * {@code default.zip}), whose files are named after the icon key directly, each - * prefixed with the size it was drawn for: {@code 16x16_connect.png}. Those are - * resolved by convention, picking the size closest to the one that is asked for. - * - *

Icon data is returned as bytes; rasterising it (the packs from 2014 on are - * vector art) is the frontend's job. Vector art may paint with {@code currentColor}, - * which the frontend sets to its text colour ({@link #withCurrentColor}). - */ -public final class IconPack { - - private static final String INI = "settings.ini"; - /** Legacy file names: {@code x_.}. */ - private static final Pattern SIZED = Pattern.compile("(\\d+)x(\\d+)_(.+)"); - - /** One image inside a pack, with the size it was authored at (0 when unknown). */ - private record Entry(String path, int size) { - } - - /** Where a pack's files are read from: a zip, a directory or the classpath. */ - private interface Storage { - /** @return the file's bytes, or {@code null} when there is no such file */ - byte[] read(String path) throws IOException; - } - - private final String id; - private final File source; - private final String name; - private final Storage storage; - private final boolean fallback; - /** Icon key to the images that can serve it, smallest first. */ - private final Map> entries; - - private IconPack(String id, File source, String name, Storage storage, boolean fallback, - Map> entries) { - this.id = id; - this.source = source; - this.name = name; - this.storage = storage; - this.fallback = fallback; - this.entries = entries; - } - - /** Stable identifier used in the settings: the file (or directory) name. */ - public String id() { - return id; - } - - public String name() { - return name; - } - - /** @return the pack's zip or directory, or {@code null} for one shipped with the client */ - public File source() { - return source; - } - - /** Whether missing icons should be looked up in the default pack, as the pack asks. */ - public boolean fallsBack() { - return fallback; - } - - /** All icon keys this pack can draw, sorted. */ - public List keys() { - return new ArrayList<>(new TreeSet<>(entries.keySet())); - } - - public boolean has(String key) { - return entries.containsKey(normalizeKey(key)); - } - - /** - * Reads the image for an icon. - * - * @param key a TeamSpeak icon key, e.g. {@code CHANNEL_GREEN} - * @param preferredSize the size it will be drawn at, so packs holding several - * resolutions can pick the closest one - * @return the image bytes (PNG or SVG), or {@code null} if the pack has no such icon - */ - public byte[] icon(String key, int preferredSize) { - Entry entry = select(entries.get(normalizeKey(key)), preferredSize); - if (entry == null) return null; - try { - return storage.read(entry.path()); - } catch (IOException e) { - return null; - } - } - - /** @return whether the icon's image is vector art the frontend has to rasterise */ - public boolean isVector(String key, int preferredSize) { - Entry entry = select(entries.get(normalizeKey(key)), preferredSize); - return entry != null && entry.path().toLowerCase(Locale.ROOT).endsWith(".svg"); - } - - @Override - public String toString() { - return name; - } - - /** The smallest image that still covers the wanted size, else the largest one. */ - private static Entry select(List candidates, int preferredSize) { - if (candidates == null || candidates.isEmpty()) return null; - for (Entry e : candidates) { - if (e.size() == 0 || e.size() >= preferredSize) return e; - } - return candidates.get(candidates.size() - 1); - } - - /** - * Sets the colour vector art paints with {@code currentColor}, as a stylesheet's - * {@code color} would. - * - * @param rgb the colour as {@code 0xRRGGBB} - */ - public static byte[] withCurrentColor(byte[] svg, int rgb) { - String text = new String(svg, StandardCharsets.UTF_8); - if (!text.contains("currentColor")) return svg; - return text.replace("currentColor", String.format("#%06X", rgb & 0xFFFFFF)).getBytes(StandardCharsets.UTF_8); - } - - private static String normalizeKey(String key) { - return key == null ? "" : key.trim().toUpperCase(Locale.ROOT); - } - - // ---- loading ---- - - /** - * Reads a pack from a {@code .zip} file or from a directory holding its contents. - * - * @return the pack, or {@code null} when it holds no icons - */ - public static IconPack load(File source) { - if (source == null) return null; - boolean zipped = source.isFile(); - if (!zipped && !source.isDirectory()) return null; - - Map files = zipped ? listZip(source) : listDirectory(source); - if (files == null || files.isEmpty()) return null; - Storage storage = zipped ? path -> readFromZip(source, path) : path -> readFromDirectory(source, path); - return create(source.getName(), source, files, storage); - } - - /** - * Reads a pack's {@code .zip} shipped on the classpath, held in memory as it cannot be - * opened as a file there. - * - * @param resource the zip, e.g. {@code /gfx/teamspeak/default.zip} - * @return the pack, or {@code null} when it is not there or holds no icons - */ - public static IconPack loadZipResource(String resource) { - Map contents = new LinkedHashMap<>(); - try (InputStream in = IconPack.class.getResourceAsStream(resource)) { - if (in == null) return null; - try (ZipInputStream zip = new ZipInputStream(in)) { - for (ZipEntry e; (e = zip.getNextEntry()) != null; ) { - if (!e.isDirectory()) contents.put(e.getName(), zip.readAllBytes()); - } - } - } catch (IOException e) { - return null; - } - Map files = new LinkedHashMap<>(); - contents.forEach((path, data) -> files.put(path, (long) data.length)); - return create(resource.substring(resource.lastIndexOf('/') + 1), null, files, contents::get); - } - - private static IconPack create(String id, File source, Map files, Storage storage) { - String iniPath = files.keySet().stream() - .filter(p -> p.equalsIgnoreCase(INI)) - .findFirst().orElse(null); - Map mapping = new LinkedHashMap<>(); - Map info = new LinkedHashMap<>(); - boolean fallback = true; - if (iniPath != null) { - byte[] ini = read(storage, iniPath); - if (ini != null) fallback = parseIni(ini, mapping, info); - } - - Map> entries = iniPath != null - ? fromMapping(mapping, files) - : byConvention(files); - if (entries.isEmpty()) return null; - - String name = info.getOrDefault("name", displayName(id)); - return new IconPack(id, source, name, storage, fallback, entries); - } - - /** - * Reads a pack shipped on the classpath. As a classpath folder cannot be listed, - * the pack needs a {@code settings.ini}, whose file names must match exactly. - * - * @param id the pack's identifier in the settings - * @param resource the folder holding it, e.g. {@code /gfx/material} - * @return the pack, or {@code null} when it is not there - */ - public static IconPack loadResource(String id, String resource) { - Storage storage = path -> { - try (InputStream in = IconPack.class.getResourceAsStream(resource + '/' + path)) { - return in == null ? null : in.readAllBytes(); - } - }; - byte[] ini = read(storage, INI); - if (ini == null) return null; - Map mapping = new LinkedHashMap<>(); - Map info = new LinkedHashMap<>(); - boolean fallback = parseIni(ini, mapping, info); - - Map> entries = new LinkedHashMap<>(); - for (Map.Entry e : mapping.entrySet()) { - entries.put(e.getKey(), List.of(new Entry(e.getValue(), 0))); - } - if (entries.isEmpty()) return null; - return new IconPack(id, null, info.getOrDefault("name", displayName(id)), storage, fallback, entries); - } - - /** Turns {@code default_colored_2014.zip} into {@code Default Colored 2014}. */ - private static String displayName(String fileName) { - String base = fileName.toLowerCase(Locale.ROOT).endsWith(".zip") - ? fileName.substring(0, fileName.length() - 4) : fileName; - StringBuilder out = new StringBuilder(); - for (String word : base.split("[_\\-\\s]+")) { - if (word.isEmpty()) continue; - if (out.length() > 0) out.append(' '); - out.append(Character.toUpperCase(word.charAt(0))).append(word.substring(1)); - } - return out.length() == 0 ? fileName : out.toString(); - } - - /** @return the pack's FALLBACK option */ - private static boolean parseIni(byte[] data, Map mapping, Map info) { - boolean fallback = true; - try (BufferedReader in = new BufferedReader( - new InputStreamReader(new java.io.ByteArrayInputStream(data), StandardCharsets.UTF_8))) { - String section = ""; - String line; - while ((line = in.readLine()) != null) { - String trimmed = line.trim(); - if (trimmed.isEmpty() || trimmed.startsWith("#") || trimmed.startsWith(";")) continue; - if (trimmed.startsWith("[") && trimmed.endsWith("]")) { - section = trimmed.substring(1, trimmed.length() - 1).trim().toLowerCase(Locale.ROOT); - continue; - } - int eq = trimmed.indexOf('='); - if (eq < 0) continue; - String key = trimmed.substring(0, eq).trim(); - String value = trimmed.substring(eq + 1).trim(); - switch (section) { - case "gfxfiles" -> { - if (!value.isEmpty()) mapping.put(normalizeKey(key), value); - } - case "info" -> info.put(key.toLowerCase(Locale.ROOT), value); - case "options" -> { - if (key.equalsIgnoreCase("FALLBACK")) fallback = !value.equalsIgnoreCase("false"); - } - default -> { - } - } - } - } catch (IOException ignored) { - } - return fallback; - } - - private static Map> fromMapping(Map mapping, Map files) { - Map> entries = new LinkedHashMap<>(); - for (Map.Entry e : mapping.entrySet()) { - String path = resolve(e.getValue(), files); - if (path != null) entries.put(e.getKey(), List.of(new Entry(path, 0))); - } - return entries; - } - - /** - * Legacy packs (and the extra files of newer ones) are keyed by their name: - * {@code 16x16_connect.png} serves {@code CONNECT}, as does {@code 32x32_connect.png} - * when no smaller one exists. - */ - private static Map> byConvention(Map files) { - Map> entries = new LinkedHashMap<>(); - for (String path : files.keySet()) { - int dot = path.lastIndexOf('.'); - if (dot < 0 || path.indexOf('/') >= 0) continue; - String ext = path.substring(dot + 1).toLowerCase(Locale.ROOT); - if (!ext.equals("png") && !ext.equals("svg")) continue; - - String base = path.substring(0, dot); - int size = 0; - Matcher m = SIZED.matcher(base); - if (m.matches()) { - size = Integer.parseInt(m.group(1)); - base = m.group(3); - } - entries.computeIfAbsent(normalizeKey(base), k -> new ArrayList<>()).add(new Entry(path, size)); - } - for (List candidates : entries.values()) { - candidates.sort((a, b) -> Integer.compare(a.size(), b.size())); - } - return entries; - } - - /** Pack authors write file names as they see them, so a mismatched case is retried. */ - private static String resolve(String fileName, Map files) { - if (files.containsKey(fileName)) return fileName; - for (String path : files.keySet()) { - if (path.equalsIgnoreCase(fileName)) return path; - } - return null; - } - - private static byte[] read(Storage storage, String path) { - try { - return storage.read(path); - } catch (IOException e) { - return null; - } - } - - private static byte[] readFromZip(File zipFile, String path) throws IOException { - try (ZipFile zip = new ZipFile(zipFile)) { - ZipEntry entry = zip.getEntry(path); - if (entry == null) return null; - try (InputStream in = zip.getInputStream(entry)) { - return in.readAllBytes(); - } - } - } - - private static byte[] readFromDirectory(File dir, String path) throws IOException { - File file = new File(dir, path); - return file.isFile() ? Files.readAllBytes(file.toPath()) : null; - } - - private static Map listZip(File file) { - if (!file.getName().toLowerCase(Locale.ROOT).endsWith(".zip")) return null; - Map files = new LinkedHashMap<>(); - try (ZipFile zip = new ZipFile(file)) { - zip.stream().filter(e -> !e.isDirectory()).forEach(e -> files.put(e.getName(), e.getSize())); - } catch (IOException e) { - return null; - } - return files; - } - - private static Map listDirectory(File dir) { - Map files = new LinkedHashMap<>(); - File[] children = dir.listFiles(File::isFile); - if (children == null) return files; - for (File f : children) files.put(f.getName(), f.length()); - return files; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/gfx/IconPacks.java b/ts3-client/core/src/main/java/com/ts3client/gfx/IconPacks.java deleted file mode 100644 index 111b0b5..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/gfx/IconPacks.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.ts3client.gfx; - -import com.ts3client.config.InstallDirs; - -import java.io.File; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -/** - * Finds the icon packs installed on this machine: the client's own {@code gfx/} - * folder, an extra folder the user configured, and the {@code gfx/} folder of an - * installed TeamSpeak 3 client (whose packs are usable as they are, see - * {@link IconPack}) — plus the Material pack the client ships. - */ -public final class IconPacks { - - /** The pack every other one falls back to, as TeamSpeak does. */ - public static final String DEFAULT_ID = "default.zip"; - /** The pack shipped with the client, drawn from Google's Material icons. */ - public static final String MATERIAL_ID = "material"; - - /** TeamSpeak's own packs, which the build ships when it finds a TeamSpeak 3 client to take them from. */ - private static final List TEAMSPEAK_IDS = - List.of(DEFAULT_ID, "default_colored_2014.zip", "default_mono_2014.zip"); - private static final String TEAMSPEAK_RESOURCE = "/gfx/teamspeak/"; - - private static volatile IconPack material; - private static volatile List teamspeak; - - private IconPacks() { - } - - /** - * Loads every pack found under {@code extraDirectory} and the well-known - * locations, the first search root winning on a name clash, then the shipped - * ones the folders did not have. - * - * @param userDirectory the client's own pack folder (may not exist yet) - * @param extraDirectory an additional folder chosen by the user, or {@code null} - * @return the packs, ordered by display name - */ - public static List findAll(File userDirectory, String extraDirectory) { - Map byId = new LinkedHashMap<>(); - for (File root : InstallDirs.searchRoots("gfx", userDirectory, extraDirectory)) { - File[] children = root.listFiles(); - if (children == null) continue; - for (File child : children) { - if (child.isFile() && !child.getName().toLowerCase(Locale.ROOT).endsWith(".zip")) continue; - if (byId.containsKey(child.getName())) continue; - IconPack pack = IconPack.load(child); - if (pack != null) byId.put(pack.id(), pack); - } - } - for (IconPack shipped : teamspeak()) byId.putIfAbsent(shipped.id(), shipped); - IconPack shipped = material(); - if (shipped != null) byId.putIfAbsent(shipped.id(), shipped); - List packs = new ArrayList<>(byId.values()); - packs.sort(Comparator.comparing(p -> p.name().toLowerCase(Locale.ROOT))); - return packs; - } - - /** @return the Material pack, or {@code null} if the build left it out */ - public static IconPack material() { - if (material == null) material = IconPack.loadResource(MATERIAL_ID, "/gfx/material"); - return material; - } - - /** @return TeamSpeak's packs the build shipped, which a pack of the same name found on disk replaces */ - public static List teamspeak() { - if (teamspeak == null) { - List packs = new ArrayList<>(); - for (String id : TEAMSPEAK_IDS) { - IconPack pack = IconPack.loadZipResource(TEAMSPEAK_RESOURCE + id); - if (pack != null) packs.add(pack); - } - teamspeak = List.copyOf(packs); - } - return teamspeak; - } - - /** @return the pack with this id, or {@code null} when it is not installed */ - public static IconPack select(List packs, String id) { - for (IconPack p : packs) { - if (p.id().equals(id)) return p; - } - return null; - } - - /** - * The packs to look an icon up in, in turn: the active one, TeamSpeak's - * {@code default.zip} if the active pack asks for it, then {@code lastResort}. - * - * @param active the chosen pack, or {@code null} for none - * @param lastResort the pack for whatever is still missing, or {@code null} - */ - public static List lookupOrder(IconPack active, List packs, IconPack lastResort) { - List order = new ArrayList<>(3); - if (active != null) order.add(active); - IconPack fallback = select(packs, DEFAULT_ID); - if (active != null && active.fallsBack() && fallback != null && !order.contains(fallback)) order.add(fallback); - if (lastResort != null && !order.contains(lastResort)) order.add(lastResort); - return order; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/hotkey/GlobalInputHook.java b/ts3-client/core/src/main/java/com/ts3client/hotkey/GlobalInputHook.java deleted file mode 100644 index 8ded28c..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/hotkey/GlobalInputHook.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.ts3client.hotkey; - -/** - * A system-wide source of key and mouse-button events: it reports every press and - * release on the machine, whether or not the client has focus, and without swallowing - * the event on its way to the focused application. - * - *

Implementations are platform code and live outside the core; the core only ever - * sees this interface. - */ -public interface GlobalInputHook extends AutoCloseable { - - interface Listener { - /** - * @param key the key or button - * @param pressed {@code true} for a press, {@code false} for a release - */ - void onInput(HotkeyKey key, boolean pressed); - } - - /** Starts delivering events on a background thread. */ - void start(Listener listener); - - /** Whether events are actually being delivered; false when the platform refused. */ - boolean isRunning(); - - /** Why the hook is not running, for the options dialog to show; empty when it is. */ - String unavailableReason(); - - /** - * The name this system's layout gives a key, or {@code null} to let the caller fall - * back to {@link HotkeyKey#fallbackName()}. - */ - String keyName(HotkeyKey key); - - @Override - void close(); -} diff --git a/ts3-client/core/src/main/java/com/ts3client/hotkey/Hotkey.java b/ts3-client/core/src/main/java/com/ts3client/hotkey/Hotkey.java deleted file mode 100644 index 7307ffd..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/hotkey/Hotkey.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.ts3client.hotkey; - -/** - * A single binding: which combination triggers which action, on which edge of the - * keypress, and whether it reaches only the active server or every connected one. - */ -public final class Hotkey { - - /** Which edge of the key press runs the action, as TS3's hotkey mode combo box offers. */ - public enum Trigger { - /** Action triggers when the key is pressed down. */ - KEY_DOWN("On key down"), - /** Action triggers when the key is released. */ - KEY_UP("On key up"); - - private final String label; - - Trigger(String label) { - this.label = label; - } - - public String label() { - return label; - } - } - - public HotkeyAction action; - public HotkeyCombo combo; - public Trigger trigger = Trigger.KEY_DOWN; - /** Apply to the active server only; when false the action reaches every connection. */ - public boolean activeServerOnly = true; - /** Meaning depends on {@link HotkeyAction#argument()}; empty when the action takes none. */ - public String argument = ""; - public boolean enabled = true; - - public Hotkey() { - } - - public Hotkey(HotkeyAction action, HotkeyCombo combo) { - this.action = action; - this.combo = combo; - } - - /** - * The binding's place in the action tree, as TS3 spells it out: - * {@code Sounds / Activate Soundpack / Default Sound Pack (Male)}. - */ - public String path() { - if (action == null) return ""; - StringBuilder sb = new StringBuilder(); - if (!action.group().isEmpty()) sb.append(action.group()).append(" / "); - sb.append(action.label()); - if (argument != null && !argument.isBlank()) sb.append(" / ").append(argument.trim()); - return sb.toString(); - } - - public boolean isValid() { - return action != null && combo != null && !combo.isEmpty(); - } - - /** Whether the action is a per-server one, for which {@link #activeServerOnly} matters. */ - public boolean isServerScoped() { - return action != null && action.category() != HotkeyAction.Category.MISC; - } - - public Hotkey copy() { - Hotkey h = new Hotkey(action, combo); - h.trigger = trigger; - h.activeServerOnly = activeServerOnly; - h.argument = argument; - h.enabled = enabled; - return h; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/hotkey/HotkeyAction.java b/ts3-client/core/src/main/java/com/ts3client/hotkey/HotkeyAction.java deleted file mode 100644 index 7746d02..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/hotkey/HotkeyAction.java +++ /dev/null @@ -1,366 +0,0 @@ -package com.ts3client.hotkey; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * The catalogue of hotkey actions, reverse-engineered from the official TeamSpeak 3 - * client (its hotkey dialog builds exactly this list, in this order). - * - *

Every entry keeps the identifiers TS3 itself uses — a numeric action type and a - * parameter keyword — so bindings stay recognisable and could be imported from, or - * exported to, the original client. {@link #supported()} tells whether this client - * can actually carry the action out; the rest are listed but greyed out. - * - *

{@link #advanced()} mirrors the dialog's "Show Advanced Actions" checkbox: TS3 - * hides all but a handful of everyday actions until it is ticked. - */ -public enum HotkeyAction { - - // ----- Server ----- - CONNECT_CURRENT_TAB(Category.SERVER, 0x0010, "Server (current tab)", - "Connect to Server on Current Tab", false, Argument.BOOKMARK, true), - CONNECT_NEW_TAB(Category.SERVER, 0x0010, "Server (new tab)", - "Connect to Server in a New Tab", false, Argument.BOOKMARK, true), - DISCONNECT_CURRENT(Category.SERVER, 0x0020, "Current Server", - "Disconnect from Current Server", false, Argument.NONE, true), - DISCONNECT_ALL(Category.SERVER, 0x0020, "All Servers", - "Disconnect from All Servers", false, Argument.NONE, true), - - MIC_ACTIVATE(Category.SERVER, 0x0030, "Activate", - "Activate Microphone (current tab)", true, Argument.NONE, true), - MIC_MUTE(Category.SERVER, 0x0030, "Mute", - "Mute Microphone", true, Argument.NONE, true), - MIC_UNMUTE(Category.SERVER, 0x0030, "Unmute", - "Unmute Microphone", true, Argument.NONE, true), - MIC_TOGGLE(Category.SERVER, 0x0030, "Toggle", - "Toggle Microphone Mute", false, Argument.NONE, true), - /** - * TS3's "local" mute silences capture without publishing a mute status, or playing - * a mute/unmute sound — unlike {@link #MIC_MUTE}. - */ - MIC_LOCAL_UNMUTE(Category.SERVER, 0x0030, "ActivateLocalMute", - "Disable Local Mic Mute", true, Argument.NONE, true), - MIC_LOCAL_MUTE(Category.SERVER, 0x0030, "DeactivateLocalMute", - "Enable Local Mic Mute", true, Argument.NONE, true), - MIC_LOCAL_TOGGLE(Category.SERVER, 0x0030, "ToggleLocalMute", - "Toggle Local Mic Mute", true, Argument.NONE, true), - - SPEAKER_MUTE(Category.SERVER, 0x0040, "Mute", - "Mute Speaker", true, Argument.NONE, true), - SPEAKER_UNMUTE(Category.SERVER, 0x0040, "Unmute", - "Unmute Speaker", true, Argument.NONE, true), - SPEAKER_TOGGLE(Category.SERVER, 0x0040, "Toggle", - "Toggle Speaker Mute", false, Argument.NONE, true), - - AWAY_SET(Category.SERVER, 0x0050, "SetAway", - "Set Away", true, Argument.NONE, true), - AWAY_ONLINE(Category.SERVER, 0x0050, "SetOnline", - "Set Online", true, Argument.NONE, true), - AWAY_TOGGLE(Category.SERVER, 0x0050, "Toggle", - "Toggle Away Status", false, Argument.NONE, true), - AWAY_TOGGLE_WITH_MESSAGE(Category.SERVER, 0x0050, "Toggle With Message", - "Toggle Away Status with Message", true, Argument.TEXT, true), - - COMMANDER_ACTIVATE(Category.SERVER, 0x0100, "Activate", - "Activate Channel Commander", true, Argument.NONE, true), - COMMANDER_DEACTIVATE(Category.SERVER, 0x0100, "Deactivate", - "Deactivate Channel Commander", true, Argument.NONE, true), - COMMANDER_TOGGLE(Category.SERVER, 0x0100, "Toggle", - "Toggle Channel Commander", true, Argument.NONE, true), - - // ----- Self ----- - CAPTURE_PROFILE_ACTIVATE(Category.SELF, 0x0110, "Activate", - "Activate Capture Profile", true, Argument.PROFILE, false), - CAPTURE_PROFILE_DEACTIVATE(Category.SELF, 0x0110, "Deactivate", - "Deactivate Capture Profile", true, Argument.PROFILE, false), - CAPTURE_PROFILE_TOGGLE(Category.SELF, 0x0110, "Toggle", - "Toggle Capture Profile", true, Argument.PROFILE, false), - PLAYBACK_PROFILE_ACTIVATE(Category.SELF, 0x0120, "Activate", - "Activate Playback Profile", true, Argument.PROFILE, false), - PLAYBACK_PROFILE_DEACTIVATE(Category.SELF, 0x0120, "Deactivate", - "Deactivate Playback Profile", true, Argument.PROFILE, false), - PLAYBACK_PROFILE_TOGGLE(Category.SELF, 0x0120, "Toggle", - "Toggle Playback Profile", true, Argument.PROFILE, false), - HOTKEY_PROFILE_ACTIVATE(Category.SELF, 0x0130, "Activate", - "Activate Hotkey Profile", true, Argument.PROFILE, false), - HOTKEY_PROFILE_DEACTIVATE(Category.SELF, 0x0130, "Deactivate", - "Deactivate Hotkey Profile", true, Argument.PROFILE, false), - - PTT_ACTIVATE(Category.SELF, 0x0140, "Activate", - "Activate Push-to-Talk", false, Argument.NONE, true, true), - PTT_DEACTIVATE(Category.SELF, 0x0140, "Deactivate", - "Deactivate Push-to-Talk", true, Argument.NONE, true), - PTT_TOGGLE(Category.SELF, 0x0140, "Toggle", - "Toggle Push-to-Talk", true, Argument.NONE, true), - - CHANNEL_SWITCH(Category.SELF, 0x0150, "Strict Channel", - "Switch to Channel", true, Argument.CHANNEL, true), - CHANNEL_NEXT(Category.SELF, 0x0150, "Next Channel", - "Switch to Next Channel (Global)", true, Argument.NONE, false), - CHANNEL_PREVIOUS(Category.SELF, 0x0150, "Previous Channel", - "Switch to Previous Channel (Global)", true, Argument.NONE, false), - CHANNEL_LAST_VISITED(Category.SELF, 0x0150, "Last Visited Channel", - "Switch to Last Visited Channel", true, Argument.NONE, false), - CHANNEL_NEXT_FAMILY(Category.SELF, 0x0150, "Next Channel Family", - "Switch to Next Channel (Channel Family)", true, Argument.NONE, false), - CHANNEL_PREVIOUS_FAMILY(Category.SELF, 0x0150, "Previous Channel Family", - "Switch to Previous Channel (Channel Family)", true, Argument.NONE, false), - CHANNEL_NEXT_LEVEL(Category.SELF, 0x0150, "Next Channel Level", - "Switch to Next Channel (Same Level)", true, Argument.NONE, false), - CHANNEL_PREVIOUS_LEVEL(Category.SELF, 0x0150, "Previous Channel Level", - "Switch to Previous Channel (Same Level)", true, Argument.NONE, false), - - SERVER_TAB_SELECT(Category.SELF, 0x0160, "Strict Server", - "Select Server Tab", true, Argument.TEXT, true), - SERVER_TAB_NEXT(Category.SELF, 0x0160, "Next Server", - "Select Next Server Tab", true, Argument.NONE, true), - SERVER_TAB_PREVIOUS(Category.SELF, 0x0160, "Previous Server", - "Select Previous Server Tab", true, Argument.NONE, true), - - SOUNDPACK_ACTIVATE(Category.SELF, 0x0170, "Activate", - "Activate Soundpack", true, Argument.PROFILE, false), - SOUND_MUTE(Category.SELF, 0x0170, "Mute", - "Mute Sounds", true, Argument.NONE, true), - SOUND_UNMUTE(Category.SELF, 0x0170, "Unmute", - "Unmute Sounds", true, Argument.NONE, true), - SOUND_TOGGLE(Category.SELF, 0x0170, "Toggle", - "Toggle Sound Mute", true, Argument.NONE, true), - - WHISPER_PUSH_ACTIVATE(Category.SELF, 0x0180, "ActivatePushToWhisper", - "Activate Push-To-Whisper", true, Argument.TEXT, false, true), - WHISPER_PUSH_DEACTIVATE(Category.SELF, 0x0180, "DeactivatePushToWhisper", - "Deactivate Push-To-Whisper", true, Argument.TEXT, false), - WHISPER_REPLY_PUSH_ACTIVATE(Category.SELF, 0x0180, "ActivateReplyPushToWhisper", - "Activate Push-To-Reply to a Whisper", true, Argument.NONE, false, true), - WHISPER_REPLY_PUSH_DEACTIVATE(Category.SELF, 0x0180, "DeactivateReplyPushToWhisper", - "Deactivate Push-To-Reply to a Whisper", true, Argument.NONE, false), - WHISPERLIST_ACTIVATE(Category.SELF, 0x0180, "Activate", - "Activate Whisperlist", true, Argument.TEXT, false), - WHISPERLIST_DEACTIVATE(Category.SELF, 0x0180, "Deactivate", - "Deactivate Whisperlist", true, Argument.TEXT, false), - WHISPER_REPLY_ACTIVATE(Category.SELF, 0x0180, "ActivateReply", - "Activate Reply to a Whisper", true, Argument.NONE, false), - WHISPER_REPLY_DEACTIVATE(Category.SELF, 0x0180, "DeactivateReply", - "Deactivate Reply to a Whisper", true, Argument.NONE, false), - WHISPER_BLOCK_ACTIVATE(Category.SELF, 0x0180, "ActivateBlock", - "Activate Block Incoming Whispers", true, Argument.NONE, false), - WHISPER_BLOCK_DEACTIVATE(Category.SELF, 0x0180, "DeactivateBlock", - "Deactivate Block Incoming Whispers", true, Argument.NONE, false), - WHISPER_BLOCK_TOGGLE(Category.SELF, 0x0180, "ToggleBlock", - "Toggle Block Incoming Whispers", true, Argument.NONE, false), - - RECORDING_START(Category.SELF, 0x01c0, "Activate", - "Start Recording", true, Argument.NONE, false), - RECORDING_START_MULTITRACK(Category.SELF, 0x01c0, "ActivateMT", - "Start Multitrack Recording", true, Argument.NONE, false), - RECORDING_STOP(Category.SELF, 0x01c0, "Deactivate", - "Stop Recording", true, Argument.NONE, false), - - VOLUME_INCREASE(Category.SELF, 0x01e0, "Increase", - "Increase Master Volume", true, Argument.NONE, true), - VOLUME_DECREASE(Category.SELF, 0x01e0, "Decrease", - "Decrease Master Volume", true, Argument.NONE, true), - - PLUGIN_ACTIVATE(Category.SELF, 0x01f0, "Activate", - "Activate Plugin", true, Argument.TEXT, false), - PLUGIN_DEACTIVATE(Category.SELF, 0x01f0, "Deactivate", - "Deactivate Plugin", true, Argument.TEXT, false), - PLUGIN_TOGGLE(Category.SELF, 0x01f0, "Toggle", - "Toggle Plugin", true, Argument.TEXT, false), - PLUGIN_COMMAND(Category.SELF, 0x01f0, "Run", - "Run Plugin Command", true, Argument.TEXT, false), - PLUGIN_HOTKEY(Category.SELF, 0x01f0, "Hotkey", - "Plugin Hotkey", true, Argument.TEXT, false), - - SERVER_GROUP_ASSIGN(Category.SELF, 0x0270, "AssignSG", - "Assign Server Group", true, Argument.TEXT, false), - SERVER_GROUP_REVOKE(Category.SELF, 0x0270, "RevokeSG", - "Revoke Server Group", true, Argument.TEXT, false), - SERVER_GROUP_TOGGLE(Category.SELF, 0x0270, "ToggleSG", - "Toggle Server Group", true, Argument.TEXT, false), - - STYLESHEET_HELPER_ON(Category.SELF, 0x0240, "Activate", - "Stylesheet Helper (on)", true, Argument.NONE, false), - STYLESHEET_HELPER_OFF(Category.SELF, 0x0240, "Deactivate", - "Stylesheet Helper (off)", true, Argument.NONE, false), - - SOUND_3D_ACTIVATE(Category.SELF, 0x0250, "Activate", - "Activate 3D Sound", true, Argument.NONE, false), - SOUND_3D_DEACTIVATE(Category.SELF, 0x0250, "Deactivate", - "Deactivate 3D Sound", true, Argument.NONE, false), - SOUND_3D_TOGGLE(Category.SELF, 0x0250, "Toggle", - "Toggle 3D Sound", true, Argument.NONE, false), - - NICKNAME_CHANGE(Category.SELF, 0x01a0, "Rename", - "Change Nickname", true, Argument.TEXT, true), - - // ----- Misc ----- - TALK_POWER_GRANT_NEXT(Category.MISC, 0x01b0, "GrantNextTalkPower", - "Grant Next User Talk Power", true, Argument.NONE, false), - TALK_POWER_REQUEST(Category.MISC, 0x01b0, "RequestTalkPower", - "Request Talk Power", true, Argument.NONE, false), - TALK_POWER_REVOKE_ALL_GRANT_NEXT(Category.MISC, 0x01b0, "RevokeAllAndGrantNext", - "Revoke All And Grant Next User Talk Power", true, Argument.NONE, false), - - FILEBROWSER(Category.MISC, 0x01d0, "Filebrowser", - "Open Filebrowser on Channel", true, Argument.NONE, true), - AUTOCONNECT_DISABLE(Category.MISC, 0x0200, "Autoconnect", - "Disable Autoconnect", true, Argument.NONE, false), - SKIN_RELOAD(Category.MISC, 0x0210, "SkinReload", - "Reload Skin", true, Argument.NONE, true), - BRING_TO_FRONT(Category.MISC, 0x0220, "Bring2Front", - "Bring Client to Front", true, Argument.NONE, true), - SEND_TO_BACK(Category.MISC, 0x0230, "Send2Back", - "Send Client to Background", true, Argument.NONE, true); - - /** The three groups the TS3 hotkey dialog separates its list into. */ - public enum Category { - SERVER("Server"), - SELF("Self"), - MISC("Misc"); - - private final String label; - - Category(String label) { - this.label = label; - } - - public String label() { - return label; - } - } - - /** - * The group an action's type belongs to in TeamSpeak's hotkey tree, taken from the - * table its dialog builds. Types absent here are ungrouped: TS3 shows them as a - * single item directly under their category. - */ - private static final Map GROUPS = Map.ofEntries( - Map.entry(0x0010, "Connect to Server"), - Map.entry(0x0020, "Disconnect from Server"), - Map.entry(0x0030, "Microphone"), - Map.entry(0x0040, "Speaker"), - Map.entry(0x0050, "Away Status"), - Map.entry(0x0100, "Channel Commander"), - Map.entry(0x0110, "Capture Profile"), - Map.entry(0x0120, "Playback Profile"), - Map.entry(0x0130, "Hotkey Profile"), - Map.entry(0x0140, "Push-to-Talk"), - Map.entry(0x0150, "Switch to Channel"), - Map.entry(0x0160, "Select Server Tab"), - Map.entry(0x0170, "Sounds"), - Map.entry(0x0180, "Whisper"), - Map.entry(0x01b0, "Talk Power"), - Map.entry(0x01c0, "Recording"), - Map.entry(0x01e0, "Master Volume"), - Map.entry(0x01f0, "Plugins"), - Map.entry(0x0250, "3D Sound"), - Map.entry(0x0270, "Permissions")); - - /** What the action's free-text parameter means, when it takes one. */ - public enum Argument { - NONE, - /** Label of a bookmark to connect to. */ - BOOKMARK, - /** Channel path, "/"-separated. */ - CHANNEL, - /** Name of a capture/playback/hotkey profile or sound pack. */ - PROFILE, - /** Anything else: nickname, away message, tab number, plugin command. */ - TEXT - } - - private final Category category; - private final int type; - private final String parameter; - private final String label; - private final boolean advanced; - private final Argument argument; - private final boolean supported; - private final boolean momentary; - - HotkeyAction(Category category, int type, String parameter, String label, - boolean advanced, Argument argument, boolean supported) { - this(category, type, parameter, label, advanced, argument, supported, false); - } - - HotkeyAction(Category category, int type, String parameter, String label, - boolean advanced, Argument argument, boolean supported, boolean momentary) { - this.category = category; - this.type = type; - this.parameter = parameter; - this.label = label; - this.advanced = advanced; - this.argument = argument; - this.supported = supported; - this.momentary = momentary; - } - - public Category category() { - return category; - } - - /** TS3's numeric action type; actions sharing one differ only by {@link #parameter()}. */ - public int type() { - return type; - } - - /** - * The node this action hangs under in the hotkey tree ("Sounds", "Microphone", …), - * or an empty string for the actions TS3 lists on their own. - */ - public String group() { - return GROUPS.getOrDefault(type, ""); - } - - /** TS3's parameter keyword, e.g. {@code Toggle} or {@code ActivateReply}. */ - public String parameter() { - return parameter; - } - - /** The name shown in the hotkey list. */ - public String label() { - return label; - } - - /** Hidden until "Show advanced actions" is ticked, as in TS3. */ - public boolean advanced() { - return advanced; - } - - public Argument argument() { - return argument; - } - - /** Whether this client implements the action; unsupported ones cannot be bound. */ - public boolean supported() { - return supported; - } - - /** - * Whether the action lasts only while the hotkey is held (push-to-talk and the - * push-to-whisper variants), in which case the trigger setting does not apply and - * the release is reported as well. - */ - public boolean momentary() { - return momentary; - } - - public static List of(Category category, boolean includeAdvanced) { - List out = new ArrayList<>(); - for (HotkeyAction a : values()) { - if (a.category == category && (includeAdvanced || !a.advanced)) out.add(a); - } - return out; - } - - /** Looks an action up by its enum name, falling back to {@code null}. */ - public static HotkeyAction byName(String name) { - for (HotkeyAction a : values()) { - if (a.name().equals(name)) return a; - } - return null; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/hotkey/HotkeyCombo.java b/ts3-client/core/src/main/java/com/ts3client/hotkey/HotkeyCombo.java deleted file mode 100644 index 742238a..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/hotkey/HotkeyCombo.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.ts3client.hotkey; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Set; -import java.util.function.Function; - -/** - * A key combination: one key or button, or several that have to be held together. - * There is no distinguished modifier — as in TS3, any key can take that role, and the - * combination fires once every one of its keys is down. - */ -public final class HotkeyCombo { - - /** Recording order, which is also the order the combination is displayed in. */ - private final List keys; - - public HotkeyCombo(Collection keys) { - List copy = new ArrayList<>(); - for (HotkeyKey k : keys) { - if (k != null && !copy.contains(k)) copy.add(k); - } - this.keys = Collections.unmodifiableList(copy); - } - - public List keys() { - return keys; - } - - public boolean isEmpty() { - return keys.isEmpty(); - } - - public boolean contains(HotkeyKey key) { - return keys.contains(key); - } - - /** Whether every key of the combination is currently held down. */ - public boolean isSatisfiedBy(Set pressed) { - return !keys.isEmpty() && pressed.containsAll(keys); - } - - /** Serialised form, e.g. {@code Keyboard:37+Keyboard:45}. */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - for (HotkeyKey k : keys) { - if (sb.length() > 0) sb.append('+'); - sb.append(k); - } - return sb.toString(); - } - - public static HotkeyCombo parse(String text) { - List keys = new ArrayList<>(); - if (text != null && !text.isBlank()) { - for (String part : text.split("\\+")) { - HotkeyKey k = HotkeyKey.parse(part); - if (k != null) keys.add(k); - } - } - return new HotkeyCombo(keys); - } - - /** - * Renders the combination for the user, e.g. {@code Ctrl+Mouse 4}. - * - * @param namer resolves a key to its name on this system, typically from the - * keyboard layout; may return {@code null} to fall back - */ - public String display(Function namer) { - if (keys.isEmpty()) return "No hotkey assigned"; - StringBuilder sb = new StringBuilder(); - for (HotkeyKey k : keys) { - String name = namer == null ? null : namer.apply(k); - if (name == null || name.isBlank()) name = k.fallbackName(); - if (sb.length() > 0) sb.append(" + "); - sb.append(name); - } - return sb.toString(); - } - - @Override - public boolean equals(Object o) { - return o instanceof HotkeyCombo other && keys.equals(other.keys); - } - - @Override - public int hashCode() { - return keys.hashCode(); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/hotkey/HotkeyEngine.java b/ts3-client/core/src/main/java/com/ts3client/hotkey/HotkeyEngine.java deleted file mode 100644 index bac87cb..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/hotkey/HotkeyEngine.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.ts3client.hotkey; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; - -/** - * Turns the raw stream of global key events into hotkey activations: it tracks which - * keys are down, decides when a binding's combination becomes (or stops being) - * satisfied, and reports that on the configured edge. - * - *

While a {@link Recorder} is installed the engine records combinations instead of - * firing them, which is how the hotkey dialog captures a new binding without the old - * ones going off. - */ -public final class HotkeyEngine implements GlobalInputHook.Listener { - - /** Receives activations; called on the input hook's thread. */ - public interface Handler { - /** - * @param hotkey the binding that fired - * @param active {@code true} on activation; a {@code false} call follows on release - * for {@link HotkeyAction#momentary()} actions only - */ - void onHotkey(Hotkey hotkey, boolean active); - } - - /** Collects a combination as the user presses it, for the "set hotkey" button. */ - public interface Recorder { - /** The keys held so far, in press order; called on every change. */ - void onRecording(HotkeyCombo combo); - - /** The user let go of everything: this is the final combination. */ - void onRecorded(HotkeyCombo combo); - } - - private final Hotkeys hotkeys; - private final Handler handler; - - private final Set pressed = new LinkedHashSet<>(); - /** Bindings whose combination is currently held, so a release can end them. */ - private final Set active = new HashSet<>(); - - private volatile Recorder recorder; - private final Set recording = new LinkedHashSet<>(); - - public HotkeyEngine(Hotkeys hotkeys, Handler handler) { - this.hotkeys = hotkeys; - this.handler = handler; - } - - /** - * Diverts every event into {@code recorder} until {@link #stopRecording()}; the - * bindings themselves stay silent meanwhile. - */ - public void record(Recorder recorder) { - synchronized (this) { - recording.clear(); - releaseActive(); - pressed.clear(); - } - this.recorder = recorder; - } - - public void stopRecording() { - recorder = null; - synchronized (this) { - recording.clear(); - pressed.clear(); - } - } - - @Override - public void onInput(HotkeyKey key, boolean down) { - Recorder rec = recorder; - if (rec != null) { - recordKey(rec, key, down); - return; - } - - List fired = new ArrayList<>(); - synchronized (this) { - if (down) { - if (!pressed.add(key)) return; - } else if (!pressed.remove(key)) { - return; - } - - for (Hotkey h : hotkeys.all()) { - if (!h.enabled || !h.isValid() || !h.action.supported()) continue; - if (!h.combo.contains(key)) continue; - - boolean satisfied = h.combo.isSatisfiedBy(pressed); - if (satisfied && active.add(h)) { - if (h.action.momentary() || h.trigger == Hotkey.Trigger.KEY_DOWN) { - fired.add(() -> handler.onHotkey(h, true)); - } - } else if (!satisfied && active.remove(h)) { - if (h.action.momentary()) { - fired.add(() -> handler.onHotkey(h, false)); - } else if (h.trigger == Hotkey.Trigger.KEY_UP) { - fired.add(() -> handler.onHotkey(h, true)); - } - } - } - } - for (Runnable r : fired) r.run(); - } - - private void recordKey(Recorder rec, HotkeyKey key, boolean down) { - HotkeyCombo combo; - boolean finished; - synchronized (this) { - if (down) { - recording.add(key); - pressed.add(key); - } else { - pressed.remove(key); - } - combo = new HotkeyCombo(recording); - finished = !down && pressed.isEmpty() && !recording.isEmpty(); - if (finished) recording.clear(); - } - if (finished) { - rec.onRecorded(combo); - } else { - rec.onRecording(combo); - } - } - - /** Ends every held binding, so nothing stays stuck when the hook stops. */ - public void releaseAll() { - List fired = new ArrayList<>(); - synchronized (this) { - for (Hotkey h : active) { - if (h.action.momentary()) fired.add(() -> handler.onHotkey(h, false)); - } - active.clear(); - pressed.clear(); - } - for (Runnable r : fired) r.run(); - } - - private void releaseActive() { - for (Hotkey h : new ArrayList<>(active)) { - if (h.action.momentary()) handler.onHotkey(h, false); - } - active.clear(); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/hotkey/HotkeyKey.java b/ts3-client/core/src/main/java/com/ts3client/hotkey/HotkeyKey.java deleted file mode 100644 index a849856..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/hotkey/HotkeyKey.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.ts3client.hotkey; - -/** - * One physical key or mouse button. Keys are identified by their position rather than by - * the character they produce, so a binding is independent of the keyboard layout in force - * when it was recorded. - * - *

The keyboard numbering is whatever the platform's own is — X keycodes (Linux evdev - * code + 8) on X11, set-1 scan codes with the {@code E0}/{@code E1} escape in the high - * byte on Windows — because that is what its input API reports and its key-naming call - * expects. Bindings are therefore per-machine, which is also how TeamSpeak stores them. - * Mouse buttons are unified on the X numbering everywhere, side buttons included. - * - * @param device which input device the code belongs to - * @param code the platform's key code for {@link Device#KEYBOARD}, an X-style button - * number for {@link Device#MOUSE} - */ -public record HotkeyKey(HotkeyKey.Device device, int code) { - - public enum Device { - KEYBOARD("Keyboard"), - MOUSE("Mouse"); - - private final String prefix; - - Device(String prefix) { - this.prefix = prefix; - } - - String prefix() { - return prefix; - } - } - - public static HotkeyKey keyboard(int keycode) { - return new HotkeyKey(Device.KEYBOARD, keycode); - } - - public static HotkeyKey mouse(int button) { - return new HotkeyKey(Device.MOUSE, button); - } - - /** Serialised form, matching TS3's {@code Keyboard:9} / {@code Mouse:9} notation. */ - @Override - public String toString() { - return device.prefix() + ":" + code; - } - - public static HotkeyKey parse(String text) { - if (text == null) return null; - int colon = text.indexOf(':'); - if (colon <= 0) return null; - String prefix = text.substring(0, colon).trim(); - int code; - try { - code = Integer.parseInt(text.substring(colon + 1).trim()); - } catch (NumberFormatException e) { - return null; - } - for (Device d : Device.values()) { - if (d.prefix().equalsIgnoreCase(prefix)) return new HotkeyKey(d, code); - } - return null; - } - - /** - * A readable name that needs no help from the platform: mouse buttons carry the - * numbering users know them by, keys fall back to their raw code. - */ - public String fallbackName() { - if (device == Device.MOUSE) { - return switch (code) { - case 1 -> "Mouse Left"; - case 2 -> "Mouse Middle"; - case 3 -> "Mouse Right"; - case 4 -> "Wheel Up"; - case 5 -> "Wheel Down"; - case 6 -> "Wheel Left"; - case 7 -> "Wheel Right"; - // X hands the side buttons out as 8 and 9; everyone else calls them 4 and 5. - case 8 -> "Mouse 4"; - case 9 -> "Mouse 5"; - default -> "Mouse " + code; - }; - } - return "Key " + code; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/hotkey/Hotkeys.java b/ts3-client/core/src/main/java/com/ts3client/hotkey/Hotkeys.java deleted file mode 100644 index 31ca3c5..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/hotkey/Hotkeys.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.ts3client.hotkey; - -import com.ts3client.config.AppDirs; -import com.ts3client.config.ProfileFiles; - -import java.io.File; -import java.io.FileInputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Properties; - -/** - * The user's hotkey bindings, stored alongside the settings file. - * Frontend-agnostic: no UI dependencies. - */ -public final class Hotkeys { - - private static File file() { - return AppDirs.file("hotkeys.properties"); - } - - private final List entries = Collections.synchronizedList(new ArrayList<>()); - - /** The bindings as they are now; later changes do not show up in the returned list. */ - public List all() { - synchronized (entries) { - return List.copyOf(entries); - } - } - - public void add(Hotkey hotkey) { - entries.add(hotkey); - } - - public void set(int index, Hotkey hotkey) { - if (index >= 0 && index < entries.size()) entries.set(index, hotkey); - } - - public void remove(int index) { - if (index >= 0 && index < entries.size()) entries.remove(index); - } - - /** Replaces every binding at once, e.g. when the options dialog is applied. */ - public void replaceAll(List hotkeys) { - synchronized (entries) { - entries.clear(); - for (Hotkey h : hotkeys) { - if (h != null && h.isValid()) entries.add(h); - } - } - } - - public static Hotkeys load() { - Hotkeys h = new Hotkeys(); - if (!file().isFile()) return h; - Properties p = new Properties(); - try (FileInputStream in = new FileInputStream(file())) { - p.load(in); - } catch (Exception e) { - return h; - } - int count = parseInt(p.getProperty("count"), 0); - for (int i = 0; i < count; i++) { - String prefix = "hotkey." + i + "."; - HotkeyAction action = HotkeyAction.byName(p.getProperty(prefix + "action", "")); - if (action == null) continue; - Hotkey entry = new Hotkey(action, HotkeyCombo.parse(p.getProperty(prefix + "keys", ""))); - entry.trigger = "KEY_UP".equals(p.getProperty(prefix + "trigger")) - ? Hotkey.Trigger.KEY_UP : Hotkey.Trigger.KEY_DOWN; - entry.activeServerOnly = !"false".equals(p.getProperty(prefix + "activeServerOnly")); - entry.argument = p.getProperty(prefix + "argument", ""); - entry.enabled = !"false".equals(p.getProperty(prefix + "enabled")); - if (entry.isValid()) h.entries.add(entry); - } - return h; - } - - public void save() { - Properties p = new Properties(); - synchronized (entries) { - p.setProperty("count", Integer.toString(entries.size())); - for (int i = 0; i < entries.size(); i++) { - Hotkey e = entries.get(i); - String prefix = "hotkey." + i + "."; - p.setProperty(prefix + "action", e.action.name()); - p.setProperty(prefix + "keys", e.combo.toString()); - p.setProperty(prefix + "trigger", e.trigger.name()); - p.setProperty(prefix + "activeServerOnly", Boolean.toString(e.activeServerOnly)); - p.setProperty(prefix + "argument", e.argument == null ? "" : e.argument); - p.setProperty(prefix + "enabled", Boolean.toString(e.enabled)); - } - } - try { - AppDirs.createProfile(); - ProfileFiles.write(file(), out -> p.store(out, "TS3J client hotkeys")); - } catch (Exception ignored) { - } - } - - private static int parseInt(String v, int def) { - if (v == null) return def; - try { - return Integer.parseInt(v.trim()); - } catch (NumberFormatException e) { - return def; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/myts/AccountInfo.java b/ts3-client/core/src/main/java/com/ts3client/myts/AccountInfo.java deleted file mode 100644 index b7865cf..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/myts/AccountInfo.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.ts3client.myts; - -import java.time.Instant; - -/** - * Who a myTeamSpeak account is, as its sign-in reply says. The {@code userId} is the - * account's myTeamSpeak ID: also the localpart of its TeamSpeak chat ID and the user the - * file API addresses. - * - * @param userId empty when the reply carried none - * @param created null when the reply carried none - */ -public record AccountInfo(String username, String userId, String uuid, Instant created) { - - private static final String BASE32 = "abcdefghijklmnopqrstuvwxyz234567"; - - static AccountInfo of(String username, String uuid, byte[] userId, long createdSeconds) { - return new AccountInfo(username, userId == null ? "" : base32(userId), uuid, - createdSeconds > 0 ? Instant.ofEpochSecond(createdSeconds) : null); - } - - /** RFC 4648 base32, lowercase and unpadded. */ - static String base32(byte[] data) { - StringBuilder out = new StringBuilder((data.length * 8 + 4) / 5); - int buffer = 0, bits = 0; - for (byte b : data) { - buffer = (buffer << 8) | (b & 0xff); - bits += 8; - while (bits >= 5) { - out.append(BASE32.charAt((buffer >> (bits - 5)) & 31)); - bits -= 5; - } - buffer &= (1 << bits) - 1; - } - if (bits > 0) out.append(BASE32.charAt((buffer << (5 - bits)) & 31)); - return out.toString(); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/myts/ChatAttachment.java b/ts3-client/core/src/main/java/com/ts3client/myts/ChatAttachment.java deleted file mode 100644 index 040bbbc..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/myts/ChatAttachment.java +++ /dev/null @@ -1,137 +0,0 @@ -package com.ts3client.myts; - -import com.ts3client.text.Json; - -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.util.Locale; -import java.util.Map; - -/** - * A file shared in chat the way TeamSpeak 6 shares one with a server that has no chat of - * its own: the file sits in the sender's myTeamSpeak cloud storage, and an ordinary text - * message carries this JSON pointer to it. TeamSpeak 6 shows such a message as the file and - * hides the text; other clients show the text. - * - *

The file lies under the sender's myTeamSpeak ID and the room it was shared in, the - * server's unique identifier, which the message does not carry: the reader supplies it. - * - * @param senderChatId the sender's TeamSpeak chat ID, {@code @:} - * @param description the text TeamSpeak 6 shows with the file; its name unless the sender wrote one - */ -public record ChatAttachment(String fileId, String senderChatId, String fileName, long fileSize, - String description) { - - private static final String TYPE = "ts.file.myts"; - /** The home server TeamSpeak 6 accounts are on; readers use only the ID before it. */ - private static final String CHAT_HOST = "chat-1.tmspk.net"; - /** What {@link #href} addresses start with. */ - public static final String SCHEME = "tsattach:"; - /** What TeamSpeak 6 shows as a picture, by the file name. */ - private static final String[] IMAGE_SUFFIXES = {".png", ".jpeg", ".jpg", ".jpe", ".svg", ".svgz", ".webp", - ".tif", ".tiff", ".gif", ".ico", ".bmp"}; - - /** A file this account shares, under the name it is shown with. */ - public static ChatAttachment of(String fileId, String senderUserId, String fileName, long fileSize) { - return new ChatAttachment(fileId, chatId(senderUserId), fileName, fileSize, fileName); - } - - /** @return the attachment {@code message} points to, or {@code null} for any other message */ - public static ChatAttachment parse(String message) { - if (message == null || !message.startsWith("{") || !message.contains(TYPE)) return null; - Map json = Json.parseObject(message); - if (json == null || !TYPE.equals(json.get("msg_type")) - || !(json.get("file_id") instanceof String fileId) || fileId.isEmpty() - || !(json.get("chat_user_id") instanceof String sender) || sender.isEmpty()) { - return null; - } - String name = json.get("file_name") instanceof String s ? s : ""; - long size = json.get("file_size") instanceof Double d ? d.longValue() : -1; - String body = json.get("body") instanceof String s ? s : ""; - return new ChatAttachment(fileId, sender, name, size, body); - } - - /** The text message to send, written as TeamSpeak 6 writes it. */ - public String toMessage() { - return "{\"msg_type\":" + Json.quote(TYPE) - + ",\"file_id\":" + Json.quote(fileId) - + ",\"chat_user_id\":" + Json.quote(senderChatId) - + ",\"file_name\":" + Json.quote(fileName) - + ",\"file_size\":" + fileSize - + ",\"body\":" + Json.quote(description) - + ",\"v2\":true}"; - } - - /** The myTeamSpeak ID the file lies under: the chat ID's local part. */ - public String senderUserId() { - int colon = senderChatId.indexOf(':'); - int from = senderChatId.startsWith("@") ? 1 : 0; - return senderChatId.substring(from, colon > from ? colon : senderChatId.length()); - } - - public boolean isImage() { - return isImageName(fileName); - } - - /** The description, when the sender wrote one rather than leaving the file name. */ - public String caption() { - return description.isBlank() || description.equals(fileName) ? "" : description; - } - - /** The address chat views link the file with, naming everything needed to fetch it. */ - public String href(String room) { - return SCHEME + encode(room) + "/" + encode(senderUserId()) + "/" + encode(fileId) + "/" + encode(fileName); - } - - /** A file as named by {@link #href}. */ - public record Ref(String room, String owner, String fileId, String fileName) { - - /** @return the file {@code href} names, or {@code null} for any other address */ - public static Ref parse(String href) { - if (href == null || !href.startsWith(SCHEME)) return null; - String[] parts = href.substring(SCHEME.length()).split("/", -1); - if (parts.length != 4) return null; - return new Ref(decode(parts[0]), decode(parts[1]), decode(parts[2]), decode(parts[3])); - } - - public boolean isImage() { - return isImageName(fileName); - } - } - - public static boolean isHref(String href) { - return href != null && href.startsWith(SCHEME); - } - - private static boolean isImageName(String fileName) { - String name = fileName.toLowerCase(Locale.ROOT); - for (String suffix : IMAGE_SUFFIXES) { - if (name.endsWith(suffix)) return true; - } - return false; - } - - /** The chat ID TeamSpeak 6 writes for a myTeamSpeak ID. */ - static String chatId(String userId) { - return "@" + padded(userId) + ":" + CHAT_HOST; - } - - /** - * A myTeamSpeak ID padded as in TeamSpeak 6's chat IDs. Files lie under the ID exactly as - * it was given when they were stored, and TeamSpeak 6 gives it padded. - */ - static String padded(String userId) { - StringBuilder id = new StringBuilder(userId); - while (id.length() % 8 != 0) id.append('='); - return id.toString(); - } - - private static String encode(String s) { - return URLEncoder.encode(s, StandardCharsets.UTF_8).replace("+", "%20"); - } - - private static String decode(String s) { - return URLDecoder.decode(s, StandardCharsets.UTF_8); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/myts/ChatAttachments.java b/ts3-client/core/src/main/java/com/ts3client/myts/ChatAttachments.java deleted file mode 100644 index 92d49f9..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/myts/ChatAttachments.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.ts3client.myts; - -import java.io.IOException; -import java.io.InputStream; - -/** - * Shares files in chat as TeamSpeak 6 does with servers that have no chat of their own: - * into the sender's myTeamSpeak cloud storage, pointed to by a {@link ChatAttachment} - * message. Everything here blocks on the network; call it off the UI thread. - */ -public final class ChatAttachments { - - /** Larger files are not shared: they are sent from memory-starved phones too. */ - public static final long MAX_UPLOAD_BYTES = 100L << 20; - /** Pictures larger than this are offered as files rather than shown, as TeamSpeak 6 does. */ - public static final long MAX_PREVIEW_BYTES = 5L << 20; - - private final MyTsFiles files; - - public ChatAttachments(MyTeamSpeakLogin login) { - this(new MyTsFiles(login)); - } - - ChatAttachments(MyTsFiles files) { - this.files = files; - } - - /** - * Stores a file for sharing in {@code room}, the server's unique identifier. - * - * @return the message to send in its place - */ - public ChatAttachment upload(InputStream data, long size, String fileName, String room) - throws IOException, MyTsException { - if (size > MAX_UPLOAD_BYTES) { - throw new MyTsException("Files over " + (MAX_UPLOAD_BYTES >> 20) + " MB cannot be shared", 0); - } - MyTsFiles.Upload upload = files.requestUpload(room); - MyTsFiles.put(upload.url(), data, size); - return ChatAttachment.of(upload.fileId(), upload.senderUserId(), fileName, size); - } - - /** Fetches a shared file whole. */ - public byte[] download(ChatAttachment.Ref ref, long maxBytes) throws IOException, MyTsException { - return MyTsFiles.get(files.requestDownload(ref.owner(), ref.room(), ref.fileId()), maxBytes); - } - - /** - * Fetches the file an {@link ChatAttachment#href} names, for picture caches. - * - * @return {@code null} when it cannot be had, e.g. while signed out - */ - public byte[] fetchPicture(String href, long maxBytes) throws IOException { - ChatAttachment.Ref ref = ChatAttachment.Ref.parse(href); - if (ref == null) return null; - try { - return download(ref, maxBytes); - } catch (MyTsException e) { - return null; - } - } - - /** Ends the myTeamSpeak session kept for sharing, e.g. on exit or sign-out. */ - public void close() { - files.close(); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/myts/MyTeamSpeak.java b/ts3-client/core/src/main/java/com/ts3client/myts/MyTeamSpeak.java deleted file mode 100644 index 4bfaf40..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/myts/MyTeamSpeak.java +++ /dev/null @@ -1,244 +0,0 @@ -package com.ts3client.myts; - -import com.ts3client.proto.ProtobufReader; -import com.ts3client.proto.ProtobufWriter; -import com.ts3client.teamspeak.SyncItem; -import com.ts3client.teamspeak.SyncItemDecoder; -import com.ts3client.teamspeak.SyncOrder; - -import java.io.IOException; -import java.net.URI; -import java.security.GeneralSecurityException; -import java.util.ArrayList; -import java.util.List; - -/** - * Reads the bookmarks and identities a myTeamSpeak account synchronises, the way - * the official client pulls them on a fresh install: sign in, ask for every item - * of the wanted classes against an empty local state, decrypt them, and sign out. - * Nothing is ever written to the account. Staying signed in is {@link MyTeamSpeakLogin}'s. - * - *

The protocol is described in {@code docs/myteamspeak/PROTOCOL.md}. - */ -public final class MyTeamSpeak { - - public static final URI API = URI.create("https://clientapi.myteamspeak.com/"); - - /** What the account holds, in the same form as a local TeamSpeak 3 client's store. */ - public record Account(AccountInfo info, List items) { - public Account { - items = List.copyOf(items); - } - - public String username() { - return info.username(); - } - - public long identities() { - return items.stream().filter(SyncItem.Identity.class::isInstance).count(); - } - - public long bookmarks() { - return items.stream().filter(SyncItem.Bookmark.class::isInstance).count(); - } - } - - private static final String NO_VERSION = "00000000-0000-0000-0000-000000000000"; - private static final int SYNC_VERSION_1_1 = 1; - private static final int[] ITEM_CLASSES = {0 /* BOOKMARK */, 1 /* IDENTITY */, 6 /* ITEM_FOLDER */}; - - private static final int LOGIN_OK = 200; - private static final int LOGIN_OFFLINE = 201; - private static final int LOGIN_EMAIL_PENDING = 203; - private static final int IN_SYNC = 300; - private static final int NOT_IN_DB = 302; - - private final MyTsTransport transport; - - public MyTeamSpeak() { - this(MyTsTransport.https(API)); - } - - /** For the other services, which share the sign-in. */ - MyTsTransport transport() { - return transport; - } - - MyTeamSpeak(MyTsTransport transport) { - this.transport = transport; - } - - /** - * What it takes to sign in again, and all the client keeps of a sign-in — the same as - * the official client's {@code Account_Data}: the login token stands in for the - * password with the server, and the account key opens the item key it returns. The - * password itself is not needed again. - */ - public record Credentials(String email, String loginToken, byte[] accountKey) { - public Credentials { - accountKey = accountKey.clone(); - } - - @Override - public byte[] accountKey() { - return accountKey.clone(); - } - - /** Runs the key derivation, deliberately slow; call it off the UI thread. */ - public static Credentials derive(String email, String password) throws MyTsException { - try { - return new Credentials(email, MyTsCrypto.loginToken(email, password), - MyTsCrypto.accountKey(email, password)); - } catch (GeneralSecurityException e) { - throw new MyTsException("This platform lacks the ciphers myTeamSpeak needs", e); - } - } - } - - /** Signs in, reads the account and signs out again: a few requests, so call it off the UI thread. */ - public Account download(Credentials credentials) throws IOException, MyTsException { - Session session = signIn(credentials); - try { - if (session.keyPackage == null) throw new MyTsException("The account has no synchronisation key", 0); - byte[] itemKey; - try { - itemKey = MyTsCrypto.unwrapItemKey(credentials.accountKey(), session.keyPackage); - } catch (GeneralSecurityException e) { - throw new MyTsException("Could not unlock the account's encrypted data", e); - } - return new Account(session.info, pull(session.id, itemKey)); - } finally { - signOut(session.id); - } - } - - /** A signed-in session: the bearer token later requests carry, and who it belongs to. */ - record Session(String id, AccountInfo info, byte[] keyPackage) { - } - - /** Signs in; the caller ends the session with {@link #signOut}. */ - Session signIn(Credentials credentials) throws IOException, MyTsException { - ProtobufReader reply = new ProtobufReader(transport.call("authentication", "login", - new ProtobufWriter().string(1, credentials.email()).string(2, credentials.loginToken()).toByteArray())); - - byte[] keyPackage = null; - String session = "", username = "", uuid = ""; - byte[] userId = null; - long createdAt = 0; - int error = 0; - while (reply.next()) { - switch (reply.fieldNumber()) { - case 1 -> keyPackage = reply.readBytes(); - case 2 -> session = reply.readString(); - case 5 -> error = (int) reply.readVarint(); - case 4 -> uuid = reply.readString(); - case 8 -> username = reply.readString(); - case 9 -> { - ProtobufReader identity = reply.readMessage(); - while (identity.next()) { - switch (identity.fieldNumber()) { - case 3 -> createdAt = identity.readVarint(); - case 4 -> userId = identity.readBytes(); - default -> identity.skip(); - } - } - } - default -> reply.skip(); - } - } - if (error != LOGIN_OK) throw loginError(error); - return new Session(session, AccountInfo.of(username, uuid, userId, createdAt), keyPackage); - } - - private List pull(String session, byte[] itemKey) throws IOException, MyTsException { - ProtobufWriter request = new ProtobufWriter().string(1, session); - for (int itemClass : ITEM_CLASSES) { - request.message(2, new ProtobufWriter().varint(1, itemClass).string(2, NO_VERSION)); - } - request.string(3, NO_VERSION).varint(4, SYNC_VERSION_1_1); - ProtobufReader reply = new ProtobufReader( - transport.call("synchronization", "requestServerItems", request.toByteArray())); - - List frames = new ArrayList<>(); - int status = 0; - while (reply.next()) { - switch (reply.fieldNumber()) { - case 1 -> status = (int) reply.readVarint(); - case 2 -> collectFrames(reply.readMessage(), frames); - default -> reply.skip(); - } - } - if (status < IN_SYNC || status > NOT_IN_DB) { - throw new MyTsException("myTeamSpeak refused to synchronise (status " + status + ")", status); - } - - List items = new ArrayList<>(); - for (byte[] frame : frames) { - SyncItem item; - try { - item = SyncItemDecoder.decode(MyTsCrypto.decryptItem(frame, itemKey)); - } catch (GeneralSecurityException e) { - throw new MyTsException("Could not decrypt the account's items", e); - } - if (item != null) items.add(item); - } - return SyncOrder.sorted(items); - } - - /** - * The encrypted items of one {@code Sync_ItemClasses_Data}; tombstones carry none. - * The server answers with every class the account holds, whatever was asked for, - * and not all of them are encrypted (add-on flags come in the clear), so only the - * wanted classes are kept. - */ - private static void collectFrames(ProtobufReader itemClass, List frames) throws IOException { - int classId = 0; - List blobs = new ArrayList<>(); - while (itemClass.next()) { - switch (itemClass.fieldNumber()) { - case 1 -> classId = (int) itemClass.readVarint(); - case 3 -> { - byte[] blob = itemBlob(itemClass.readMessage()); - if (blob != null) blobs.add(blob); - } - default -> itemClass.skip(); - } - } - for (int wanted : ITEM_CLASSES) { - if (wanted == classId) frames.addAll(blobs); - } - } - - private static byte[] itemBlob(ProtobufReader detail) throws IOException { - byte[] blob = null; - boolean deleted = false; - while (detail.next()) { - switch (detail.fieldNumber()) { - case 3 -> blob = detail.readBytes(); - case 4 -> deleted = detail.readBool(); - default -> detail.skip(); - } - } - return !deleted && blob != null && blob.length > 0 ? blob : null; - } - - /** Ends the session rather than leave it for the server to expire; nothing to do if that fails. */ - void signOut(String session) { - if (session.isEmpty()) return; - try { - transport.call("authentication", "deleteSession", new ProtobufWriter().string(1, session).toByteArray()); - } catch (IOException | MyTsException ignored) { - // The session expires on its own. - } - } - - private static MyTsException loginError(int error) { - String message = switch (error) { - case MyTsException.LOGIN_FAILED -> "Wrong email address or password"; - case LOGIN_EMAIL_PENDING -> "Confirm your email address before signing in"; - case LOGIN_OFFLINE -> "myTeamSpeak is offline, try again later"; - default -> "myTeamSpeak refused the sign-in (error " + error + ")"; - }; - return new MyTsException(message, error); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/myts/MyTeamSpeakLogin.java b/ts3-client/core/src/main/java/com/ts3client/myts/MyTeamSpeakLogin.java deleted file mode 100644 index 83822bd..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/myts/MyTeamSpeakLogin.java +++ /dev/null @@ -1,143 +0,0 @@ -package com.ts3client.myts; - -import com.ts3client.config.AppDirs; -import com.ts3client.config.ProfileFiles; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Base64; -import java.util.Properties; - -/** - * The myTeamSpeak account this client stays signed in to. Signing in keeps the - * {@link MyTeamSpeak.Credentials} in the profile, private to the user, so the account - * can be read again later without asking for the password; signing out forgets them. - * Each read signs in afresh; only {@link MyTsFiles} keeps a session. - */ -public final class MyTeamSpeakLogin { - - private static final String FILE_NAME = "myteamspeak.properties"; - - private final File file; - private final MyTeamSpeak service; - private MyTeamSpeak.Credentials credentials; - private String username = ""; - - MyTeamSpeakLogin(File file, MyTeamSpeak service) { - this.file = file; - this.service = service; - read(); - } - - public static MyTeamSpeakLogin load() { - return new MyTeamSpeakLogin(AppDirs.file(FILE_NAME), new MyTeamSpeak()); - } - - public synchronized boolean isSignedIn() { - return credentials != null; - } - - /** Empty when signed out. */ - public synchronized String email() { - return credentials == null ? "" : credentials.email(); - } - - /** The account's display name; the email when the account has none. */ - public synchronized String username() { - return username.isBlank() ? email() : username; - } - - /** - * Signs in and stays signed in, returning what the account holds. Blocks for the key - * derivation and a few requests. Nothing is kept when it fails. - */ - public MyTeamSpeak.Account signIn(String email, String password) throws IOException, MyTsException { - MyTeamSpeak.Credentials fresh = MyTeamSpeak.Credentials.derive(email.trim(), password); - MyTeamSpeak.Account account = service.download(fresh); - synchronized (this) { - credentials = fresh; - username = account.username(); - write(); - } - return account; - } - - /** - * Reads the account again. When the server no longer takes the kept credentials — - * the password was changed elsewhere — this signs out before rethrowing. - * - * @throws IllegalStateException when signed out - */ - public MyTeamSpeak.Account fetch() throws IOException, MyTsException { - MyTeamSpeak.Credentials current; - synchronized (this) { - if (credentials == null) throw new IllegalStateException("Not signed in to myTeamSpeak"); - current = credentials; - } - try { - MyTeamSpeak.Account account = service.download(current); - synchronized (this) { - if (credentials == current && !account.username().equals(username)) { - username = account.username(); - write(); - } - } - return account; - } catch (MyTsException e) { - if (!e.credentialsRejected()) throw e; - synchronized (this) { - if (credentials == current) signOut(); - } - throw new MyTsException("myTeamSpeak no longer accepts the saved sign-in; the password may have " - + "changed. Sign in again.", e.code()); - } - } - - /** What signs in, or {@code null} when signed out. */ - synchronized MyTeamSpeak.Credentials credentials() { - return credentials; - } - - MyTeamSpeak service() { - return service; - } - - public synchronized void signOut() { - credentials = null; - username = ""; - //noinspection ResultOfMethodCallIgnored - file.delete(); - } - - private void read() { - if (!file.isFile()) return; - Properties p = new Properties(); - try (InputStream in = new FileInputStream(file)) { - p.load(in); - String email = p.getProperty("email", ""); - String token = p.getProperty("loginToken", ""); - byte[] key = Base64.getDecoder().decode(p.getProperty("accountKey", "")); - if (email.isEmpty() || token.isEmpty() || key.length == 0) return; - credentials = new MyTeamSpeak.Credentials(email, token, key); - username = p.getProperty("username", ""); - } catch (IOException | IllegalArgumentException unreadable) { - // Treated as signed out. - } - } - - private void write() { - Properties p = new Properties(); - p.setProperty("email", credentials.email()); - p.setProperty("username", username); - p.setProperty("loginToken", credentials.loginToken()); - p.setProperty("accountKey", Base64.getEncoder().encodeToString(credentials.accountKey())); - try { - AppDirs.createProfile(); - ProfileFiles.write(file, out -> p.store(out, "myTeamSpeak sign-in: a derived token and key, not the password")); - } catch (IOException e) { - // Signed in for this run only. - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/myts/MyTsCrypto.java b/ts3-client/core/src/main/java/com/ts3client/myts/MyTsCrypto.java deleted file mode 100644 index 5e3a60b..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/myts/MyTsCrypto.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.ts3client.myts; - -import javax.crypto.AEADBadTagException; -import javax.crypto.Cipher; -import javax.crypto.Mac; -import javax.crypto.spec.GCMParameterSpec; -import javax.crypto.spec.SecretKeySpec; -import java.nio.charset.StandardCharsets; -import java.security.GeneralSecurityException; -import java.security.MessageDigest; -import java.util.Arrays; -import java.util.Base64; - -/** - * The end-to-end encryption of myTeamSpeak synchronisation, as the official - * client's {@code teamcrypto} does it (see {@code docs/myteamspeak/CRYPTO_RE_SALT.md}). - * Both keys come from the password: the login token proves it to the server, and - * the account key unwraps the item key the server hands back, which the server - * itself never learns. - */ -final class MyTsCrypto { - - private static final int PBKDF2_ITERATIONS = 10_000; - private static final int LOGIN_TOKEN_BYTES = 48; - private static final int KEY_BYTES = 32; - private static final int GCM_TAG_BYTES = 16; - private static final int GCM_IV_BYTES = 12; - private static final int KEY_PACKAGE_VERSION = 2; - private static final int CTR_BLOCK_BYTES = 16; - private static final int ITEM_HASH_BYTES = 64; - - private MyTsCrypto() { - } - - /** What {@code LoginData.password} carries instead of the password. */ - static String loginToken(String email, String password) throws GeneralSecurityException { - return Base64.getEncoder().encodeToString(derive(email, password, "ts3Login", LOGIN_TOKEN_BYTES)); - } - - static byte[] accountKey(String email, String password) throws GeneralSecurityException { - return derive(email, password, "ts3Encryption", KEY_BYTES); - } - - /** - * Opens {@code LoginSession.key}: {@code 02 || tag[16] || iv[12] || ciphertext[32]}, - * AES-256-GCM under the account key, no AAD. - */ - static byte[] unwrapItemKey(byte[] accountKey, byte[] keyPackage) throws GeneralSecurityException { - if (keyPackage.length != 1 + GCM_TAG_BYTES + GCM_IV_BYTES + KEY_BYTES || keyPackage[0] != KEY_PACKAGE_VERSION) { - throw new GeneralSecurityException("Unsupported account key package"); - } - int ivAt = 1 + GCM_TAG_BYTES; - int dataAt = ivAt + GCM_IV_BYTES; - // JCA wants the tag after the ciphertext. - byte[] sealed = new byte[KEY_BYTES + GCM_TAG_BYTES]; - System.arraycopy(keyPackage, dataAt, sealed, 0, KEY_BYTES); - System.arraycopy(keyPackage, 1, sealed, KEY_BYTES, GCM_TAG_BYTES); - - Cipher gcm = Cipher.getInstance("AES/GCM/NoPadding"); - gcm.init(Cipher.DECRYPT_MODE, new SecretKeySpec(accountKey, "AES"), - new GCMParameterSpec(GCM_TAG_BYTES * 8, keyPackage, ivAt, GCM_IV_BYTES)); - try { - return gcm.doFinal(sealed); - } catch (AEADBadTagException e) { - throw new GeneralSecurityException("The account key does not match the password", e); - } - } - - /** - * Decrypts an item frame, {@code iv[16] || ciphertext || SHA-512(plaintext)}, into - * its {@code Item_Data} message. The cipher is AES-256-CTR, but with the counter - * incremented little-endian, so JCA's own CTR mode cannot be used. - */ - static byte[] decryptItem(byte[] frame, byte[] itemKey) throws GeneralSecurityException { - int textLength = frame.length - CTR_BLOCK_BYTES - ITEM_HASH_BYTES; - if (textLength <= 0) throw new GeneralSecurityException("Truncated item"); - - Cipher aes = Cipher.getInstance("AES/ECB/NoPadding"); - aes.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(itemKey, "AES")); - byte[] counter = Arrays.copyOf(frame, CTR_BLOCK_BYTES); - byte[] plain = new byte[textLength]; - for (int off = 0; off < textLength; off += CTR_BLOCK_BYTES) { - byte[] keyStream = aes.doFinal(counter); - int n = Math.min(CTR_BLOCK_BYTES, textLength - off); - for (int i = 0; i < n; i++) plain[off + i] = (byte) (frame[CTR_BLOCK_BYTES + off + i] ^ keyStream[i]); - incrementLittleEndian(counter); - } - - byte[] hash = MessageDigest.getInstance("SHA-512").digest(plain); - byte[] expected = Arrays.copyOfRange(frame, frame.length - ITEM_HASH_BYTES, frame.length); - if (!MessageDigest.isEqual(hash, expected)) throw new GeneralSecurityException("Item integrity check failed"); - return plain; - } - - /** PBKDF2-HMAC-SHA512 keyed by the password, salted with {@code lower(email) + purpose + password}. */ - private static byte[] derive(String email, String password, String purpose, int length) - throws GeneralSecurityException { - byte[] salt = (asciiLowerCase(email) + purpose + password).getBytes(StandardCharsets.UTF_8); - Mac hmac = Mac.getInstance("HmacSHA512"); - hmac.init(new SecretKeySpec(password.getBytes(StandardCharsets.UTF_8), "HmacSHA512")); - - byte[] out = new byte[length]; - byte[] blockSalt = Arrays.copyOf(salt, salt.length + 4); - for (int block = 1, off = 0; off < length; block++) { - blockSalt[salt.length] = (byte) (block >>> 24); - blockSalt[salt.length + 1] = (byte) (block >>> 16); - blockSalt[salt.length + 2] = (byte) (block >>> 8); - blockSalt[salt.length + 3] = (byte) block; - byte[] u = hmac.doFinal(blockSalt); - byte[] t = u.clone(); - for (int i = 1; i < PBKDF2_ITERATIONS; i++) { - u = hmac.doFinal(u); - for (int j = 0; j < t.length; j++) t[j] ^= u[j]; - } - int n = Math.min(t.length, length - off); - System.arraycopy(t, 0, out, off, n); - off += n; - } - return out; - } - - /** The official client lowercases bytewise, leaving anything outside ASCII alone. */ - private static String asciiLowerCase(String s) { - char[] chars = s.toCharArray(); - for (int i = 0; i < chars.length; i++) { - if (chars[i] >= 'A' && chars[i] <= 'Z') chars[i] += 'a' - 'A'; - } - return new String(chars); - } - - private static void incrementLittleEndian(byte[] counter) { - for (int i = 0; i < counter.length && ++counter[i] == 0; i++) { - // carry into the next byte - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/myts/MyTsException.java b/ts3-client/core/src/main/java/com/ts3client/myts/MyTsException.java deleted file mode 100644 index b8ee406..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/myts/MyTsException.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.ts3client.myts; - -/** The myTeamSpeak service refused a request; the message is fit to show the user. */ -public final class MyTsException extends Exception { - - /** {@code ERROR_LOGIN_FAILED}: wrong email or password. */ - static final int LOGIN_FAILED = 202; - - private final int code; - - MyTsException(String message, int code) { - super(message); - this.code = code; - } - - MyTsException(String message, Throwable cause) { - super(message, cause); - this.code = 0; - } - - /** The service's {@code ErrorCommon}/{@code SyncStatus} code or HTTP status; 0 when there is none. */ - public int code() { - return code; - } - - /** The server no longer accepts the email and password, for instance after a password change. */ - public boolean credentialsRejected() { - return code == LOGIN_FAILED; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/myts/MyTsFiles.java b/ts3-client/core/src/main/java/com/ts3client/myts/MyTsFiles.java deleted file mode 100644 index a1ea6cb..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/myts/MyTsFiles.java +++ /dev/null @@ -1,183 +0,0 @@ -package com.ts3client.myts; - -import com.ts3client.proto.ProtobufReader; -import com.ts3client.proto.ProtobufWriter; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; - -/** - * Files kept in myTeamSpeak cloud storage, as TeamSpeak 6 shares them in chat. The service - * hands out signed storage addresses: one to put a new file under this account's ID and a - * room, one to get a file someone put under theirs. Both need a signed-in account; the - * session is kept for later requests and renewed when it runs out. - * - *

The storage addresses are signed for {@code Content-Type: text/plain} whatever the file - * is, both ways; a request without it is refused. - */ -public final class MyTsFiles { - - private static final String SIGNED_TYPE = "text/plain"; - private static final int TIMEOUT_MS = 30_000; - - private static final int ERROR_NOT_ALLOWED = 107; - private static final int ERROR_SESSION_EXPIRED = 109; - - private final MyTeamSpeakLogin login; - private final MyTeamSpeak service; - private MyTeamSpeak.Session session; - private MyTeamSpeak.Credentials sessionCredentials; - - public MyTsFiles(MyTeamSpeakLogin login) { - this(login, login.service()); - } - - MyTsFiles(MyTeamSpeakLogin login, MyTeamSpeak service) { - this.login = login; - this.service = service; - } - - /** Where a new file goes. */ - public record Upload(String fileId, String senderUserId, String url) { - } - - /** Asks for a place to put a new file shared in {@code room}. */ - public Upload requestUpload(String room) throws IOException, MyTsException { - return withSession(s -> { - String userId = ChatAttachment.padded(s.info().userId()); - byte[] request = new ProtobufWriter().string(1, s.id()).string(2, userId).string(3, room).toByteArray(); - FileInfo info = FileInfo.read(service.transport().call("user", "requestUploadFile", request)); - return new Upload(info.fileId, userId, info.url); - }); - } - - /** The address a file someone shared in {@code room} can be fetched from. */ - public String requestDownload(String owner, String room, String fileId) throws IOException, MyTsException { - return withSession(s -> { - byte[] request = new ProtobufWriter().string(1, s.id()).string(2, owner).string(3, room) - .string(4, fileId).toByteArray(); - return FileInfo.read(service.transport().call("user", "requestDownloadFile", request)).url; - }); - } - - /** Stores the file at an address {@link #requestUpload} gave. */ - public static void put(String url, InputStream data, long length) throws IOException { - HttpURLConnection http = open(url); - try { - http.setRequestMethod("PUT"); - http.setDoOutput(true); - http.setFixedLengthStreamingMode(length); - try (OutputStream out = http.getOutputStream()) { - data.transferTo(out); - } - int status = http.getResponseCode(); - if (status / 100 != 2) throw new IOException("The file store answered HTTP " + status); - } finally { - http.disconnect(); - } - } - - /** - * Fetches the file at an address {@link #requestDownload} gave. - * - * @throws IOException also when the file is larger than {@code maxBytes} - */ - public static byte[] get(String url, long maxBytes) throws IOException { - HttpURLConnection http = open(url); - try { - int status = http.getResponseCode(); - if (status != HttpURLConnection.HTTP_OK) throw new IOException("The file store answered HTTP " + status); - if (http.getContentLengthLong() > maxBytes) throw new IOException("The file is too large"); - try (InputStream in = http.getInputStream()) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - byte[] buf = new byte[16 << 10]; - for (int n; (n = in.read(buf)) > 0; ) { - if (out.size() + n > maxBytes) throw new IOException("The file is too large"); - out.write(buf, 0, n); - } - return out.toByteArray(); - } - } finally { - http.disconnect(); - } - } - - /** Ends the kept session, e.g. on sign-out or exit; the next request signs in again. */ - public void close() { - MyTeamSpeak.Session ended; - synchronized (this) { - ended = session; - session = null; - sessionCredentials = null; - } - if (ended != null) service.signOut(ended.id()); - } - - private interface Request { - T run(MyTeamSpeak.Session session) throws IOException, MyTsException; - } - - private T withSession(Request request) throws IOException, MyTsException { - MyTeamSpeak.Session s = session(); - try { - return request.run(s); - } catch (MyTsException e) { - if (e.code() != ERROR_SESSION_EXPIRED) throw e; - synchronized (this) { - if (session == s) session = null; - } - return request.run(session()); - } - } - - private synchronized MyTeamSpeak.Session session() throws IOException, MyTsException { - MyTeamSpeak.Credentials credentials = login.credentials(); - if (session != null && sessionCredentials == credentials) return session; - if (session != null) service.signOut(session.id()); - session = null; - if (credentials == null) throw new MyTsException("Sign in to myTeamSpeak to share files", 0); - session = service.signIn(credentials); - sessionCredentials = credentials; - if (session.info().userId().isEmpty()) throw new MyTsException("The account has no myTeamSpeak ID", 0); - return session; - } - - private static HttpURLConnection open(String url) throws IOException { - HttpURLConnection http = (HttpURLConnection) new URL(url).openConnection(); - http.setConnectTimeout(TIMEOUT_MS); - http.setReadTimeout(TIMEOUT_MS); - http.setRequestProperty("Content-Type", SIGNED_TYPE); - return http; - } - - /** The service's {@code FileInfo} reply. */ - private record FileInfo(String fileId, String url) { - - static FileInfo read(byte[] reply) throws IOException, MyTsException { - ProtobufReader r = new ProtobufReader(reply); - boolean success = false; - int error = 0; - String fileId = "", url = ""; - while (r.next()) { - switch (r.fieldNumber()) { - case 1 -> success = r.readBool(); - case 2 -> error = (int) r.readVarint(); - case 5 -> fileId = r.readString(); - case 6 -> url = r.readString(); - default -> r.skip(); - } - } - if (success && !url.isEmpty()) return new FileInfo(fileId, url); - String message = switch (error) { - case ERROR_NOT_ALLOWED -> "The file is not available"; - case ERROR_SESSION_EXPIRED -> "The myTeamSpeak session ran out"; - default -> "myTeamSpeak refused the file (error " + error + ")"; - }; - throw new MyTsException(message, error); - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/myts/MyTsTransport.java b/ts3-client/core/src/main/java/com/ts3client/myts/MyTsTransport.java deleted file mode 100644 index 2f781a3..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/myts/MyTsTransport.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.ts3client.myts; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URI; -import java.nio.charset.StandardCharsets; - -/** - * One call to the myTeamSpeak client API: a protobuf request to a method of a - * service endpoint, answered with a protobuf reply. - */ -interface MyTsTransport { - - byte[] call(String endpoint, String method, byte[] request) throws IOException, MyTsException; - - /** - * The official client's wire form: an HTTP/1.1 POST of {@code } - * as {@code application/ts3cloud}. The reply is the bare protobuf, whatever its - * Content-Type says. Cloudflare in front turns away clients that look different, - * hence the cpp-httplib user agent. - */ - static MyTsTransport https(URI base) { - return (endpoint, method, request) -> { - byte[] name = method.getBytes(StandardCharsets.US_ASCII); - HttpURLConnection http = (HttpURLConnection) base.resolve(endpoint).toURL().openConnection(); - try { - http.setRequestMethod("POST"); - http.setConnectTimeout(15_000); - http.setReadTimeout(30_000); - http.setDoOutput(true); - http.setRequestProperty("Content-Type", "application/ts3cloud"); - http.setRequestProperty("Accept", "*/*"); - http.setRequestProperty("User-Agent", "cpp-httplib/0.11.1"); - http.setFixedLengthStreamingMode(1 + name.length + request.length); - try (OutputStream out = http.getOutputStream()) { - out.write(name.length); - out.write(name); - out.write(request); - } - int status = http.getResponseCode(); - if (status != HttpURLConnection.HTTP_OK) { - throw new MyTsException("The myTeamSpeak server answered HTTP " + status, status); - } - try (InputStream in = http.getInputStream()) { - return in.readAllBytes(); - } - } finally { - http.disconnect(); - } - }; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/AvatarAdmin.java b/ts3-client/core/src/main/java/com/ts3client/net/AvatarAdmin.java deleted file mode 100644 index 88aa9a1..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/AvatarAdmin.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.ts3client.net; - -import com.github.manevolent.ts3j.command.SingleCommand; -import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; -import com.github.manevolent.ts3j.protocol.ProtocolRole; -import com.ts3client.net.avatar.AvatarNaming; -import com.ts3client.net.avatar.ImageFormat; -import com.ts3client.net.filetransfer.FileTransfer; -import com.ts3client.net.filetransfer.FileTransferManager; - -import java.io.File; -import java.nio.file.Files; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -/** - * Publishes and withdraws the local client's avatar, the way the official client does - * it: the picture goes into channel 0's file repository as {@code /avatar_} and - * {@code client_flag_avatar} is then set to its MD5, which is what other clients key - * their downloads on. - */ -final class AvatarAdmin { - - /** The server's own default for {@code i_client_max_avatar_filesize}. */ - static final int DEFAULT_MAX_AVATAR_BYTES = 200_000; - /** The largest avatar we are willing to download, whatever a server allows. */ - static final int MAX_AVATAR_DOWNLOAD_BYTES = 8 * 1024 * 1024; - - private static final long UPLOAD_TIMEOUT_MS = 60_000; - - private final TeamspeakConnection conn; - - AvatarAdmin(TeamspeakConnection conn) { - this.conn = conn; - } - - /** - * How large an avatar this server lets us upload, from - * {@code i_client_max_avatar_filesize}, or the server default while unknown. - */ - int maxUploadBytes() { - int limit = conn.getModel().selfPermissionValue("i_client_max_avatar_filesize"); - return limit > 0 ? limit : DEFAULT_MAX_AVATAR_BYTES; - } - - /** Uploads {@code source} as our avatar and announces it; returns its flag. */ - String upload(File source) throws Exception { - byte[] data = Files.readAllBytes(source.toPath()); - if (data.length == 0) throw new IllegalArgumentException("That file is empty"); - if (ImageFormat.detect(data) == null) { - throw new IllegalArgumentException("Avatars must be PNG, JPEG, GIF or BMP images"); - } - int limit = maxUploadBytes(); - if (data.length > limit) { - throw new IllegalArgumentException("This server limits avatars to " + (limit / 1024) + " KiB"); - } - String name = ownFileName(); - - CountDownLatch done = new CountDownLatch(1); - FileTransfer transfer = fileTransfers().upload(0, "", "/" + name, source, true, t -> { - if (t.isDone()) done.countDown(); - }); - if (!done.await(UPLOAD_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { - throw new IllegalStateException("The upload did not finish in time"); - } - if (transfer.getState() != FileTransfer.State.COMPLETED) { - throw new IllegalStateException(transfer.getErrorMessage() == null - ? "The upload failed" : transfer.getErrorMessage()); - } - String flag = AvatarNaming.flag(data); - setFlag(flag); - conn.getAvatars().put(data); - return flag; - } - - /** Clears our avatar flag and removes the file from the server. */ - void remove() throws Exception { - setFlag(""); - try { - deleteFile(conn.getSelfUniqueId()); - } catch (Exception ignored) { - // The flag is what other clients go by; a leftover file only wastes space. - // Servers refuse the deletion unless we may delete others' avatars too. - } - } - - /** - * Deletes another client's avatar, which needs {@code b_client_avatar_delete_other}; - * the server then clears their flag for everyone. - */ - void removeOther(String uniqueId) throws Exception { - deleteFile(uniqueId); - } - - /** - * Deleting names the avatar by its owner's unique id, {@code /avatar_}, which the - * server maps to the stored file itself; the stored name is refused ("convert error"). - */ - private void deleteFile(String uniqueId) throws Exception { - fileTransfers().delete(0, "", "/avatar_" + uniqueId); - } - - private void setFlag(String flag) throws Exception { - SingleCommand cmd = new SingleCommand("clientupdate", ProtocolRole.CLIENT, - new CommandSingleParameter("client_flag_avatar", flag)); - conn.socket().executeCommand(cmd).complete(); - } - - private String ownFileName() { - String name = AvatarNaming.fileName(conn.getSelfUniqueId()); - if (name == null) throw new IllegalStateException("Our identity has no usable unique id"); - return name; - } - - private FileTransferManager fileTransfers() { - FileTransferManager ft = conn.fileTransfers(); - if (ft == null) throw new IllegalStateException("Not connected"); - return ft; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/BanAdmin.java b/ts3-client/core/src/main/java/com/ts3client/net/BanAdmin.java deleted file mode 100644 index 3a5bdbd..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/BanAdmin.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.ts3client.net; - -import com.github.manevolent.ts3j.command.CommandException; -import com.github.manevolent.ts3j.command.SingleCommand; -import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; -import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent; -import com.github.manevolent.ts3j.protocol.ProtocolRole; -import com.ts3client.net.ban.BanEntry; -import com.ts3client.net.ban.BanRule; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -/** - * The server's ban list: reading it and adding, replacing and deleting entries. - * - *

Split out of {@link TeamspeakConnection} like {@link ChannelAdmin}, and for the same - * reason: it is a self-contained request/response corner of the protocol that only the - * ban list window uses. Every call here blocks and must run off the UI thread; the - * connection's public wrappers do that. - */ -final class BanAdmin { - - /** What {@code banlist} answers when there are no bans at all. */ - private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501; - - private final TeamspeakConnection conn; - - /** - * The {@code banlist} reply in progress. The server answers the command with a burst - * of {@code notifybanlist} events rather than a command response, so one request may - * be in flight at a time and its entries are collected here until the command itself - * completes. - */ - private volatile List listing; - - BanAdmin(TeamspeakConnection conn) { - this.conn = conn; - } - - /** Reads every ban on the server. */ - List list() throws Exception { - List entries = Collections.synchronizedList(new ArrayList<>()); - listing = entries; - try { - conn.socket().executeCommand(new SingleCommand("banlist", ProtocolRole.CLIENT)).complete(); - // The entries were queued on the event thread before the command's own reply - // was read, so draining that thread is what guarantees they have all landed. - conn.awaitEventsProcessed(); - } catch (CommandException e) { - if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e; - } finally { - listing = null; - } - return new ArrayList<>(entries); - } - - /** Collects one {@code notifybanlist} entry for the request in flight. */ - void onListEntry(UnknownTeamspeakEvent e) { - List entries = listing; - if (entries == null) return; - BanEntry entry = BanEntry.from(e.getMap()); - if (entry.id >= 0) entries.add(entry); - } - - /** - * Adds a ban. - * - * @return the new ban's id, or -1 where the server did not name it - */ - int add(BanRule rule) throws Exception { - if (!rule.hasTarget()) throw new IllegalArgumentException("A ban needs something to match"); - SingleCommand cmd = new SingleCommand("banadd", ProtocolRole.CLIENT); - addIfSet(cmd, "ip", rule.ipRegex); - addIfSet(cmd, "name", rule.nameRegex); - addIfSet(cmd, "uid", rule.uid); - addIfSet(cmd, "mytsid", rule.mytsid); - if (!rule.isPermanent()) cmd.add(new CommandSingleParameter("time", Long.toString(rule.durationSeconds))); - addIfSet(cmd, "banreason", rule.reason); - for (SingleCommand answer : conn.socket().executeCommand(cmd).get()) { - Map fields = answer.toMap(); - if (fields.containsKey("banid")) { - return BanEntry.from(fields).id; - } - } - return -1; - } - - /** - * Replaces a ban with a re-written one. The server has no way to edit a ban in place, - * so the new one is added before the old is removed: a failure half-way leaves the - * client banned twice rather than not at all. - */ - void replace(int banId, BanRule rule) throws Exception { - add(rule); - try { - delete(banId); - } catch (Exception e) { - throw new IllegalStateException("The edited ban was added, but the original could not be" - + " removed: " + e.getMessage(), e); - } - } - - void delete(int banId) throws Exception { - SingleCommand cmd = new SingleCommand("bandel", ProtocolRole.CLIENT, - new CommandSingleParameter("banid", Integer.toString(banId))); - conn.socket().executeCommand(cmd).complete(); - } - - private static void addIfSet(SingleCommand cmd, String key, String value) { - if (value != null && !value.isEmpty()) cmd.add(new CommandSingleParameter(key, value)); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ChannelAdmin.java b/ts3-client/core/src/main/java/com/ts3client/net/ChannelAdmin.java deleted file mode 100644 index 8a3f80c..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/ChannelAdmin.java +++ /dev/null @@ -1,282 +0,0 @@ -package com.ts3client.net; - -import com.github.manevolent.ts3j.api.Channel; -import com.github.manevolent.ts3j.command.MultiCommand; -import com.github.manevolent.ts3j.command.SingleCommand; -import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; -import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent; -import com.github.manevolent.ts3j.protocol.ProtocolRole; -import com.ts3client.net.filetransfer.FileTransfer; -import com.ts3client.net.filetransfer.FileTransferManager; -import com.ts3client.net.filetransfer.RemoteFile; - -import java.io.File; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.zip.CRC32; - -/** - * Everything the channel editor needs of the server: reading and writing a channel's - * properties and its needed-power permissions, plus the virtual server's icon store. - * - *

Split out of {@link TeamspeakConnection} because it is a self-contained request/ - * response corner of the protocol that only the editor uses. Every call here blocks and - * must run off the UI thread; the connection's public wrappers do that. - */ -final class ChannelAdmin { - - /** The directory a server's icons live in, where the server has one. */ - private static final String ICON_DIRECTORY = "icons"; - - /** How long to wait for a whole icon to travel over the file connection. */ - private static final long ICON_UPLOAD_TIMEOUT_MS = 30_000; - - private final TeamspeakConnection conn; - - /** - * The {@code channelpermlist} reply in progress. TeamSpeak answers the command with a - * burst of {@code notifychannelpermlist} events rather than a command response, and - * only the first of them repeats the channel id, so one request may be in flight at a - * time and its entries are collected here until the command itself completes. - */ - private volatile PermRequest permRequest; - - ChannelAdmin(TeamspeakConnection conn) { - this.conn = conn; - } - - // ---- channel properties ---- - - /** Reads a channel's full property set. */ - ChannelSettings readSettings(int channelId) throws Exception { - Channel info = conn.socket().getChannelInfo(channelId); - if (info == null) throw new IllegalStateException("The server did not describe that channel"); - return ChannelSettings.from(channelId, info.getMap()); - } - - /** - * Creates a channel below {@code parentId} (0 being the top level). - * - * @param properties the new channel's properties, as {@link ChannelSettings#creationParameters} - * @return the new channel's id - */ - int create(int parentId, Map properties) throws Exception { - SingleCommand cmd = new SingleCommand("channelcreate", ProtocolRole.CLIENT); - cmd.add(new CommandSingleParameter("cpid", Integer.toString(parentId))); - for (Map.Entry property : properties.entrySet()) { - cmd.add(new CommandSingleParameter(property.getKey(), property.getValue())); - } - for (SingleCommand answer : conn.socket().executeCommand(cmd).get()) { - int cid = parseInt(answer.toMap().get("cid"), -1); - if (cid > 0) return cid; - } - // Some servers acknowledge the command without naming the channel; the - // notifychannelcreated they also send does name it, so read it off the model - // once that event has been handled. - conn.awaitEventsProcessed(); - ChannelNode created = conn.getModel().findChannelByName(parentId, properties.get("channel_name")); - if (created == null) throw new IllegalStateException("The server did not report the new channel"); - return created.id; - } - - /** Applies {@code changes} (property name to value) with a single {@code channeledit}. */ - void edit(int channelId, Map changes) throws Exception { - if (changes.isEmpty()) return; - SingleCommand cmd = new SingleCommand("channeledit", ProtocolRole.CLIENT); - cmd.add(new CommandSingleParameter("cid", Integer.toString(channelId))); - for (Map.Entry change : changes.entrySet()) { - cmd.add(new CommandSingleParameter(change.getKey(), change.getValue())); - } - conn.socket().executeCommand(cmd).complete(); - } - - /** Deletes a channel, with its sub-channels and whoever is in them moved out when {@code force}. */ - void delete(int channelId, boolean force) throws Exception { - conn.socket().executeCommand(new SingleCommand("channeldelete", ProtocolRole.CLIENT, - new CommandSingleParameter("cid", Integer.toString(channelId)), - new CommandSingleParameter("force", force ? "1" : "0"))).complete(); - } - - // ---- channel permissions ---- - - /** - * Reads the permissions set directly on a channel. - * - * @return permission name to value, holding only the permissions the channel itself - * carries — anything inherited from a group is absent - */ - Map readPermissions(int channelId) throws Exception { - if (!conn.getModel().hasPermissionNames()) { - // channelpermlist reports numeric ids, which only the permissionlist response - // gives names to; without it the values could not be told apart. - throw new IllegalStateException("The server did not send its permission list"); - } - PermRequest request = new PermRequest(channelId); - permRequest = request; - try { - SingleCommand cmd = new SingleCommand("channelpermlist", ProtocolRole.CLIENT, - new CommandSingleParameter("cid", Integer.toString(channelId))); - conn.socket().executeCommand(cmd).complete(); - // The entries were queued on the event thread before the command's own reply - // was read, so draining that thread is what guarantees they have all landed. - conn.awaitEventsProcessed(); - } finally { - permRequest = null; - } - - Map byName = new LinkedHashMap<>(); - for (Map.Entry entry : request.values.entrySet()) { - String name = conn.getModel().permissionName(entry.getKey()); - if (name != null) byName.put(name, entry.getValue()); - } - return byName; - } - - /** Collects one {@code notifychannelpermlist} entry for the request in flight. */ - void onPermListEntry(UnknownTeamspeakEvent e) { - PermRequest request = permRequest; - if (request == null) return; - String cid = e.get("cid"); - if (cid != null && !cid.isEmpty() && parseInt(cid, -1) != request.channelId) return; - int permId = parseInt(e.get("permid"), -1); - if (permId >= 0) request.values.put(permId, parseInt(e.get("permvalue"), 0)); - } - - /** - * Sets and clears channel permissions by name. A permission set to a value is added or - * updated; one that is cleared is removed so the channel inherits it again. - */ - void writePermissions(int channelId, Map set, Collection remove) - throws Exception { - if (!set.isEmpty()) { - List parts = new ArrayList<>(set.size()); - for (Map.Entry perm : set.entrySet()) { - parts.add(new SingleCommand("channeladdperm", ProtocolRole.CLIENT, - new CommandSingleParameter("permsid", perm.getKey()), - new CommandSingleParameter("permvalue", Integer.toString(perm.getValue())))); - } - send("channeladdperm", channelId, parts); - } - if (!remove.isEmpty()) { - List parts = new ArrayList<>(remove.size()); - for (String name : remove) { - parts.add(new SingleCommand("channeldelperm", ProtocolRole.CLIENT, - new CommandSingleParameter("permsid", name))); - } - send("channeldelperm", channelId, parts); - } - } - - private void send(String name, int channelId, List parts) throws Exception { - MultiCommand cmd = new MultiCommand(name, ProtocolRole.CLIENT, parts); - cmd.add(new CommandSingleParameter("cid", Integer.toString(channelId))); - conn.socket().executeCommand(cmd).complete(); - } - - // ---- the server's icon store ---- - - /** - * The ids of the icons uploaded to this virtual server, which live in channel 0's file - * repository as {@code /icon_}. - */ - List listIcons() throws Exception { - List ids = new ArrayList<>(); - boolean hasIconDirectory = false; - for (RemoteFile file : fileTransfers().list(0, "", "/")) { - if (file.isDirectory()) { - hasIconDirectory |= file.getName().equals(ICON_DIRECTORY); - continue; - } - addIcon(ids, file); - } - // Newer servers keep the icons in their own directory rather than loose in the - // repository's root; both layouts exist, so whichever this server uses is read. - if (hasIconDirectory) { - for (RemoteFile file : fileTransfers().list(0, "", "/" + ICON_DIRECTORY)) { - if (!file.isDirectory()) addIcon(ids, file); - } - } - return ids; - } - - private static void addIcon(List ids, RemoteFile file) { - if (!file.getName().startsWith("icon_")) return; - long id = parseLong(file.getName().substring("icon_".length())); - if (id > 0 && !ids.contains(id)) ids.add(id); - } - - /** - * Uploads an image as a server icon. - * - * @return the icon's id, which TeamSpeak derives from the file's CRC32 - */ - long uploadIcon(File source) throws Exception { - byte[] data = Files.readAllBytes(source.toPath()); - if (data.length == 0) throw new IllegalArgumentException("That file is empty"); - if (data.length > TeamspeakConnection.MAX_ICON_BYTES) { - throw new IllegalArgumentException("Icons may not be larger than " - + (TeamspeakConnection.MAX_ICON_BYTES / 1024) + " KiB"); - } - CRC32 crc = new CRC32(); - crc.update(data); - long id = crc.getValue(); - - CountDownLatch done = new CountDownLatch(1); - FileTransfer transfer = fileTransfers().upload(0, "", "/icon_" + id, source, true, t -> { - if (t.isDone()) done.countDown(); - }); - if (!done.await(ICON_UPLOAD_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { - throw new IllegalStateException("The upload did not finish in time"); - } - if (transfer.getState() != FileTransfer.State.COMPLETED) { - throw new IllegalStateException(transfer.getErrorMessage() == null - ? "The upload failed" : transfer.getErrorMessage()); - } - return id; - } - - void deleteIcon(long iconId) throws Exception { - fileTransfers().delete(0, "", "/icon_" + iconId); - } - - private FileTransferManager fileTransfers() { - FileTransferManager ft = conn.fileTransfers(); - if (ft == null) throw new IllegalStateException("Not connected"); - return ft; - } - - // ---- helpers ---- - - private static int parseInt(String value, int fallback) { - try { - return value == null || value.isEmpty() ? fallback : Integer.parseInt(value.trim()); - } catch (NumberFormatException e) { - return fallback; - } - } - - private static long parseLong(String value) { - try { - return Long.parseLong(value.trim()); - } catch (NumberFormatException e) { - return 0; - } - } - - /** One in-flight {@code channelpermlist} and the entries received for it so far. */ - private static final class PermRequest { - final int channelId; - final Map values = new ConcurrentHashMap<>(); - - PermRequest(int channelId) { - this.channelId = channelId; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ChannelCodec.java b/ts3-client/core/src/main/java/com/ts3client/net/ChannelCodec.java deleted file mode 100644 index bfed8b2..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/ChannelCodec.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.ts3client.net; - -/** - * The voice codecs a channel can use, in TeamSpeak's own id order, with the editor's - * presets and what one talking client costs in bandwidth. - */ -public final class ChannelCodec { - - /** Codec names, indexed by {@link ChannelSettings#codec}. */ - public static final String[] NAMES = { - "Speex Narrowband", "Speex Wideband", "Speex Ultra-Wideband", - "CELT Mono", "Opus Voice", "Opus Music"}; - - public static final int OPUS_VOICE = 4; - public static final int OPUS_MUSIC = 5; - public static final int MAX_QUALITY = 10; - - /** The channel editor's presets; a codec and quality matching none of them is custom. */ - public enum Preset { - VOICE_MOBILE("Voice Mobile", OPUS_VOICE, 4), - VOICE_DESKTOP("Voice Desktop", OPUS_VOICE, 6), - MUSIC("Music", OPUS_MUSIC, 6); - - public final String label; - public final int codec; - public final int quality; - - Preset(String label, int codec, int quality) { - this.label = label; - this.codec = codec; - this.quality = quality; - } - - /** The preset with this codec and quality, or null for a custom setting. */ - public static Preset of(int codec, int quality) { - for (Preset p : values()) { - if (p.codec == codec && p.quality == quality) return p; - } - return null; - } - } - - /** - * Bandwidth per talking client in KiB/s at quality 0 and 10, per codec, as published by - * TeamSpeak. The steps in between are interpolated: the client shows a figure per - * quality step, and only the two ends of each codec's range are documented. - */ - private static final double[][] BANDWIDTH_RANGE = { - {2.49, 5.22}, {2.69, 7.37}, {2.73, 7.57}, {6.10, 13.92}, {2.73, 7.71}, {3.08, 11.87}}; - - private ChannelCodec() { - } - - public static String name(int codec) { - return NAMES[clampCodec(codec)]; - } - - public static int clampCodec(int codec) { - return Math.max(0, Math.min(NAMES.length - 1, codec)); - } - - /** KiB/s one talking client costs. */ - public static double bandwidth(int codec, int quality) { - double[] range = BANDWIDTH_RANGE[clampCodec(codec)]; - int q = Math.max(0, Math.min(MAX_QUALITY, quality)); - return range[0] + (range[1] - range[0]) * q / MAX_QUALITY; - } - - /** {@link #bandwidth} as the editor shows it. */ - public static String bandwidthText(int codec, int quality) { - return String.format("%.2f KiB/s", bandwidth(codec, quality)); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ChannelNode.java b/ts3-client/core/src/main/java/com/ts3client/net/ChannelNode.java deleted file mode 100644 index 211b3b8..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/ChannelNode.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.ts3client.net; - -import java.util.ArrayList; -import java.util.List; - -/** - * View-model of a TeamSpeak channel. The event thread updates it while the UI reads it, so - * every field is volatile; {@link #children} and {@link #clients} are replaced whole on each - * {@link ServerModel#buildTree()}, never changed in place. - */ -public final class ChannelNode { - public final int id; - public volatile int parentId; - public volatile int order; - public volatile String name; - public volatile String topic = ""; - public volatile String description = ""; - public volatile boolean descriptionLoaded; - public volatile boolean hasPassword; - public volatile boolean permanent; - public volatile int maxClients = -1; - /** Id of the channel's custom icon in the server's file repository, or 0 for none. */ - public volatile long iconId; - /** Whether the server sends us this channel's client list; set from the subscription events. */ - public volatile boolean subscribed; - - /** As of the last {@link ServerModel#buildTree()}; unmodifiable. */ - public volatile List children = List.of(); - public volatile List clients = List.of(); - - public ChannelNode(int id, String name) { - this.id = id; - this.name = name; - } - - /** @return whether this channel or any channel below it is subscribed */ - public boolean anySubscribed() { - if (subscribed) return true; - for (ChannelNode child : children) { - if (child.anySubscribed()) return true; - } - return false; - } - - /** @return whether this channel and every channel below it is subscribed */ - public boolean allSubscribed() { - if (!subscribed) return false; - for (ChannelNode child : children) { - if (!child.allSubscribed()) return false; - } - return true; - } - - /** @return this channel's id, followed by those of the channels below it when {@code family} */ - public List familyIds(boolean family) { - List ids = new ArrayList<>(); - collectIds(family, ids); - return ids; - } - - private void collectIds(boolean family, List into) { - into.add(id); - if (!family) return; - for (ChannelNode child : children) child.collectIds(true, into); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ChannelSettings.java b/ts3-client/core/src/main/java/com/ts3client/net/ChannelSettings.java deleted file mode 100644 index af4ce17..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/ChannelSettings.java +++ /dev/null @@ -1,219 +0,0 @@ -package com.ts3client.net; - -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * The editable properties of a channel, as read from {@code channelinfo} and written - * back with {@code channeledit}. - * - *

Kept apart from {@link ChannelNode} on purpose: the node is the live tree state the - * server pushes at us, while this is a snapshot an editor works on. Submitting compares - * the edited copy against the untouched original ({@link #changesFrom}) so only the - * properties the user actually changed are sent — TeamSpeak refuses the whole command - * when it contains one property the client may not modify, even an unchanged one. - */ -public final class ChannelSettings { - - /** How long a channel outlives its last occupant. */ - public enum Type {TEMPORARY, SEMI_PERMANENT, PERMANENT} - - /** TeamSpeak's ceiling for {@code channel_delete_delay}, in seconds. */ - public static final int MAX_DELETE_DELAY = 604800; - - public int id; - public int parentId; - public String name = ""; - public String topic = ""; - public String description = ""; - public String phoneticName = ""; - /** Whether the server reports a password on this channel; the password itself is never readable. */ - public boolean hasPassword; - /** {@code null} leaves the password alone, {@code ""} removes it, anything else sets it. */ - public String password; - public Type type = Type.PERMANENT; - public boolean defaultChannel; - /** The sibling this channel sorts after, or 0 to sort first. */ - public int order; - public int neededTalkPower; - /** TeamSpeak codec id; see {@code com.github.manevolent.ts3j.api.Codec}. */ - public int codec = 4; - public int codecQuality = 6; - public boolean encrypted = true; - public int deleteDelay; - public boolean maxClientsUnlimited = true; - public int maxClients = 16; - public boolean familyInherited = true; - public boolean familyUnlimited; - public int maxFamilyClients = 16; - public long iconId; - - /** Reads a {@code channelinfo} (or {@code channellist}) property map. */ - public static ChannelSettings from(int channelId, Map props) { - ChannelSettings s = new ChannelSettings(); - s.id = channelId; - s.parentId = intOf(props, "pid", intOf(props, "cpid", 0)); - s.name = strOf(props, "channel_name"); - s.topic = strOf(props, "channel_topic"); - s.description = strOf(props, "channel_description"); - s.phoneticName = strOf(props, "channel_name_phonetic"); - s.hasPassword = boolOf(props, "channel_flag_password"); - if (boolOf(props, "channel_flag_permanent")) s.type = Type.PERMANENT; - else if (boolOf(props, "channel_flag_semi_permanent")) s.type = Type.SEMI_PERMANENT; - else s.type = Type.TEMPORARY; - s.defaultChannel = boolOf(props, "channel_flag_default"); - s.order = intOf(props, "channel_order", 0); - s.neededTalkPower = intOf(props, "channel_needed_talk_power", 0); - s.codec = intOf(props, "channel_codec", 4); - s.codecQuality = intOf(props, "channel_codec_quality", 6); - s.encrypted = !boolOf(props, "channel_codec_is_unencrypted"); - s.deleteDelay = intOf(props, "channel_delete_delay", 0); - s.maxClientsUnlimited = boolOf(props, "channel_flag_maxclients_unlimited"); - s.maxClients = Math.max(0, intOf(props, "channel_maxclients", 16)); - s.familyInherited = boolOf(props, "channel_flag_maxfamilyclients_inherited"); - s.familyUnlimited = boolOf(props, "channel_flag_maxfamilyclients_unlimited"); - s.maxFamilyClients = Math.max(0, intOf(props, "channel_maxfamilyclients", 16)); - s.iconId = longOf(props, "channel_icon_id"); - return s; - } - - public ChannelSettings copy() { - ChannelSettings c = new ChannelSettings(); - c.id = id; - c.parentId = parentId; - c.name = name; - c.topic = topic; - c.description = description; - c.phoneticName = phoneticName; - c.hasPassword = hasPassword; - c.password = password; - c.type = type; - c.defaultChannel = defaultChannel; - c.order = order; - c.neededTalkPower = neededTalkPower; - c.codec = codec; - c.codecQuality = codecQuality; - c.encrypted = encrypted; - c.deleteDelay = deleteDelay; - c.maxClientsUnlimited = maxClientsUnlimited; - c.maxClients = maxClients; - c.familyInherited = familyInherited; - c.familyUnlimited = familyUnlimited; - c.maxFamilyClients = maxFamilyClients; - c.iconId = iconId; - return c; - } - - /** - * The {@code channeledit} parameters needed to turn {@code original} into this. - * - * @return property name to value, empty when nothing changed - */ - public Map changesFrom(ChannelSettings original) { - Map changes = new LinkedHashMap<>(); - putIfChanged(changes, "channel_name", name, original.name); - putIfChanged(changes, "channel_topic", topic, original.topic); - putIfChanged(changes, "channel_description", description, original.description); - putIfChanged(changes, "channel_name_phonetic", phoneticName, original.phoneticName); - if (password != null) changes.put("channel_password", password); - if (type != original.type) { - // The three flags are mutually exclusive and the server wants the whole set: - // clearing one without setting another leaves the channel type ambiguous. - changes.put("channel_flag_permanent", flag(type == Type.PERMANENT)); - changes.put("channel_flag_semi_permanent", flag(type == Type.SEMI_PERMANENT)); - changes.put("channel_flag_temporary", flag(type == Type.TEMPORARY)); - } - // Clearing the default flag is meaningless — some channel has to be the default — - // so only setting it is ever sent. - if (defaultChannel && !original.defaultChannel) changes.put("channel_flag_default", "1"); - putIfChanged(changes, "channel_order", order, original.order); - putIfChanged(changes, "channel_needed_talk_power", neededTalkPower, original.neededTalkPower); - putIfChanged(changes, "channel_codec", codec, original.codec); - putIfChanged(changes, "channel_codec_quality", codecQuality, original.codecQuality); - putIfChanged(changes, "channel_codec_is_unencrypted", !encrypted, !original.encrypted); - putIfChanged(changes, "channel_delete_delay", deleteDelay, original.deleteDelay); - putIfChanged(changes, "channel_flag_maxclients_unlimited", - maxClientsUnlimited, original.maxClientsUnlimited); - if (!maxClientsUnlimited) putIfChanged(changes, "channel_maxclients", maxClients, original.maxClients); - putIfChanged(changes, "channel_flag_maxfamilyclients_inherited", - familyInherited, original.familyInherited); - putIfChanged(changes, "channel_flag_maxfamilyclients_unlimited", - familyUnlimited, original.familyUnlimited); - if (!familyInherited && !familyUnlimited) { - putIfChanged(changes, "channel_maxfamilyclients", maxFamilyClients, original.maxFamilyClients); - } - if (iconId != original.iconId) changes.put("channel_icon_id", Long.toString(iconId)); - return changes; - } - - /** - * The {@code channelcreate} parameters for a channel that does not exist yet. - * - *

Everything a fresh channel would get anyway is left out, because TeamSpeak checks - * a create permission per property that is present — a client allowed to create plain - * channels but not, say, ones with a topic must not send an empty topic. What the - * server cannot infer is always sent: the name, the channel type (whose absent flags - * would silently mean temporary), the codec, and the client limits when they are not - * unlimited. - */ - public Map creationParameters() { - Map params = changesFrom(new ChannelSettings()); - params.put("channel_name", name); - params.put("channel_flag_permanent", flag(type == Type.PERMANENT)); - params.put("channel_flag_semi_permanent", flag(type == Type.SEMI_PERMANENT)); - params.put("channel_flag_temporary", flag(type == Type.TEMPORARY)); - params.put("channel_codec", Integer.toString(codec)); - params.put("channel_codec_quality", Integer.toString(codecQuality)); - if (!maxClientsUnlimited) params.put("channel_maxclients", Integer.toString(maxClients)); - if (!familyInherited && !familyUnlimited) { - params.put("channel_maxfamilyclients", Integer.toString(maxFamilyClients)); - } - if (password == null || password.isEmpty()) params.remove("channel_password"); - return params; - } - - private static void putIfChanged(Map into, String key, String value, String was) { - if (!value.equals(was)) into.put(key, value); - } - - private static void putIfChanged(Map into, String key, int value, int was) { - if (value != was) into.put(key, Integer.toString(value)); - } - - private static void putIfChanged(Map into, String key, boolean value, boolean was) { - if (value != was) into.put(key, flag(value)); - } - - private static String flag(boolean set) { - return set ? "1" : "0"; - } - - private static String strOf(Map props, String key) { - String v = props.get(key); - return v == null ? "" : v; - } - - private static boolean boolOf(Map props, String key) { - return "1".equals(props.get(key)); - } - - private static int intOf(Map props, String key, int fallback) { - try { - String v = props.get(key); - return v == null || v.isEmpty() ? fallback : Integer.parseInt(v.trim()); - } catch (NumberFormatException e) { - return fallback; - } - } - - private static long longOf(Map props, String key) { - try { - String v = props.get(key); - if (v == null || v.isEmpty()) return 0; - long id = Long.parseLong(v.trim()); - return id < 0 ? id & 0xFFFFFFFFL : id; - } catch (NumberFormatException e) { - return 0; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ClientEntry.java b/ts3-client/core/src/main/java/com/ts3client/net/ClientEntry.java deleted file mode 100644 index a14aaa8..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/ClientEntry.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.ts3client.net; - -/** - * View-model of a connected client. The event and audio threads update it while the UI reads - * it, so every field is volatile; {@link #serverGroupIds} is replaced, never changed in place. - */ -public final class ClientEntry { - public final int id; - public volatile int channelId; - public volatile String nickname; - /** How text-to-speech should say the nickname ({@code client_nickname_phonetic}). */ - public volatile String phoneticNickname = ""; - public volatile String uniqueId = ""; - public volatile int databaseId; - public volatile int type; // 0 = normal voice client, 1 = server-query - public volatile int talkPower; - /** Waiting for a moderator to grant talk power ({@code client_talk_request}). */ - public volatile boolean talkRequest; - - public volatile int[] serverGroupIds = new int[0]; - public volatile int channelGroupId; - - // Filled on demand from clientinfo. - public volatile String platform = ""; - public volatile String version = ""; - public volatile long idleTimeMs; - public volatile String description = ""; - /** MD5 of the client's avatar ({@code client_flag_avatar}); empty when they have none. */ - public volatile String avatarFlag = ""; - /** Where the server places the client ({@code client_country}), as an ISO code; empty when it cannot tell. */ - public volatile String country = ""; - /** File transfer traffic this month ({@code client_month_bytes_*}), -1 until asked for. */ - public volatile long monthBytesDownloaded = -1; - public volatile long monthBytesUploaded = -1; - - public volatile boolean talking; - public volatile boolean inputMuted; // microphone muted (client_input_muted) - public volatile boolean outputMuted; // speakers muted / deafened (client_output_muted) - /** False while the capture device is unavailable: another tab holds the microphone. */ - public volatile boolean inputHardware = true; - /** False while the playback device is unavailable. */ - public volatile boolean outputHardware = true; - public volatile boolean away; - /** The message published with the away state, empty when there is none. */ - public volatile String awayMessage = ""; - public volatile boolean channelCommander; - /** Unread messages in the client's offline message inbox ({@code client_unread_messages}). */ - public volatile int unreadMessages; - public volatile boolean self; - - public ClientEntry(int id, String nickname) { - this.id = id; - this.nickname = nickname; - } - - public boolean isQuery() { - return type == 1; - } - - public boolean inServerGroup(int groupId) { - for (int id : serverGroupIds) if (id == groupId) return true; - return false; - } - - /** Adds a server group id, if not already present. */ - public void addServerGroup(int groupId) { - int[] ids = serverGroupIds; - for (int id : ids) if (id == groupId) return; - int[] updated = java.util.Arrays.copyOf(ids, ids.length + 1); - updated[ids.length] = groupId; - serverGroupIds = updated; - } - - /** Removes a server group id, if present. */ - public void removeServerGroup(int groupId) { - int[] ids = serverGroupIds; - int index = -1; - for (int i = 0; i < ids.length; i++) { - if (ids[i] == groupId) { - index = i; - break; - } - } - if (index < 0) return; - int[] updated = new int[ids.length - 1]; - System.arraycopy(ids, 0, updated, 0, index); - System.arraycopy(ids, index + 1, updated, index, ids.length - index - 1); - serverGroupIds = updated; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ClientStatus.java b/ts3-client/core/src/main/java/com/ts3client/net/ClientStatus.java deleted file mode 100644 index 3e27c05..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/ClientStatus.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ts3client.net; - -/** - * What the channel tree shows for a client, in the order the official client gives the - * states priority: the first that applies wins. - */ -public enum ClientStatus { - QUERY, - SPEAKERS_DISABLED, - SPEAKERS_MUTED, - MIC_DISABLED, - MIC_MUTED, - AWAY, - COMMANDER_TALKING, - COMMANDER, - TALKING, - IDLE; - - public static ClientStatus of(ClientEntry c) { - if (c.isQuery()) return QUERY; - if (!c.outputHardware) return SPEAKERS_DISABLED; - if (c.outputMuted) return SPEAKERS_MUTED; - if (!c.inputHardware) return MIC_DISABLED; - if (c.inputMuted) return MIC_MUTED; - if (c.away) return AWAY; - if (c.channelCommander) return c.talking ? COMMANDER_TALKING : COMMANDER; - return c.talking ? TALKING : IDLE; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/Complaint.java b/ts3-client/core/src/main/java/com/ts3client/net/Complaint.java deleted file mode 100644 index 53f5af0..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/Complaint.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.ts3client.net; - -import java.util.Map; - -/** - * A complaint one client filed about another; the server keeps at most one per pair. - * - * @param targetDbId the database id of the client complained about - * @param fromDbId the database id of the client who complained - */ -public record Complaint(int targetDbId, String targetName, int fromDbId, String fromName, - String message, long timestampEpochSeconds) { - - /** Reads a complaint off a {@code notifycomplainlist} event's fields. */ - static Complaint from(Map fields) { - return new Complaint((int) parseLong(fields.get("tcldbid")), - orEmpty(fields.get("tname")), - (int) parseLong(fields.get("fcldbid")), - orEmpty(fields.get("fname")), - orEmpty(fields.get("message")), - parseLong(fields.get("timestamp"))); - } - - private static String orEmpty(String s) { - return s == null || s.equals("null") ? "" : s; - } - - private static long parseLong(String s) { - try { - return s == null ? 0 : Long.parseLong(s.trim()); - } catch (NumberFormatException e) { - return 0; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ComplaintAdmin.java b/ts3-client/core/src/main/java/com/ts3client/net/ComplaintAdmin.java deleted file mode 100644 index 6300828..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/ComplaintAdmin.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.ts3client.net; - -import com.github.manevolent.ts3j.command.CommandException; -import com.github.manevolent.ts3j.command.SingleCommand; -import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; -import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent; -import com.github.manevolent.ts3j.protocol.ProtocolRole; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * The server's complaints: filing, listing and removing them. - * - *

Split out of {@link TeamspeakConnection} like {@link BanAdmin}, and answered the same - * way: {@code complainlist} replies with {@code notifycomplainlist} events ahead of the - * command's own completion. Every call here blocks and must run off the UI thread; the - * connection's public wrappers do that. - */ -final class ComplaintAdmin { - - /** What {@code complainlist} answers when there are no complaints at all. */ - private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501; - /** What {@code complainadd} answers when we already complained about that client. */ - private static final int ERROR_DATABASE_DUPLICATE_ENTRY = 0x0502; - - private final TeamspeakConnection conn; - - /** The {@code complainlist} reply in progress; one request may be in flight at a time. */ - private volatile List listing; - - ComplaintAdmin(TeamspeakConnection conn) { - this.conn = conn; - } - - List list() throws Exception { - List complaints = Collections.synchronizedList(new ArrayList<>()); - listing = complaints; - try { - conn.socket().executeCommand(new SingleCommand("complainlist", ProtocolRole.CLIENT)).complete(); - conn.awaitEventsProcessed(); - } catch (CommandException e) { - if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e; - } finally { - listing = null; - } - return new ArrayList<>(complaints); - } - - void onListEntry(UnknownTeamspeakEvent e) { - List complaints = listing; - if (complaints != null) complaints.add(Complaint.from(e.getMap())); - } - - /** Files a complaint about a client; the server takes one per client from each of us. */ - void add(int targetDbId, String message) throws Exception { - try { - conn.socket().executeCommand(new SingleCommand("complainadd", ProtocolRole.CLIENT, - new CommandSingleParameter("tcldbid", Integer.toString(targetDbId)), - new CommandSingleParameter("message", message))).complete(); - } catch (CommandException e) { - if (e.getErrorId() != ERROR_DATABASE_DUPLICATE_ENTRY) throw e; - throw new IllegalStateException("Cannot add multiple complaints about the same client."); - } - } - - void delete(Complaint complaint) throws Exception { - conn.socket().executeCommand(new SingleCommand("complaindel", ProtocolRole.CLIENT, - new CommandSingleParameter("tcldbid", Integer.toString(complaint.targetDbId())), - new CommandSingleParameter("fcldbid", Integer.toString(complaint.fromDbId())))).complete(); - } - - /** Removes every complaint about one client. */ - void deleteAll(int targetDbId) throws Exception { - conn.socket().executeCommand(new SingleCommand("complaindelall", ProtocolRole.CLIENT, - new CommandSingleParameter("tcldbid", Integer.toString(targetDbId)))).complete(); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionEventHandler.java b/ts3-client/core/src/main/java/com/ts3client/net/ConnectionEventHandler.java deleted file mode 100644 index a31f229..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionEventHandler.java +++ /dev/null @@ -1,743 +0,0 @@ -package com.ts3client.net; - -import com.github.manevolent.ts3j.event.*; -import com.github.manevolent.ts3j.api.TextMessageTargetMode; -import com.ts3client.contacts.Contact; -import com.ts3client.sound.SoundEvent; -import com.ts3client.sound.SoundNotifier; - -import java.util.Map; - -/** - * The {@link TS3Listener} side of a connection: keeps {@link ServerModel} in sync with - * incoming notify events, mirrors native TeamSpeak's server-tab log lines, and picks the - * matching {@link SoundEvent} for each one. Registered alongside {@link TeamspeakConnection} - * itself (which keeps only the lifecycle-critical {@code onDisconnected} callback) so this - * class can stay focused on "event arrived, update state and tell the user" and nothing else. - */ -final class ConnectionEventHandler implements TS3Listener { - - // ---- who went where: TeamSpeak's reason ids ---- - - /** {@code reasonid} of a client view/move notification. */ - private static final int REASON_SWITCHED = 0; - private static final int REASON_MOVED = 1; - private static final int REASON_TIMEOUT = 3; - private static final int REASON_CHANNEL_KICK = 4; - private static final int REASON_SERVER_KICK = 5; - private static final int REASON_BAN = 6; - - private final TeamspeakConnection conn; - - ConnectionEventHandler(TeamspeakConnection conn) { - this.conn = conn; - } - - @Override - public void onClientJoin(ClientJoinEvent e) { - ClientEntry c = conn.getModel().putClient(e.getClientId(), e.getClientNickname(), e.getClientTargetId()); - c.type = safeInt(e, "client_type"); - c.talkPower = e.getClientTalkPower(); - c.talkRequest = talkRequested(e); - c.phoneticNickname = TeamspeakConnection.orEmpty(e.get("client_nickname_phonetic")); - c.inputMuted = e.isClientInputMuted(); - c.outputMuted = e.isClientOutputMuted(); - c.inputHardware = e.isClientUsingHardwareInput(); - c.outputHardware = e.isClientUsingHardwareOutput(); - c.away = e.isClientAway(); - c.awayMessage = TeamspeakConnection.orEmpty(e.get("client_away_message")); - c.uniqueId = TeamspeakConnection.orEmpty(e.getUniqueClientIdentifier()); - c.avatarFlag = TeamspeakConnection.orEmpty(e.get("client_flag_avatar")); - c.country = TeamspeakConnection.orEmpty(e.get("client_country")); - c.databaseId = e.getClientDatabaseId(); - c.serverGroupIds = parseIntList(e.getClientServerGroups()); - c.channelGroupId = e.getClientChannelGroupId(); - c.unreadMessages = safeInt(e, "client_unread_messages"); - c.self = (e.getClientId() == conn.getSelfClientId()); - // Query clients stay out of sight, as they do in the tree and in TS3's log. - if (!c.self && !c.isQuery()) { - conn.applyContact(c); - announceClientEntered(e); - logClientEntered(e); - } - conn.ui.onModelChanged(); - } - - @Override - public void onClientLeave(ClientLeaveEvent e) { - ClientEntry gone = conn.getModel().getClient(e.getClientId()); - if (e.getClientId() == conn.getSelfClientId()) { - announceOwnRemoval(safeInt(e, "reasonid"), e); - } else if (gone == null || !gone.isQuery()) { - String name = conn.clientLink(e.getClientId()); - announceClientLeft(e); - logClientLeft(e, name); - } - conn.getModel().removeClient(e.getClientId()); - if (conn.getPlayback() != null) conn.getPlayback().removeClient(e.getClientId()); - conn.ui.onModelChanged(); - } - - @Override - public void onClientMoved(ClientMovedEvent e) { - ClientEntry c = conn.getModel().getClient(e.getClientId()); - if (c != null) { - int from = c.channelId; - c.channelId = e.getTargetChannelId(); - if (e.getClientId() == conn.getSelfClientId()) { - conn.getModel().enteredChannel(e.getTargetChannelId()); - announceOwnMove(safeInt(e, "reasonid"), e); - logOwnMove(e, from, e.getTargetChannelId()); - } else if (!c.isQuery()) { - announceClientMoved(safeInt(e, "reasonid"), e.getClientId(), from, e.getTargetChannelId()); - logClientMoved(e, conn.clientLink(c.id), from, e.getTargetChannelId()); - } - conn.ui.onModelChanged(); - } - } - - /** A client became visible to us, logged the way native TS3's server tab does. */ - private void logClientEntered(ClientJoinEvent e) { - String name = conn.clientLink(e.getClientId(), - TeamspeakConnection.orEmpty(e.getUniqueClientIdentifier()), e.getClientNickname()); - // A client connecting also comes with "switched", only from no channel at all. - int reason = safeInt(e, "reasonid"); - if (reason == REASON_SWITCHED && e.getClientFromId() == 0) reason = -1; - switch (reason) { - case REASON_MOVED: - conn.log(name + " appears, coming from channel \"" + conn.channelLink(e.getClientFromId()) + "\""); - break; - case REASON_CHANNEL_KICK: - conn.log(name + " appears, was kicked from channel \"" + conn.channelLink(e.getClientFromId()) - + "\" by " + invokerName(e)); - break; - case REASON_SWITCHED: - conn.log(name + " switched to channel \"" + conn.channelLink(e.getClientTargetId()) - + "\", coming from channel \"" + conn.channelLink(e.getClientFromId()) + "\""); - break; - default: - conn.log(name + " connected to channel \"" + conn.channelLink(e.getClientTargetId()) + "\""); - } - } - - /** A client stopped being visible to us. */ - private void logClientLeft(ClientLeaveEvent e, String name) { - String reasonMsg = TeamspeakConnection.orEmpty(e.get("reasonmsg")); - String suffix = reasonMsg.isEmpty() ? "" : " (" + reasonMsg + ")"; - int reason = safeInt(e, "reasonid"); - // A client leaving the server may also come with "switched", only to no channel at all. - if (reason == REASON_SWITCHED && e.getClientTargetId() == 0) reason = -1; - switch (reason) { - case REASON_TIMEOUT: - conn.log(name + " dropped (ping timeout)"); - break; - case REASON_SERVER_KICK: - conn.log(name + " was kicked from the server by " + invokerName(e) + suffix); - break; - case REASON_BAN: - conn.log(name + " was banned from the server by " + invokerName(e) + suffix); - break; - case REASON_CHANNEL_KICK: - conn.log(name + " left: was kicked to channel \"" + conn.channelLink(e.getClientTargetId()) - + "\" by " + invokerName(e) + suffix); - break; - case REASON_MOVED: - conn.log(name + " left, heading to channel \"" + conn.channelLink(e.getClientTargetId()) + "\""); - break; - case REASON_SWITCHED: - conn.log(name + " left, switched to channel \"" + conn.channelLink(e.getClientTargetId()) + "\""); - break; - default: - conn.log(name + " disconnected"); - } - } - - /** A client we can see moved between two channels we can see. */ - private void logClientMoved(ClientMovedEvent e, String name, int fromChannel, int toChannel) { - String reasonMsg = TeamspeakConnection.orEmpty(e.get("reasonmsg")); - String suffix = reasonMsg.isEmpty() ? "" : " (" + reasonMsg + ")"; - switch (safeInt(e, "reasonid")) { - case REASON_MOVED: - conn.log(name + " was moved from channel \"" + conn.channelLink(fromChannel) + "\" to \"" - + conn.channelLink(toChannel) + "\" by " + invokerName(e)); - break; - case REASON_CHANNEL_KICK: - conn.log(name + " was kicked from channel \"" + conn.channelLink(fromChannel) + "\" to \"" - + conn.channelLink(toChannel) + "\" by " + invokerName(e) + suffix); - break; - default: - conn.log(name + " switched from channel \"" + conn.channelLink(fromChannel) + "\" to \"" - + conn.channelLink(toChannel) + "\""); - } - } - - /** Our own move between channels, logged the way TS3 does for everyone else. */ - private void logOwnMove(ClientMovedEvent e, int fromChannel, int toChannel) { - String reasonMsg = TeamspeakConnection.orEmpty(e.get("reasonmsg")); - String suffix = reasonMsg.isEmpty() ? "" : " (" + reasonMsg + ")"; - switch (safeInt(e, "reasonid")) { - case REASON_MOVED: - conn.log("You were moved from channel \"" + conn.channelLink(fromChannel) + "\" to \"" - + conn.channelLink(toChannel) + "\" by " + invokerName(e)); - break; - case REASON_CHANNEL_KICK: - conn.log("You were kicked from channel \"" + conn.channelLink(fromChannel) + "\" to \"" - + conn.channelLink(toChannel) + "\" by " + invokerName(e) + suffix); - break; - default: - conn.log("You switched from channel \"" + conn.channelLink(fromChannel) + "\" to \"" - + conn.channelLink(toChannel) + "\""); - } - } - - /** - * A client became visible: either they just connected, or they moved in from a - * channel we could not see — TeamSpeak's "appears" case. - */ - private void announceClientEntered(ClientJoinEvent e) { - if (!conn.isConnected()) return; - int clientId = e.getClientId(); - boolean current = conn.inOwnChannel(e.getClientTargetId()); - Map vars = conn.clientVars(clientId, e.getClientNickname()); - switch (safeInt(e, "reasonid")) { - case REASON_MOVED: - conn.sound(current ? SoundEvent.CLIENT_MOVED_TO_CURRENT_CHANNEL_APPEARS - : SoundEvent.CLIENT_MOVED_TO_OTHER_CHANNEL_APPEARS, vars); - break; - case REASON_CHANNEL_KICK: - conn.sound(current ? SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_TO_CURRENT_CHANNEL_APPEARS - : SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_TO_OTHER_CHANNEL_APPEARS, vars); - break; - case REASON_SWITCHED: - conn.sound(current ? SoundEvent.CLIENT_SWITCHED_TO_CURRENT_CHANNEL_APPEARS - : SoundEvent.CLIENT_SWITCHED_TO_OTHER_CHANNEL_APPEARS, vars); - break; - default: - conn.sound(current ? SoundEvent.CLIENT_CONNECTION_CONNECTED_CURRENT_CHANNEL - : SoundEvent.CLIENT_CONNECTION_CONNECTED_SERVER, vars); - } - } - - /** A client stopped being visible: they left the server, or moved out of sight. */ - private void announceClientLeft(ClientLeaveEvent e) { - if (!conn.isConnected()) return; - int clientId = e.getClientId(); - boolean current = conn.inOwnChannel(e.getClientFromId()); - Map vars = conn.clientVars(clientId, null); - switch (safeInt(e, "reasonid")) { - case REASON_TIMEOUT: - conn.sound(current ? SoundEvent.CLIENT_CONNECTION_LOST_CONNECTION_CURRENT_CHANNEL - : SoundEvent.CLIENT_CONNECTION_LOST_CONNECTION_SERVER, vars); - break; - case REASON_SERVER_KICK: - conn.sound(current ? SoundEvent.CLIENT_WAS_KICKED_FROM_SERVER_CURRENT_CHANNEL - : SoundEvent.CLIENT_WAS_KICKED_FROM_SERVER_SERVER, vars); - break; - case REASON_BAN: - conn.sound(current ? SoundEvent.CLIENT_WAS_BANNED_CURRENT_CHANNEL - : SoundEvent.CLIENT_WAS_BANNED_SERVER, vars); - break; - case REASON_CHANNEL_KICK: - conn.sound(current ? SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_FROM_CURRENT_CHANNEL_DISAPPEARS - : SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_TO_OTHER_CHANNEL_DISAPPEARS, vars); - break; - case REASON_MOVED: - conn.sound(current ? SoundEvent.CLIENT_MOVED_FROM_CURRENT_CHANNEL_DISAPPEARS - : SoundEvent.CLIENT_MOVED_TO_OTHER_CHANNEL_DISAPPEARS, vars); - break; - case REASON_SWITCHED: - conn.sound(current ? SoundEvent.CLIENT_SWITCHED_FROM_CURRENT_CHANNEL_DISAPPEARS - : SoundEvent.CLIENT_SWITCHED_TO_OTHER_CHANNEL_DISAPPEARS, vars); - break; - default: - conn.sound(current ? SoundEvent.CLIENT_CONNECTION_DISCONNECTED_CURRENT_CHANNEL - : SoundEvent.CLIENT_CONNECTION_DISCONNECTED_SERVER, vars); - } - } - - /** A client we can see moved between two channels we can see ("stays"). */ - private void announceClientMoved(int reason, int clientId, int fromChannel, int toChannel) { - if (!conn.isConnected()) return; - boolean toCurrent = conn.inOwnChannel(toChannel); - boolean fromCurrent = conn.inOwnChannel(fromChannel); - Map vars = conn.clientVars(clientId, null); - switch (reason) { - case REASON_MOVED: - conn.sound(toCurrent ? SoundEvent.CLIENT_MOVED_TO_CURRENT_CHANNEL_STAYS - : fromCurrent ? SoundEvent.CLIENT_MOVED_FROM_CURRENT_CHANNEL_STAYS - : SoundEvent.CLIENT_MOVED_TO_OTHER_CHANNEL_STAYS, vars); - break; - case REASON_CHANNEL_KICK: - conn.sound(toCurrent ? SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_TO_CURRENT_CHANNEL_STAYS - : fromCurrent ? SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_FROM_CURRENT_CHANNEL_STAYS - : SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_TO_OTHER_CHANNEL_STAYS, vars); - break; - default: - conn.sound(toCurrent ? SoundEvent.CLIENT_SWITCHED_TO_CURRENT_CHANNEL_STAYS - : fromCurrent ? SoundEvent.CLIENT_SWITCHED_FROM_CURRENT_CHANNEL_STAYS - : SoundEvent.CLIENT_SWITCHED_TO_OTHER_CHANNEL_STAYS, vars); - } - } - - /** We changed channel ourselves, or somebody changed it for us. */ - private void announceOwnMove(int reason, ClientMovedEvent e) { - if (!conn.isConnected()) return; - Map vars = conn.channelVars(e.getTargetChannelId(), e.get("invokername")); - switch (reason) { - case REASON_MOVED: - conn.sound(SoundEvent.YOU_WERE_MOVED_TO_DIFFERENT_CHANNEL, vars); - break; - case REASON_CHANNEL_KICK: - conn.sound(SoundEvent.YOU_WERE_KICKED_FROM_CHANNEL, vars); - break; - default: - conn.sound(SoundEvent.YOU_SWITCHED_CHANNEL, vars); - } - } - - /** We were removed from the server (kick or ban); the disconnect follows. */ - private void announceOwnRemoval(int reason, ClientLeaveEvent e) { - if (!conn.isConnected()) return; - Map vars = SoundNotifier.vars( - "servername", conn.getModel().getServerName(), - "clientname", TeamspeakConnection.orEmpty(e.get("invokername")), - "reason", TeamspeakConnection.orEmpty(e.get("reasonmsg"))); - if (reason == REASON_SERVER_KICK) { - conn.sound(SoundEvent.YOU_WERE_KICKED_FROM_SERVER, vars); - } else if (reason == REASON_BAN) { - conn.sound(SoundEvent.YOU_WERE_BANNED, vars); - } - } - - @Override - public void onClientChanged(ClientUpdatedEvent e) { - ClientEntry c = conn.getModel().getClient(e.getClientId()); - if (c == null) return; - boolean renamed = has(e, "client_nickname") && !e.get("client_nickname").equals(c.nickname); - String oldName = c.nickname; - if (renamed) c.nickname = e.get("client_nickname"); - if (has(e, "client_input_muted")) c.inputMuted = e.getBoolean("client_input_muted"); - if (has(e, "client_output_muted")) c.outputMuted = e.getBoolean("client_output_muted"); - if (has(e, "client_input_hardware")) c.inputHardware = e.getBoolean("client_input_hardware"); - if (has(e, "client_output_hardware")) c.outputHardware = e.getBoolean("client_output_hardware"); - if (has(e, "client_away")) { - c.away = e.getBoolean("client_away"); - // Both fields travel together, so an absent message here means "no message" - // — which `has` cannot tell from "not reported". - c.awayMessage = c.away ? TeamspeakConnection.orEmpty(e.get("client_away_message")) : ""; - } else if (reported(e, "client_away_message")) { - c.awayMessage = TeamspeakConnection.orEmpty(e.get("client_away_message")); - } - if (has(e, "client_talk_power")) c.talkPower = e.getInt("client_talk_power"); - if (has(e, "client_talk_request")) c.talkRequest = talkRequested(e); - if (reported(e, "client_nickname_phonetic")) { - c.phoneticNickname = TeamspeakConnection.orEmpty(e.get("client_nickname_phonetic")); - } - if (reported(e, "client_description")) { - c.description = TeamspeakConnection.orEmpty(e.get("client_description")); - conn.ui.onInfoUpdated(); - } - // The answer to clientgetvariables. - if (has(e, "client_version") || has(e, "client_platform")) { - if (has(e, "client_version")) c.version = e.get("client_version"); - if (has(e, "client_platform")) c.platform = e.get("client_platform"); - conn.ui.onInfoUpdated(); - } - if (has(e, "client_month_bytes_downloaded")) - c.monthBytesDownloaded = TeamspeakConnection.safeLong(e, "client_month_bytes_downloaded"); - if (has(e, "client_month_bytes_uploaded")) - c.monthBytesUploaded = TeamspeakConnection.safeLong(e, "client_month_bytes_uploaded"); - if (has(e, "client_is_channel_commander")) - c.channelCommander = e.getBoolean("client_is_channel_commander"); - if (reported(e, "client_flag_avatar")) c.avatarFlag = TeamspeakConnection.orEmpty(e.get("client_flag_avatar")); - if (reported(e, "client_country")) c.country = TeamspeakConnection.orEmpty(e.get("client_country")); - if (has(e, "client_unread_messages")) { - int before = c.unreadMessages; - c.unreadMessages = safeInt(e, "client_unread_messages"); - if (c.id == conn.getSelfClientId()) conn.unreadMessagesChanged(before); - } - announceClientUpdate(e, c, renamed, oldName); - conn.ui.onModelChanged(); - } - - /** Renames, talk-power changes and recording flags all arrive as a client update. */ - private void announceClientUpdate(ClientUpdatedEvent e, ClientEntry c, boolean renamed, String oldName) { - if (!conn.isConnected()) return; - boolean self = c.id == conn.getSelfClientId(); - Map vars = conn.clientVars(c.id, null); - - if (renamed) { - conn.sound(safeInt(e, "invokerid") == conn.getSelfClientId() - ? SoundEvent.CLIENT_RENAMED_BY_YOU : SoundEvent.CLIENT_RENAMED_BY_OTHER, vars); - conn.log(oldName + " is now known as " + conn.clientLink(c.id)); - } - if (has(e, "client_talk_request") && talkRequested(e) && !self) { - conn.sound(SoundEvent.CLIENT_REQUESTED_TALK_POWER, vars); - } - if (self && has(e, "client_is_talker")) { - conn.sound(e.getBoolean("client_is_talker") - ? SoundEvent.YOU_WERE_GRANTED_TALK_POWER : SoundEvent.YOU_WERE_REVOKED_TALK_POWER, vars); - } - if (!self && has(e, "client_is_recording")) { - boolean recording = e.getBoolean("client_is_recording"); - if (!recording) { - conn.sound(SoundEvent.CLIENT_RECORDING_STOP, vars); - } else { - conn.sound(conn.inOwnChannel(c.channelId) - ? SoundEvent.CLIENT_RECORDING_IN_CHANNEL : SoundEvent.CLIENT_RECORDING_START, vars); - } - } - } - - @Override - public void onChannelCreate(ChannelCreateEvent e) { - int cid = e.getChannelId(); - int pid = safeInt(e, "cpid"); - if (pid == 0) pid = safeInt(e, "pid"); - int order = safeInt(e, "channel_order"); - ChannelNode node = conn.getModel().putChannel(cid, e.get("channel_name"), pid, order); - applyChannelProperties(node, e); - conn.getModel().relinkChannel(cid, pid, order); - if (conn.isConnected()) { - conn.sound(byInvoker(e, SoundEvent.CHANNEL_CREATED_BY_YOU, SoundEvent.CHANNEL_CREATED_BY_OTHER, - SoundEvent.CHANNEL_CREATED_BY_OTHER), conn.channelVars(cid, e.get("invokername"))); - conn.log("Channel \"" + conn.channelLink(cid) + "\" was created by " + invokerName(e)); - } - conn.ui.onModelChanged(); - } - - @Override - public void onChannelDeleted(ChannelDeletedEvent e) { - int cid = e.getChannelId(); - if (conn.isConnected()) { - conn.sound(byInvoker(e, SoundEvent.CHANNEL_DELETED_BY_YOU, SoundEvent.CHANNEL_DELETED_BY_OTHER, - SoundEvent.CHANNEL_DELETED_BY_SERVER), conn.channelVars(cid, e.get("invokername"))); - conn.log("Channel \"" + conn.channelName(cid) + "\" was deleted by " + invokerName(e)); - } - conn.getModel().removeChannel(cid); - conn.ui.onModelChanged(); - } - - @Override - public void onChannelEdit(ChannelEditedEvent e) { - ChannelNode ch = conn.getModel().getChannel(safeInt(e, "cid")); - if (ch == null) return; - // The answer to channelgetdescription; an empty description comes as a bare key. - if (reported(e, "channel_description")) { - ch.description = TeamspeakConnection.orEmpty(e.get("channel_description")); - ch.descriptionLoaded = true; - conn.ui.onInfoUpdated(); - } - // That answer has no invoker: nothing was edited. - if (!e.getMap().containsKey("invokerid")) return; - applyChannelProperties(ch, e); - // Sorting among the same siblings arrives here too, and TS3 announces it as an edit. - if (has(e, "channel_order")) conn.getModel().relinkChannel(ch.id, ch.parentId, e.getInt("channel_order")); - if (conn.isConnected()) { - boolean current = conn.inOwnChannel(ch.id); - conn.sound(current - ? byInvoker(e, SoundEvent.CHANNEL_EDITED_CURRENT_BY_YOU, - SoundEvent.CHANNEL_EDITED_CURRENT_BY_OTHER, SoundEvent.CHANNEL_EDITED_CURRENT_BY_OTHER) - : byInvoker(e, SoundEvent.CHANNEL_EDITED_OTHER_BY_YOU, - SoundEvent.CHANNEL_EDITED_OTHER_BY_OTHER, SoundEvent.CHANNEL_EDITED_OTHER_BY_SERVER), - conn.channelVars(ch.id, e.get("invokername"))); - conn.log("Channel \"" + conn.channelLink(ch.id) + "\" was edited by " + invokerName(e)); - } - conn.ui.onModelChanged(); - } - - /** The properties a channel event carries that the model keeps; each only when present. */ - private static void applyChannelProperties(ChannelNode ch, BaseEvent e) { - if (has(e, "channel_name")) ch.name = e.get("channel_name"); - // An emptied topic arrives as a bare key, which has() would skip. - if (reported(e, "channel_topic")) ch.topic = TeamspeakConnection.orEmpty(e.get("channel_topic")); - if (has(e, "channel_icon_id")) ch.iconId = TeamspeakConnection.safeLong(e, "channel_icon_id"); - if (has(e, "channel_flag_password")) ch.hasPassword = e.getBoolean("channel_flag_password"); - if (has(e, "channel_flag_permanent")) ch.permanent = e.getBoolean("channel_flag_permanent"); - if (has(e, "channel_flag_maxclients_unlimited") && e.getBoolean("channel_flag_maxclients_unlimited")) { - ch.maxClients = -1; - } else if (has(e, "channel_maxclients")) { - ch.maxClients = safeInt(e, "channel_maxclients"); - } - } - - /** - * Descriptions never travel with the notify, so a cached one has to be re-fetched. - * Only channels whose description was already loaded are refreshed; the rest pick the - * new text up the first time they are looked at. - */ - @Override - public void onChannelDescriptionChanged(ChannelDescriptionEditedEvent e) { - ChannelNode ch = conn.getModel().getChannel(safeInt(e, "cid")); - if (ch == null || !ch.descriptionLoaded) return; - ch.descriptionLoaded = false; - conn.requestChannelInfo(ch.id); - } - - @Override - public void onChannelMoved(ChannelMovedEvent e) { - ChannelNode ch = conn.getModel().getChannel(safeInt(e, "cid")); - if (ch == null) return; - int parent = has(e, "cpid") ? e.getInt("cpid") : ch.parentId; - int order = has(e, "order") ? e.getInt("order") : ch.order; - conn.getModel().relinkChannel(ch.id, parent, order); - if (conn.isConnected()) { - conn.sound(byInvoker(e, SoundEvent.CHANNEL_MOVED_BY_YOU, SoundEvent.CHANNEL_MOVED_BY_OTHER, - SoundEvent.CHANNEL_MOVED_BY_OTHER), conn.channelVars(ch.id, e.get("invokername"))); - String newParent = parent == 0 ? conn.getModel().getServerName() : conn.channelLink(parent); - conn.log("Channel \"" + conn.channelLink(ch.id) + "\" was moved by " + invokerName(e) - + ", new parent channel is \"" + newParent + "\""); - } - conn.ui.onModelChanged(); - } - - @Override - public void onChannelSubscribed(ChannelSubscribedEvent e) { - setSubscribed(safeInt(e, "cid"), true); - } - - @Override - public void onChannelUnsubscribed(ChannelUnsubscribedEvent e) { - setSubscribed(safeInt(e, "cid"), false); - } - - private void setSubscribed(int cid, boolean subscribed) { - ChannelNode ch = conn.getModel().getChannel(cid); - if (ch == null || ch.subscribed == subscribed) return; - ch.subscribed = subscribed; - conn.ui.onModelChanged(); - } - - @Override - public void onServerEdit(ServerEditedEvent e) { - if (has(e, "virtualserver_name")) conn.getModel().setServerName(e.get("virtualserver_name")); - conn.getModel().putServerProperties(e.getMap()); - if (conn.isConnected()) { - conn.sound(byInvoker(e, SoundEvent.SERVER_EDITED_BY_YOU, SoundEvent.SERVER_EDITED_BY_OTHER, - SoundEvent.SERVER_EDITED_BY_OTHER), conn.serverVars()); - } - conn.ui.onModelChanged(); - } - - @Override - public void onServerGroupClientAdded(ServerGroupClientAddedEvent e) { - ClientEntry c = conn.getModel().getClient(e.getClientId()); - if (c != null) c.addServerGroup(e.getServerGroupId()); - boolean self = e.getClientId() == conn.getSelfClientId(); - if (self) conn.requestSelfPowers(); - conn.sound(self - ? byInvoker(e, SoundEvent.YOU_SERVERGROUP_ADDED_BY_USER, SoundEvent.YOU_SERVERGROUP_ADDED_BY_USER, - SoundEvent.YOU_SERVERGROUP_ADDED_BY_SERVER) - : byInvoker(e, SoundEvent.CLIENT_SERVERGROUP_ADDED_BY_USER, - SoundEvent.CLIENT_SERVERGROUP_ADDED_BY_USER, SoundEvent.CLIENT_SERVERGROUP_ADDED_BY_SERVER), - groupVars(e.getClientId(), serverGroupName(e.getServerGroupId()))); - conn.log(clientLogName(e.getClientId()) + " was added to server group \"" + serverGroupName(e.getServerGroupId()) - + "\" by " + invokerName(e) + "."); - conn.ui.onModelChanged(); - } - - @Override - public void onServerGroupClientDeleted(ServerGroupClientDeletedEvent e) { - int clientId = safeInt(e, "clid"); - ClientEntry c = conn.getModel().getClient(clientId); - if (c != null) c.removeServerGroup(e.getServerGroupId()); - boolean self = clientId == conn.getSelfClientId(); - if (self) conn.requestSelfPowers(); - conn.sound(self - ? byInvoker(e, SoundEvent.YOU_SERVERGROUP_REMOVED_BY_USER, - SoundEvent.YOU_SERVERGROUP_REMOVED_BY_USER, SoundEvent.YOU_SERVERGROUP_REMOVED_BY_SERVER) - : byInvoker(e, SoundEvent.CLIENT_SERVERGROUP_REMOVED_BY_USER, - SoundEvent.CLIENT_SERVERGROUP_REMOVED_BY_USER, SoundEvent.CLIENT_SERVERGROUP_REMOVED_BY_SERVER), - groupVars(clientId, serverGroupName(e.getServerGroupId()))); - conn.log(clientLogName(clientId) + " was removed from server group \"" + serverGroupName(e.getServerGroupId()) - + "\" by " + invokerName(e) + "."); - conn.ui.onModelChanged(); - } - - @Override - public void onClientChannelGroupChanged(ClientChannelGroupChangedEvent e) { - ClientEntry c = conn.getModel().getClient(e.getClientId()); - if (c != null) c.channelGroupId = e.getChannelGroupId(); - boolean self = e.getClientId() == conn.getSelfClientId(); - if (self) conn.requestSelfPowers(); - String groupName = conn.getModel().channelGroupName(e.getChannelGroupId()); - conn.sound(self - ? byInvoker(e, SoundEvent.YOU_CHANNELGROUP_CHANGED_BY_USER, - SoundEvent.YOU_CHANNELGROUP_CHANGED_BY_USER, SoundEvent.YOU_CHANNELGROUP_CHANGED_BY_SERVER) - : byInvoker(e, SoundEvent.CLIENT_CHANNELGROUP_CHANGED_BY_USER, - SoundEvent.CLIENT_CHANNELGROUP_CHANGED_BY_USER, SoundEvent.CLIENT_CHANNELGROUP_CHANGED_BY_SERVER), - groupVars(e.getClientId(), groupName)); - conn.log("Channel group \"" + TeamspeakConnection.orEmpty(groupName) + "\" was assigned to " - + clientLogName(e.getClientId()) + " by " + invokerName(e) + "."); - conn.ui.onModelChanged(); - } - - /** - * The group's own name. The notify's {@code name} field is misleading: TeamSpeak fills - * it with the client's nickname, not the group's. - */ - private String serverGroupName(int groupId) { - Group g = conn.getModel().serverGroup(groupId); - return g != null ? g.name : "#" + groupId; - } - - /** A client's name for a log line, as a link, falling back to its id once it has left. */ - private String clientLogName(int clientId) { - return conn.clientLink(clientId); - } - - /** Picks the event variant matching who caused the change: us, another client, or the server. */ - private SoundEvent byInvoker(BaseEvent e, SoundEvent byYou, SoundEvent byOther, SoundEvent byServer) { - int invoker = safeInt(e, "invokerid"); - if (invoker == conn.getSelfClientId() && invoker != 0) return byYou; - return invoker == 0 ? byServer : byOther; - } - - private Map groupVars(int clientId, String groupName) { - Map vars = conn.clientVars(clientId, null); - vars.put("groupname", TeamspeakConnection.orEmpty(groupName)); - return vars; - } - - @Override - public void onChannelList(ChannelListEvent e) { - // Incremental channel arriving during connect. - int cid = e.getChannelId(); - ChannelNode node = conn.getModel().putChannel(cid, e.get("channel_name"), - safeInt(e, "cpid"), safeInt(e, "channel_order")); - applyChannelProperties(node, e); - } - - @Override - public void onServerGroupList(ServerGroupListEvent e) { - int id = safeInt(e, "sgid"); - if (id > 0) conn.getModel().putServerGroup(toGroup(e, id)); - } - - @Override - public void onChannelGroupList(ChannelGroupListEvent e) { - int id = safeInt(e, "cgid"); - if (id > 0) conn.getModel().putChannelGroup(toGroup(e, id)); - } - - private static Group toGroup(BaseEvent e, int id) { - return new Group(id, e.get("name"), TeamspeakConnection.safeLong(e, "iconid"), safeInt(e, "sortid"), - safeInt(e, "type"), safeInt(e, "n_member_addp"), safeInt(e, "n_member_removep")); - } - - @Override - public void onPermissionList(PermissionListEvent e) { - conn.getModel().putPermissionName(e.get("permname")); - } - - @Override - public void onClientNeededPermissions(ClientNeededPermissionsEvent e) { - conn.getModel().putSelfPermissionValue(safeInt(e, "permid"), safeInt(e, "permvalue")); - } - - @Override - public void onTextMessage(TextMessageEvent e) { - if (e.getInvokerId() == conn.getSelfClientId()) return; // don't echo our own - Contact contact = conn.contacts.find(e.getInvokerUniqueId()); - if (contact != null) { - boolean isPrivate = e.getTargetMode() == TextMessageTargetMode.CLIENT; - if (isPrivate ? contact.ignorePrivateMessages : contact.ignorePublicMessages) return; - } - ConnectionListener.ChatScope scope; - SoundEvent notification; - switch (e.getTargetMode()) { - case CLIENT: - scope = ConnectionListener.ChatScope.PRIVATE; - notification = SoundEvent.CHAT_RECEIVED_MESSAGE_CLIENT; - break; - case CHANNEL: - scope = ConnectionListener.ChatScope.CHANNEL; - notification = SoundEvent.CHAT_RECEIVED_MESSAGE_CHANNEL; - break; - default: - scope = ConnectionListener.ChatScope.SERVER; - notification = SoundEvent.CHAT_RECEIVED_MESSAGE_SERVER; - break; - } - conn.persistIncomingChat(scope, e.getInvokerId(), e.getInvokerUniqueId(), e.getInvokerName(), e.getMessage()); - conn.sound(notification, conn.clientVars(e.getInvokerId(), e.getInvokerName())); - conn.ui.onChat(scope, e.getInvokerId(), e.getInvokerUniqueId(), e.getInvokerName(), e.getMessage()); - } - - @Override - public void onClientPoke(ClientPokeEvent e) { - Contact contact = conn.contacts.find(e.getInvokerUniqueId()); - if (contact != null && contact.ignorePokes) return; - conn.sound(SoundEvent.OTHER_RECEIVED_POKE, conn.clientVars(e.getInvokerId(), e.getInvokerName())); - String from = conn.contacts.displayName(e.getInvokerUniqueId(), TeamspeakConnection.orEmpty(e.getInvokerName())); - conn.ui.onPoke(from, TeamspeakConnection.orEmpty(e.get("msg"))); - } - - @Override - public void onUnknownEvent(UnknownTeamspeakEvent e) { - if ("notifyconnectioninfo".equals(e.getCommand())) conn.stats.onReport(e); - else if ("notifychannelpermlist".equals(e.getCommand())) conn.channels.onPermListEntry(e); - else if ("notifybanlist".equals(e.getCommand())) conn.bans.onListEntry(e); - else if ("notifytokenlist".equals(e.getCommand())) conn.privilegeKeys.onListEntry(e); - else if ("notifytokenadd".equals(e.getCommand())) conn.privilegeKeys.onAdded(e); - else if ("notifycomplainlist".equals(e.getCommand())) conn.complaints.onListEntry(e); - else if ("notifyserverlog".equals(e.getCommand())) conn.serverLog.onLine(e); - else conn.offlineMessages.onReply(e); - } - - // ---- helpers ---- - - /** Who caused an event, linked where the server named them; "the server" when nobody did. */ - private String invokerName(BaseEvent e) { - String name = TeamspeakConnection.orEmpty(e.get("invokername")); - if (name.isEmpty()) return "the server"; - return conn.clientLink(safeInt(e, "invokerid"), - TeamspeakConnection.orEmpty(e.get("invokeruid")), name); - } - - /** {@code client_talk_request} holds the request's timestamp, or 0 when there is none. */ - private static boolean talkRequested(BaseEvent e) { - String v = e.get("client_talk_request"); - return v != null && !v.isBlank() && !v.trim().equals("0"); - } - - private static int safeInt(BaseEvent e, String key) { - try { - String v = e.get(key); - return v == null ? 0 : Integer.parseInt(v.trim()); - } catch (Exception ex) { - return 0; - } - } - - /** - * Whether the event actually carries a field. ts3j answers a missing key with an - * empty string rather than null, so a plain null check is always true — and a - * partial update (say, someone muting) would otherwise look like it reported - * every other field as well. - */ - private static boolean has(BaseEvent e, String key) { - String value = e.get(key); - return value != null && !value.isEmpty(); - } - - /** Whether the event carries a field at all, even empty: for text that can be cleared. */ - private static boolean reported(BaseEvent e, String key) { - return e.getMap().containsKey(key); - } - - /** Parses a comma-separated id list (e.g. server groups "6,12,15"). */ - private static int[] parseIntList(String csv) { - if (csv == null || csv.isEmpty()) return new int[0]; - String[] parts = csv.split(","); - int[] out = new int[parts.length]; - int n = 0; - for (String p : parts) { - try { - out[n++] = Integer.parseInt(p.trim()); - } catch (NumberFormatException ignored) { - } - } - return n == parts.length ? out : java.util.Arrays.copyOf(out, n); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionListener.java b/ts3-client/core/src/main/java/com/ts3client/net/ConnectionListener.java deleted file mode 100644 index dc276ff..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionListener.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.ts3client.net; - -import java.util.List; - -/** - * UI-facing callbacks fired by {@link TeamspeakConnection}. Implementations are - * responsible for marshalling to the Swing EDT. - */ -public interface ConnectionListener { - - /** Message scope for chat display. */ - enum ChatScope {SERVER, CHANNEL, PRIVATE} - - void onStatus(String status); - - void onConnected(); - - void onDisconnected(String reason); - - /** The channel/client model changed and any tree view should be rebuilt. */ - void onModelChanged(); - - /** On-demand channel/client details finished loading; refresh any info view. */ - void onInfoUpdated(); - - /** A group icon finished downloading; repaint anything showing icons. */ - void onIconsUpdated(); - - void onChat(ChatScope scope, int fromClientId, String fromUniqueId, String fromName, String message); - - /** Previously persisted TS3 HTML log entries for one chat scope. */ - default void onChatHistory(ChatScope scope, List htmlEntries) { - } - - /** Previously persisted TS3 HTML log entries for a private chat. */ - default void onPrivateChatHistory(int clientId, String nickname, List htmlEntries) { - } - - /** A client (possibly the local one) started or stopped talking. */ - void onTalkStateChanged(int clientId, boolean talking); - - void onError(String message); - - /** Someone poked the local client. */ - void onPoke(String fromName, String message); - - /** - * Something happened on the server that native TS3 records in the server - * log: a client connecting/disconnecting/moving, a channel being edited, - * a group being (un)assigned, and so on. - */ - void onServerLog(String message); - - /** Our offline message inbox's unread count changed, or became known on connecting. */ - default void onUnreadMessagesChanged(int unread) { - } - - /** A server-log line already rendered in TS3's HTML log format. */ - default void onServerLogHtml(String html) { - onServerLog(html == null ? "" : html); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStats.java b/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStats.java deleted file mode 100644 index 1c8ccc2..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStats.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.ts3client.net; - -import com.ts3client.audio.VoiceReceiveStats; - -import java.util.EnumMap; -import java.util.Map; - -/** - * A snapshot of a client's connection statistics, as shown in the Connection - * Info window. Values default to {@code -1} meaning "unknown / not reported", - * which callers should render as a dash. - * - *

Traffic is seen from the client's side, as TeamSpeak shows it: in is what - * the client received, out what it sent. For a remote client the figures come - * from {@code notifyconnectioninfo} (the server relays the client's own counters, plus - * the loss it measured itself); for the local client they are read from our own socket. - */ -public final class ConnectionStats { - - /** The three traffic categories TeamSpeak accounts separately. */ - public enum Kind {SPEECH, KEEPALIVE, CONTROL} - - /** A quota permission's value for "no limit". */ - public static final long UNLIMITED = -1; - - public int clientId; - public String nickname = ""; - public boolean self; - - /** Empty when the server withholds it. */ - public String ip = ""; - public int port = -1; - - public double pingMs = -1; - public double pingDeviationMs = -1; - public long connectedTimeMs = -1; - public long idleTimeMs = -1; - - public long filetransferBandwidthSent = -1; - public long filetransferBandwidthReceived = -1; - - public final Traffic total = new Traffic(); - private final Map perKind = new EnumMap<>(Kind.class); - - public long monthBytesDownloaded = -1; - public long monthBytesUploaded = -1; - /** Our own transfer quota in MiB, or {@link #UNLIMITED}; only known for ourselves. */ - public long downloadQuotaMb = UNLIMITED; - public long uploadQuotaMb = UNLIMITED; - - /** - * How voice has been coming in here, measured by this client's own playback: from this - * speaker, or for ourselves from everyone. {@code null} when nothing was heard. - */ - public VoiceReceiveStats voiceReceived; - - /** One category's figures, or {@link #total} for a null {@code kind}. */ - public Traffic traffic(Kind kind) { - return kind == null ? total : perKind.computeIfAbsent(kind, k -> new Traffic()); - } - - /** One direction pair of counters. Values default to {@code -1} meaning "unknown". */ - public static final class Traffic { - /** Fractions 0..1: server to client, and client to server. */ - public double lossIn = -1; - public double lossOut = -1; - public long packetsIn = -1; - public long packetsOut = -1; - public long bytesIn = -1; - public long bytesOut = -1; - public long bandwidthInLastSecond = -1; - public long bandwidthOutLastSecond = -1; - public long bandwidthInLastMinute = -1; - public long bandwidthOutLastMinute = -1; - - /** The chance a packet is lost either way, or whichever direction is known. */ - public double lossTotal() { - if (lossIn < 0) return lossOut; - if (lossOut < 0) return lossIn; - return 1 - (1 - lossIn) * (1 - lossOut); - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsCollector.java b/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsCollector.java deleted file mode 100644 index 3123926..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsCollector.java +++ /dev/null @@ -1,288 +0,0 @@ -package com.ts3client.net; - -import com.github.manevolent.ts3j.command.SingleCommand; -import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; -import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent; -import com.github.manevolent.ts3j.protocol.PacketKind; -import com.github.manevolent.ts3j.protocol.ProtocolRole; -import com.github.manevolent.ts3j.protocol.packet.statistics.PacketStatistics; -import com.github.manevolent.ts3j.protocol.socket.client.LocalTeamspeakClientSocket; -import com.github.manevolent.ts3j.util.Pair; -import com.ts3client.audio.VoiceOutput; -import com.ts3client.net.filetransfer.FileTransferManager; - -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.function.Consumer; - -/** - * Builds {@link ConnectionStats} snapshots for the info window from {@code getconnectioninfo}. - * - *

For another client the server answers twice: at once with the figures it last - * heard, then again once the client has sent fresh ones ({@code setconnectioninfo}). - * For ourselves it answers once, with only what it measures itself (address, idle time, - * the loss on the way in); the traffic comes from our own socket's counters. - */ -final class ConnectionStatsCollector { - - private static final long REPORT_WAIT_MS = 1000; - /** {@code clientgetvariables} for the month's transfer figures, which change slowly. */ - private static final long VARIABLES_REFRESH_MS = 10_000; - - private final TeamspeakConnection conn; - - /** Requests awaiting their reports, keyed by client id. */ - private final Map pending = new ConcurrentHashMap<>(); - private final Map variablesAskedAt = new ConcurrentHashMap<>(); - /** The file transfer byte counts at the previous poll: time, sent, received. */ - private long[] lastTransferSample; - - ConnectionStatsCollector(TeamspeakConnection conn) { - this.conn = conn; - } - - /** Drops any requests left over from a connection that just went away. */ - void clear() { - pending.clear(); - variablesAskedAt.clear(); - lastTransferSample = null; - } - - /** - * Fetches a client's statistics and delivers them to {@code callback} exactly once, - * on a background thread. May be called repeatedly to poll. - */ - void request(int clientId, Consumer callback) { - new Thread(() -> callback.accept(collect(clientId)), "ts3j-conninfo").start(); - } - - /** Folds an arriving {@code notifyconnectioninfo} report into its request. */ - void onReport(UnknownTeamspeakEvent e) { - Pending p = pending.get(safeInt(e.get("clid"))); - if (p == null) return; - synchronized (p.stats) { - applyReport(p.stats, e.getMap()); - } - p.reports.countDown(); - } - - private ConnectionStats collect(int clientId) { - ConnectionStats s = new ConnectionStats(); - s.clientId = clientId; - s.self = clientId == conn.getSelfClientId(); - refreshVariables(clientId); - awaitReports(s, s.self ? 1 : 2); - - synchronized (s) { - if (s.self) { - applyLocal(s); - applyTransferRate(s); - } - sumKinds(s); - ClientEntry entry = conn.getModel().getClient(clientId); - if (entry != null) { - s.nickname = entry.nickname; - s.monthBytesDownloaded = entry.monthBytesDownloaded; - s.monthBytesUploaded = entry.monthBytesUploaded; - } - if (s.self) { - ServerModel model = conn.getModel(); - s.downloadQuotaMb = model.selfPermissionValue("i_ft_quota_mb_download_per_client", -1); - s.uploadQuotaMb = model.selfPermissionValue("i_ft_quota_mb_upload_per_client", -1); - } - VoiceOutput playback = conn.getPlayback(); - if (playback != null) { - s.voiceReceived = s.self ? playback.receiveStats() : playback.receiveStats(clientId); - } - } - return s; - } - - private void awaitReports(ConnectionStats s, int expected) { - LocalTeamspeakClientSocket client = conn.client; - if (client == null) return; - Pending p = new Pending(s, expected); - pending.put(s.clientId, p); - try { - client.executeCommand(new SingleCommand("getconnectioninfo", ProtocolRole.CLIENT, - new CommandSingleParameter("clid", Integer.toString(s.clientId)))).complete(); - p.reports.await(REPORT_WAIT_MS, TimeUnit.MILLISECONDS); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } catch (Exception ignored) { - // refused (e.g. no permission to view it); what is known locally still shows - } finally { - pending.remove(s.clientId, p); - } - } - - /** Asks for the month's transfer figures now and then; they land in the model. */ - private void refreshVariables(int clientId) { - long now = System.currentTimeMillis(); - Long last = variablesAskedAt.get(clientId); - if (last != null && now - last < VARIABLES_REFRESH_MS) return; - variablesAskedAt.put(clientId, now); - conn.requestClientInfo(clientId); - } - - /** Our own traffic, straight from the socket. */ - private void applyLocal(ConnectionStats s) { - long connectedAt = conn.connectedAtMs; - if (connectedAt > 0) s.connectedTimeMs = System.currentTimeMillis() - connectedAt; - - LocalTeamspeakClientSocket c = conn.client; - if (c == null) return; - try { - Pair ping = c.getPing(); - s.pingMs = ping.getKey() * 1000.0; - s.pingDeviationMs = ping.getValue() * 1000.0; - } catch (Exception ignored) { - // ping unavailable; leave as unknown - } - for (PacketKind kind : PacketKind.values()) { - PacketStatistics st = c.getStatistics(kind); - ConnectionStats.Traffic t = s.traffic(mapKind(kind)); - t.packetsIn = add(t.packetsIn, st.getReceivedPackets()); - t.packetsOut = add(t.packetsOut, st.getSentPackets()); - t.bytesIn = add(t.bytesIn, st.getReceivedBytes()); - t.bytesOut = add(t.bytesOut, st.getSentBytes()); - t.bandwidthInLastSecond = add(t.bandwidthInLastSecond, st.getReceivedBytesLastSecond()); - t.bandwidthOutLastSecond = add(t.bandwidthOutLastSecond, st.getSentBytesLastSecond()); - t.bandwidthInLastMinute = add(t.bandwidthInLastMinute, st.getReceivedBandwidthLastMinute()); - t.bandwidthOutLastMinute = add(t.bandwidthOutLastMinute, st.getSentBandwidthLastMinute()); - } - } - - /** Our file transfer rate since the previous poll; the server reports it only for others. */ - private synchronized void applyTransferRate(ConnectionStats s) { - FileTransferManager ft = conn.fileTransfers(); - if (ft == null) return; - long[] now = {System.currentTimeMillis(), ft.bytesSent(), ft.bytesReceived()}; - long[] last = lastTransferSample; - lastTransferSample = now; - long elapsed = last == null ? 0 : now[0] - last[0]; - s.filetransferBandwidthSent = elapsed <= 0 ? 0 : (now[1] - last[1]) * 1000 / elapsed; - s.filetransferBandwidthReceived = elapsed <= 0 ? 0 : (now[2] - last[2]) * 1000 / elapsed; - } - - /** Several of ts3j's packet kinds (commands and their acks) make up one TeamSpeak category. */ - private static long add(long current, long value) { - return Math.max(current, 0) + value; - } - - /** Fills the totals from the categories: clients report only those. */ - private static void sumKinds(ConnectionStats s) { - ConnectionStats.Traffic total = s.total; - if (total.packetsIn >= 0) return; - total.packetsIn = total.packetsOut = total.bytesIn = total.bytesOut = 0; - total.bandwidthInLastSecond = total.bandwidthOutLastSecond = 0; - total.bandwidthInLastMinute = total.bandwidthOutLastMinute = 0; - for (ConnectionStats.Kind kind : ConnectionStats.Kind.values()) { - ConnectionStats.Traffic t = s.traffic(kind); - total.packetsIn += Math.max(t.packetsIn, 0); - total.packetsOut += Math.max(t.packetsOut, 0); - total.bytesIn += Math.max(t.bytesIn, 0); - total.bytesOut += Math.max(t.bytesOut, 0); - total.bandwidthInLastSecond += Math.max(t.bandwidthInLastSecond, 0); - total.bandwidthOutLastSecond += Math.max(t.bandwidthOutLastSecond, 0); - total.bandwidthInLastMinute += Math.max(t.bandwidthInLastMinute, 0); - total.bandwidthOutLastMinute += Math.max(t.bandwidthOutLastMinute, 0); - } - } - - /** Parses TeamSpeak's {@code connection_*} fields; ones the report leaves out stay as they are. */ - private static void applyReport(ConnectionStats s, Map m) { - s.pingMs = pickDouble(s.pingMs, m.get("connection_ping")); - s.pingDeviationMs = pickDouble(s.pingDeviationMs, m.get("connection_ping_deviation")); - s.connectedTimeMs = pick(s.connectedTimeMs, m.get("connection_connected_time")); - s.idleTimeMs = pick(s.idleTimeMs, m.get("connection_idle_time")); - String ip = m.get("connection_client_ip"); - if (ip != null && !ip.isEmpty()) s.ip = ip; - s.port = (int) pick(s.port, m.get("connection_client_port")); - s.filetransferBandwidthSent = pick(s.filetransferBandwidthSent, m.get("connection_filetransfer_bandwidth_sent")); - s.filetransferBandwidthReceived = - pick(s.filetransferBandwidthReceived, m.get("connection_filetransfer_bandwidth_received")); - - applyTraffic(s.total, m, "total"); - for (ConnectionStats.Kind kind : ConnectionStats.Kind.values()) { - applyTraffic(s.traffic(kind), m, kind.name().toLowerCase(Locale.ROOT)); - } - } - - private static void applyTraffic(ConnectionStats.Traffic t, Map m, String suffix) { - t.lossIn = pickDouble(t.lossIn, m.get("connection_server2client_packetloss_" + suffix)); - t.lossOut = pickDouble(t.lossOut, m.get("connection_client2server_packetloss_" + suffix)); - t.packetsIn = pick(t.packetsIn, m.get("connection_packets_received_" + suffix)); - t.packetsOut = pick(t.packetsOut, m.get("connection_packets_sent_" + suffix)); - t.bytesIn = pick(t.bytesIn, m.get("connection_bytes_received_" + suffix)); - t.bytesOut = pick(t.bytesOut, m.get("connection_bytes_sent_" + suffix)); - t.bandwidthInLastSecond = pick(t.bandwidthInLastSecond, m.get("connection_bandwidth_received_last_second_" + suffix)); - t.bandwidthOutLastSecond = pick(t.bandwidthOutLastSecond, m.get("connection_bandwidth_sent_last_second_" + suffix)); - t.bandwidthInLastMinute = pick(t.bandwidthInLastMinute, m.get("connection_bandwidth_received_last_minute_" + suffix)); - t.bandwidthOutLastMinute = pick(t.bandwidthOutLastMinute, m.get("connection_bandwidth_sent_last_minute_" + suffix)); - } - - private static ConnectionStats.Kind mapKind(PacketKind kind) { - switch (kind) { - case KEEPALIVE: - return ConnectionStats.Kind.KEEPALIVE; - case SPEECH: - return ConnectionStats.Kind.SPEECH; - default: - return ConnectionStats.Kind.CONTROL; - } - } - - private static long pick(long current, String value) { - long v = parseLong(value); - return v >= 0 ? v : current; - } - - private static double pickDouble(double current, String value) { - double v = parseDouble(value); - return v >= 0 ? v : current; - } - - /** Parses a long, returning -1 for null/blank/non-numeric input. */ - private static long parseLong(String s) { - if (s == null || s.isEmpty()) return -1; - try { - return Long.parseLong(s.trim()); - } catch (NumberFormatException e) { - return -1; - } - } - - /** Parses a double, returning -1 for null/blank/non-numeric input. */ - private static double parseDouble(String s) { - if (s == null || s.isEmpty()) return -1; - try { - return Double.parseDouble(s.trim()); - } catch (NumberFormatException e) { - return -1; - } - } - - /** @return the parsed value, or 0 when it is absent or not a number */ - private static int safeInt(String value) { - try { - return value == null ? 0 : Integer.parseInt(value.trim()); - } catch (NumberFormatException ex) { - return 0; - } - } - - /** A request's snapshot, filled in by its reports as they arrive. */ - private static final class Pending { - final ConnectionStats stats; - final CountDownLatch reports; - - Pending(ConnectionStats stats, int expected) { - this.stats = stats; - this.reports = new CountDownLatch(expected); - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsFormat.java b/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsFormat.java deleted file mode 100644 index 1b91bfd..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionStatsFormat.java +++ /dev/null @@ -1,186 +0,0 @@ -package com.ts3client.net; - -import com.ts3client.audio.VoiceReceiveStats; - -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.List; - -/** - * Renders {@link ConnectionStats} the way the official Connection Info window does: a - * summary, one traffic table per tab with Total / In / Out columns, and a quota tab. - * An unknown value (negative) shows as a dash. - */ -public final class ConnectionStatsFormat { - - public static final String UNKNOWN = "—"; - public static final String HIDDEN = "Hidden"; - public static final String UNLIMITED = "Unlimited"; - public static final String EXCEEDED = "Exceeded"; - - /** The traffic table's column headings, after the row labels. */ - public static final List COLUMNS = List.of("Total", "In", "Out"); - - private ConnectionStatsFormat() { - } - - /** A labelled figure. */ - public record Row(String label, String value) { - } - - /** A traffic table row; {@code total} is empty where the official client leaves it blank. */ - public record TrafficRow(String label, String total, String in, String out) { - } - - /** A traffic tab: the totals for a null {@code kind}, else one category. */ - public record Tab(String title, ConnectionStats.Kind kind) { - } - - public static final List TRAFFIC_TABS = List.of( - new Tab("Total", null), - new Tab("Speech", ConnectionStats.Kind.SPEECH), - new Tab("Keep Alive", ConnectionStats.Kind.KEEPALIVE), - new Tab("Control", ConnectionStats.Kind.CONTROL)); - - public static final String QUOTA_TAB = "Quota"; - public static final String VOICE_TAB = "Voice received"; - - /** Who the client is and how the link to them is doing; {@code s} may be null while loading. */ - public static List summaryRows(ConnectionStats s, String nickname) { - ConnectionStats k = s == null ? new ConnectionStats() : s; - return List.of( - new Row("Client name", nickname), - new Row("Connection time", duration(k.connectedTimeMs)), - new Row("Idle time", duration(k.idleTimeMs)), - new Row("Ping", ping(k.pingMs, k.pingDeviationMs)), - new Row("Client address", s == null ? UNKNOWN : address(s))); - } - - /** {@code ip:port}, what the copy button next to it puts on the clipboard; null when unknown. */ - public static String copyableAddress(ConnectionStats s) { - if (s == null || s.ip.isEmpty()) return null; - return s.port > 0 ? s.ip + ":" + s.port : s.ip; - } - - private static String address(ConnectionStats s) { - String address = copyableAddress(s); - return address == null ? HIDDEN : address; - } - - /** One traffic tab's table; only the totals carry the file transfer row. */ - public static List trafficRows(ConnectionStats s, ConnectionStats.Kind kind) { - ConnectionStats.Traffic t = s == null ? new ConnectionStats.Traffic() : s.traffic(kind); - List rows = new ArrayList<>(List.of( - new TrafficRow("Packet loss", loss(t.lossTotal()), loss(t.lossIn), loss(t.lossOut)), - new TrafficRow("Packets transferred", "", count(t.packetsIn), count(t.packetsOut)), - new TrafficRow("Bytes transferred", "", bytes(t.bytesIn), bytes(t.bytesOut)), - new TrafficRow("Bandwidth last second", "", - rate(t.bandwidthInLastSecond), rate(t.bandwidthOutLastSecond)), - new TrafficRow("Bandwidth last minute", "", - rate(t.bandwidthInLastMinute), rate(t.bandwidthOutLastMinute)))); - if (kind == null) { - long in = s == null ? -1 : s.filetransferBandwidthReceived; - long out = s == null ? -1 : s.filetransferBandwidthSent; - rows.add(new TrafficRow("File transfer bandwidth", "", rate(in), rate(out))); - } - return rows; - } - - /** - * The quota tab: downloads, then uploads. Only our own limits are known, so another - * client's groups hold just the month's figure. - */ - public static List> quotaGroups(ConnectionStats s) { - ConnectionStats k = s == null ? new ConnectionStats() : s; - return List.of( - quota(k, "download", "Downloaded this month:", k.monthBytesDownloaded, k.downloadQuotaMb), - quota(k, "upload", "Uploaded this month:", k.monthBytesUploaded, k.uploadQuotaMb)); - } - - private static List quota(ConnectionStats s, String direction, String label, long used, long quotaMb) { - Row month = new Row(label, bytes(used)); - if (!s.self) return List.of(month); - String available = quotaMb < 0 ? UNLIMITED : bytes(quotaMb * 1024 * 1024); - String remaining; - if (quotaMb < 0) remaining = UNLIMITED; - else if (used < 0) remaining = UNKNOWN; - else if (used > quotaMb * 1024 * 1024) remaining = EXCEEDED; - else remaining = bytes(quotaMb * 1024 * 1024 - used); - return List.of(month, - new Row("Available " + direction + " quota:", available), - new Row("Remaining " + direction + " this month:", remaining)); - } - - /** The voice our playback received; every value is a dash when nothing was heard. */ - public static List voiceRows(VoiceReceiveStats v) { - VoiceReceiveStats s = v == null ? VoiceReceiveStats.NONE : v; - boolean known = v != null; - return List.of( - new Row("Received", known ? count(s.received()) : UNKNOWN), - new Row("Played", known ? countOf(s.played(), s.due()) : UNKNOWN), - new Row("Missed", known ? countOf(s.missed(), s.due()) : UNKNOWN), - new Row("Recovered (FEC)", known ? countOf(s.recovered(), s.missed()) : UNKNOWN), - new Row("Out of order", known ? countOf(s.outOfOrder(), s.received()) : UNKNOWN), - new Row("Dropped (too late)", known ? countOf(s.late(), s.received()) : UNKNOWN), - new Row("Discarded (copies)", known ? countOf(s.duplicates(), s.received()) : UNKNOWN)); - } - - // ---- figures ---- - - /** {@code 153 ms ± 217.0}. */ - public static String ping(double ms, double deviationMs) { - if (ms < 0) return UNKNOWN; - String base = Math.round(ms) + " ms"; - if (deviationMs >= 0) base += " ± " + new DecimalFormat("0.0").format(deviationMs); - return base; - } - - /** A fraction 0..1 as a percentage. */ - public static String loss(double fraction) { - if (fraction < 0) return UNKNOWN; - return new DecimalFormat("0.00").format(fraction * 100.0) + " %"; - } - - /** {@code 133}, {@code 2.12 k}, {@code 1.05 M}. */ - public static String count(long n) { - if (n < 0) return UNKNOWN; - if (n < 1000) return Long.toString(n); - DecimalFormat f = new DecimalFormat("0.00"); - if (n < 1_000_000) return f.format(n / 1e3) + " k"; - return f.format(n / 1e6) + " M"; - } - - /** A count with its share of {@code of}, e.g. {@code 12 (0.4 %)}. */ - public static String countOf(long n, long of) { - if (n < 0) return UNKNOWN; - if (of <= 0) return count(n); - return count(n) + " (" + new DecimalFormat("0.0").format(100.0 * n / of) + " %)"; - } - - public static String bytes(long bytes) { - if (bytes < 0) return UNKNOWN; - if (bytes < 1024) return bytes + " Bytes"; - DecimalFormat f = new DecimalFormat("0.00"); - double kib = bytes / 1024.0; - if (kib < 1024) return f.format(kib) + " KiB"; - double mib = kib / 1024.0; - if (mib < 1024) return f.format(mib) + " MiB"; - return f.format(mib / 1024.0) + " GiB"; - } - - public static String rate(long bytesPerSecond) { - return bytesPerSecond < 0 ? UNKNOWN : bytes(bytesPerSecond) + "/s"; - } - - /** {@code 04:34}, or {@code 15:35:17} from an hour on. */ - public static String duration(long ms) { - if (ms < 0) return UNKNOWN; - long totalSeconds = ms / 1000; - long hours = totalSeconds / 3600; - long minutes = (totalSeconds % 3600) / 60; - long seconds = totalSeconds % 60; - return hours > 0 - ? String.format("%02d:%02d:%02d", hours, minutes, seconds) - : String.format("%02d:%02d", minutes, seconds); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/DatabaseClient.java b/ts3-client/core/src/main/java/com/ts3client/net/DatabaseClient.java deleted file mode 100644 index 2d74cb9..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/DatabaseClient.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.ts3client.net; - -/** - * A client the server's database knows, online or not: what an offline message is addressed to. - * - * @param nickname the nickname they last used on this server - */ -public record DatabaseClient(String uniqueId, int databaseId, String nickname) { -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/Details.java b/ts3-client/core/src/main/java/com/ts3client/net/Details.java deleted file mode 100644 index 818d3d5..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/Details.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.ts3client.net; - -import com.ts3client.contacts.Contact; - -import java.time.Instant; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.List; - -/** - * What the info box tells about the server, a channel or a client, as the TeamSpeak 3 client's - * info frame does: labelled facts, then a description in BBCode. The same on every frontend, - * which only lays it out. - * - * @param description BBCode; empty when there is none - * @param pending the description is still being asked for - */ -public record Details(String title, List fields, String description, boolean pending) { - - /** - * One labelled fact. - * - * @param groups the groups {@code value} names, in order, for frontends that show their icons; - * empty when it names none - * @param minor for frontends short of room to show only on asking - */ - public record Field(String label, String value, List groups, boolean minor) { - Field(String label, String value) { - this(label, value, List.of(), false); - } - - Field(String label, String value, List groups) { - this(label, value, groups, false); - } - - static Field minor(String label, String value) { - return new Field(label, value, List.of(), true); - } - } - - private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - - public static Details server(ServerModel model, String address) { - List fields = new ArrayList<>(); - fields.add(new Field("Address", address)); - String version = model.serverProperty("virtualserver_version"); - String platform = model.serverProperty("virtualserver_platform"); - if (!version.isEmpty()) fields.add(new Field("Version", version + (platform.isEmpty() ? "" : " on " + platform))); - String max = model.serverProperty("virtualserver_maxclients"); - fields.add(new Field("Clients", model.clientCount() + (max.isEmpty() ? "" : " / " + max))); - fields.add(new Field("Channels", Integer.toString(model.channelCount()))); - long created = parseLong(model.serverProperty("virtualserver_created")); - if (created > 0) { - fields.add(new Field("Created", DATE.format(Instant.ofEpochSecond(created).atZone(ZoneId.systemDefault())))); - } - String welcome = model.serverProperty("virtualserver_welcomemessage").trim(); - String host = model.serverProperty("virtualserver_hostmessage").trim(); - String description = welcome.isEmpty() || host.isEmpty() ? welcome + host : welcome + "\n\n" + host; - return new Details(model.getServerName(), fields, description, false); - } - - public static Details channel(ChannelNode ch) { - List fields = new ArrayList<>(); - if (ch.maxClients >= 0) fields.add(new Field("Max clients", Integer.toString(ch.maxClients))); - if (ch.hasPassword) fields.add(new Field("Password", "protected")); - if (!ch.topic.isEmpty()) fields.add(new Field("Topic", ch.topic)); - String description = ch.description == null ? "" : ch.description; - return new Details(ch.name, fields, description, description.isEmpty() && !ch.descriptionLoaded); - } - - /** @param contact the client's contact entry, or null */ - public static Details client(ClientEntry cl, ServerModel model, Contact contact) { - List fields = new ArrayList<>(); - if (contact != null) { - String type = contact.type.label(); - if (!contact.phoneticNickname.isEmpty()) type += " (" + contact.phoneticNickname + ")"; - fields.add(Field.minor("Contact", type)); - } - - List serverGroups = model.serverGroupsOf(cl.serverGroupIds); - if (serverGroups.isEmpty()) { - List names = model.serverGroupNames(cl.serverGroupIds); - fields.add(new Field("Server groups", names.isEmpty() ? "—" : String.join(", ", names))); - } else { - // A nameless group is there for its icon only; without one, there is nothing to show of it. - List shown = new ArrayList<>(); - List names = new ArrayList<>(); - for (Group g : serverGroups) { - if (g.name.isBlank() && g.iconId == 0) continue; - shown.add(g); - if (!g.name.isBlank()) names.add(g.name.trim()); - } - fields.add(new Field("Server groups", names.isEmpty() ? "—" : String.join(", ", names), shown)); - } - Group channelGroup = model.channelGroup(cl.channelGroupId); - fields.add(channelGroup != null - ? new Field("Channel group", channelGroup.name, List.of(channelGroup)) - : new Field("Channel group", "#" + cl.channelGroupId)); - - if (cl.talkPower != 0) fields.add(Field.minor("Talk power", Integer.toString(cl.talkPower))); - if (!cl.version.isEmpty()) { - fields.add(Field.minor("Version", cl.version + (cl.platform.isEmpty() ? "" : " on " + cl.platform))); - } else if (!cl.platform.isEmpty()) { - fields.add(Field.minor("Platform", cl.platform)); - } - if (cl.away) fields.add(Field.minor("Status", "Away")); - if (!cl.inputHardware) fields.add(Field.minor("Microphone", "disabled")); - else if (cl.inputMuted) fields.add(Field.minor("Microphone", "muted")); - if (!cl.outputHardware) fields.add(Field.minor("Speakers", "disabled")); - else if (cl.outputMuted) fields.add(Field.minor("Speakers", "muted")); - if (!cl.uniqueId.isEmpty()) fields.add(Field.minor("Unique ID", cl.uniqueId)); - - String name = contact == null ? cl.nickname : contact.displayName(cl.nickname); - return new Details(name, fields, cl.description == null ? "" : cl.description, false); - } - - private static long parseLong(String s) { - try { - return s.isEmpty() ? 0 : Long.parseLong(s.trim()); - } catch (NumberFormatException e) { - return 0; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/Group.java b/ts3-client/core/src/main/java/com/ts3client/net/Group.java deleted file mode 100644 index a81b397..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/Group.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.ts3client.net; - -/** A server or channel group as announced by the server. */ -public final class Group { - - public final int id; - public final String name; - /** Id of the group's icon (0 = none); resolved through {@link IconRepository}. */ - public final long iconId; - /** Display order among groups; lower comes first. */ - public final int sortId; - /** TS3 group type: 0 = template, 1 = regular, 2 = query (server groups only). */ - public final int type; - /** Power needed to add a member to this group. */ - public final int neededMemberAddPower; - /** Power needed to remove a member from this group. */ - public final int neededMemberRemovePower; - - public Group(int id, String name, long iconId, int sortId, int type, - int neededMemberAddPower, int neededMemberRemovePower) { - this.id = id; - this.name = name; - this.iconId = iconId; - this.sortId = sortId; - this.type = type; - this.neededMemberAddPower = neededMemberAddPower; - this.neededMemberRemovePower = neededMemberRemovePower; - } - - /** Regular, user-assignable groups exclude templates and query-only groups. */ - public boolean isRegular() { - return type == 1; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/GroupChoice.java b/ts3-client/core/src/main/java/com/ts3client/net/GroupChoice.java deleted file mode 100644 index 2364ec6..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/GroupChoice.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.ts3client.net; - -/** A group as offered for one client: whether they are in it, and whether we may change that. */ -public record GroupChoice(Group group, boolean assigned, boolean allowed) { -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/HostButton.java b/ts3-client/core/src/main/java/com/ts3client/net/HostButton.java deleted file mode 100644 index 548676b..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/HostButton.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.ts3client.net; - -/** - * The button a server puts in the toolbar's top right corner, linking to its host's site. - * - * @param url what a click opens; empty when the button only shows - * @param gfxUrl the picture to show; empty for TeamSpeak's own host button icon - * @param tooltip shown on hover; may be empty - */ -public record HostButton(String url, String gfxUrl, String tooltip) { - - /** @return the button, or {@code null} when the server sets neither a link nor a picture */ - public static HostButton of(String url, String gfxUrl, String tooltip) { - url = url == null ? "" : url.trim(); - gfxUrl = gfxUrl == null ? "" : gfxUrl.trim(); - if (url.isEmpty() && gfxUrl.isEmpty()) return null; - return new HostButton(url, gfxUrl, tooltip == null ? "" : tooltip.trim()); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/IconRepository.java b/ts3-client/core/src/main/java/com/ts3client/net/IconRepository.java deleted file mode 100644 index 6dc5a67..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/IconRepository.java +++ /dev/null @@ -1,200 +0,0 @@ -package com.ts3client.net; - -import com.ts3client.config.AppDirs; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * Supplies the raw PNG bytes of a TeamSpeak icon id, as used by server and channel - * groups. - * - *

Ids up to {@link #MAX_BUNDLED_ID} identify the icons shipped with the client - * (TeamSpeak's default group icons); anything above that is a server-specific icon - * stored in the virtual server's file repository as {@code /icon_} in channel 0, - * which is downloaded once and then cached in memory and on disk. - * - *

Lookups never block: {@link #get(long)} returns {@code null} while an icon is - * still being fetched and the listener is notified once it becomes available. - */ -public final class IconRepository { - - /** Icons at or below this id are bundled defaults rather than server uploads. */ - public static final int MAX_BUNDLED_ID = 1000; - - /** - * The default group icons shipped with the client, in the order TeamSpeak's own icon - * packs list them. These are what the icon chooser offers as "local" icons. - */ - public static final List BUNDLED_IDS = List.of(100L, 200L, 300L, 500L, 600L); - - /** Downloads {@code /icon_} from the connected server's file repository. */ - public interface Fetcher { - byte[] fetchIcon(long iconId) throws Exception; - } - - private final Fetcher fetcher; - private final Runnable onIconLoaded; - private final Map icons = new ConcurrentHashMap<>(); - private final Set pending = ConcurrentHashMap.newKeySet(); - private final Set failed = ConcurrentHashMap.newKeySet(); - private final ExecutorService downloads = Executors.newSingleThreadExecutor(r -> { - Thread t = new Thread(r, "ts3j-icons"); - t.setDaemon(true); - return t; - }); - - /** - * @param onIconLoaded run (off the UI thread) whenever a previously missing icon - * has arrived, so the view can repaint - */ - public IconRepository(Fetcher fetcher, Runnable onIconLoaded) { - this.fetcher = fetcher; - this.onIconLoaded = onIconLoaded; - } - - /** - * @return the icon's PNG bytes, or {@code null} if it is unknown, still loading or - * unavailable. A server icon that is not cached yet starts downloading. - */ - public byte[] get(long iconId) { - long id = normalize(iconId); - if (id == 0) return null; - - byte[] cached = icons.get(id); - if (cached != null) return cached; - - byte[] bundled = readBundled(id); - if (bundled != null) { - icons.put(id, bundled); - return bundled; - } - if (id <= MAX_BUNDLED_ID) return null; // a default icon we do not ship - - byte[] fromDisk = readDiskCache(id); - if (fromDisk != null) { - icons.put(id, fromDisk); - return fromDisk; - } - if (!failed.contains(id) && pending.add(id)) { - downloads.execute(() -> download(id)); - } - return null; - } - - /** - * The icon as a file on disk, materialising bundled icons into the cache directory - * on first use, for callers that can only reference images by URL (HTML views). - * - * @return the file, or {@code null} while the icon is unavailable - */ - public File file(long iconId) { - long id = normalize(iconId); - byte[] data = get(id); - if (data == null) return null; - File file = new File(cacheDir(), "icon_" + id + ".png"); - if (!file.isFile()) writeDiskCache(id, data); - return file.isFile() ? file : null; - } - - /** - * An icon that needs no server: one shipped with the client or downloaded earlier, - * e.g. for a bookmark while it is not connected. - * - * @return the icon's PNG bytes, or {@code null} if it has never been fetched - */ - public static byte[] cached(long iconId) { - long id = normalize(iconId); - if (id == 0) return null; - byte[] bundled = readBundled(id); - return bundled != null || id <= MAX_BUNDLED_ID ? bundled : readDiskCache(id); - } - - /** An icon id as a property carries it, 0 for none or garbage. */ - public static long parseId(String value) { - if (value == null || value.isBlank()) return 0; - try { - return normalize(Long.parseLong(value.trim())); - } catch (NumberFormatException e) { - return 0; - } - } - - /** Forgets download failures so icons can be retried on the next reconnect. */ - public void retryFailed() { - failed.clear(); - } - - public void shutdown() { - downloads.shutdownNow(); - } - - private void download(long id) { - try { - byte[] data = fetcher.fetchIcon(id); - if (data == null || data.length == 0) { - failed.add(id); - return; - } - icons.put(id, data); - writeDiskCache(id, data); - if (onIconLoaded != null) onIconLoaded.run(); - } catch (IllegalStateException e) { - // Not connected (yet): a channel icon can be asked for while the tree is - // first painted, before file transfers are up. Leave it retryable. - } catch (Exception e) { - // Missing or permission-denied icons are common; don't ask again. - failed.add(id); - } finally { - pending.remove(id); - } - } - - /** - * TeamSpeak transmits icon ids as unsigned 32-bit CRCs, which arrive here through - * signed parsing; fold them back into their unsigned value. - */ - private static long normalize(long iconId) { - return iconId < 0 ? iconId & 0xFFFFFFFFL : iconId; - } - - private static byte[] readBundled(long id) { - try (InputStream in = IconRepository.class.getResourceAsStream("/icons/group_" + id + ".png")) { - return in == null ? null : in.readAllBytes(); - } catch (IOException e) { - return null; - } - } - - private static File cacheDir() { - return new File(AppDirs.profile(), "icons"); - } - - private static byte[] readDiskCache(long id) { - File file = new File(cacheDir(), "icon_" + id + ".png"); - if (!file.isFile()) return null; - try { - return Files.readAllBytes(file.toPath()); - } catch (IOException e) { - return null; - } - } - - private void writeDiskCache(long id, byte[] data) { - try { - //noinspection ResultOfMethodCallIgnored - cacheDir().mkdirs(); - Files.write(new File(cacheDir(), "icon_" + id + ".png").toPath(), data); - } catch (IOException ignored) { - // the in-memory cache still serves this session - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/OfflineMessage.java b/ts3-client/core/src/main/java/com/ts3client/net/OfflineMessage.java deleted file mode 100644 index af1b3e6..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/OfflineMessage.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.ts3client.net; - -import java.util.Map; - -/** - * A message in our offline message inbox on the server, without its body: {@code messagelist} - * leaves that out, and reading it costs a {@code messageget} each. - * - * @param senderName the sender's last known nickname, or their unique id when the server has forgotten them - */ -public record OfflineMessage(int id, String senderUid, String senderName, String subject, - long timestampEpochSeconds, boolean read) { - - /** Reads a message off a {@code notifymessagelist} event's fields. */ - static OfflineMessage from(Map fields, String senderName) { - return new OfflineMessage((int) parseLong(fields.get("msgid")), - orEmpty(fields.get("cluid")), - senderName, - orEmpty(fields.get("subject")), - parseLong(fields.get("timestamp")), - "1".equals(fields.get("flag_read"))); - } - - public OfflineMessage withRead(boolean read) { - return new OfflineMessage(id, senderUid, senderName, subject, timestampEpochSeconds, read); - } - - static String orEmpty(String s) { - return s == null || s.equals("null") ? "" : s; - } - - private static long parseLong(String s) { - try { - return s == null ? 0 : Long.parseLong(s.trim()); - } catch (NumberFormatException e) { - return 0; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/OfflineMessageAdmin.java b/ts3-client/core/src/main/java/com/ts3client/net/OfflineMessageAdmin.java deleted file mode 100644 index 37b9d72..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/OfflineMessageAdmin.java +++ /dev/null @@ -1,163 +0,0 @@ -package com.ts3client.net; - -import com.github.manevolent.ts3j.command.CommandException; -import com.github.manevolent.ts3j.command.SingleCommand; -import com.github.manevolent.ts3j.command.parameter.CommandParameter; -import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; -import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent; -import com.github.manevolent.ts3j.protocol.ProtocolRole; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Our offline message inbox on the server, sending offline messages, and finding the - * database clients to send them to. - * - *

Split out of {@link TeamspeakConnection} like {@link ComplaintAdmin}. Every reply comes as - * notifications ahead of the command's completion, collected into {@link #replies}; calls are - * serialised so two requests never share it. Every call blocks and must run off the UI thread. - */ -final class OfflineMessageAdmin { - - /** What a listing answers when it has nothing to list. */ - private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501; - /** What a unique id or database id lookup answers when the server has no such client. */ - private static final int ERROR_INVALID_CLIENT_ID = 0x0200; - /** The most matches a nickname search names; each costs a lookup, and lookups flood quickly. */ - private static final int MAX_SEARCH_RESULTS = 10; - - private final TeamspeakConnection conn; - /** Senders' nicknames by unique id; they cost a lookup each, so a connection asks once. */ - private final Map names = new ConcurrentHashMap<>(); - - /** The notification the request in flight is answered by, and what has arrived of it. */ - private volatile String awaited; - private volatile List> replies; - - OfflineMessageAdmin(TeamspeakConnection conn) { - this.conn = conn; - } - - /** Forgets what the last server told us; a reconnect may be to another server. */ - void reset() { - names.clear(); - } - - void onReply(UnknownTeamspeakEvent e) { - List> collected = replies; - if (collected != null && e.getCommand().equals(awaited)) collected.add(e.getMap()); - } - - /** Runs a command and returns the {@code notification} rows it was answered with; none when the result is empty. */ - private synchronized List> query(String notification, String command, - CommandParameter... params) throws Exception { - List> collected = Collections.synchronizedList(new ArrayList<>()); - awaited = notification; - replies = collected; - try { - conn.socket().executeCommand(new SingleCommand(command, ProtocolRole.CLIENT, params)).complete(); - conn.awaitEventsProcessed(); - } catch (CommandException e) { - if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e; - } finally { - replies = null; - awaited = null; - } - return new ArrayList<>(collected); - } - - private synchronized void execute(String command, CommandParameter... params) throws Exception { - conn.socket().executeCommand(new SingleCommand(command, ProtocolRole.CLIENT, params)).complete(); - } - - private static CommandSingleParameter param(String key, Object value) { - return new CommandSingleParameter(key, String.valueOf(value)); - } - - // ---- inbox ---- - - List list() throws Exception { - List messages = new ArrayList<>(); - for (Map row : query("notifymessagelist", "messagelist")) { - String sender = OfflineMessage.orEmpty(row.get("cluid")); - messages.add(OfflineMessage.from(row, senderName(sender))); - } - return messages; - } - - private String senderName(String uniqueId) throws Exception { - if (uniqueId.isEmpty()) return ""; - String known = names.get(uniqueId); - if (known != null) return known; - DatabaseClient client = lookupUid(uniqueId); - String name = client != null ? client.nickname() : uniqueId; - names.put(uniqueId, name); - return name; - } - - /** Reads a message's body; this does not mark it read. */ - String body(int messageId) throws Exception { - List> rows = query("notifymessage", "messageget", param("msgid", messageId)); - if (rows.isEmpty()) throw new IllegalStateException("The message is gone."); - return OfflineMessage.orEmpty(rows.get(0).get("message")); - } - - void setRead(int messageId, boolean read) throws Exception { - execute("messageupdateflag", param("msgid", messageId), param("flag", read ? 1 : 0)); - } - - void delete(int messageId) throws Exception { - execute("messagedel", param("msgid", messageId)); - } - - void send(String recipientUid, String subject, String message) throws Exception { - execute("messageadd", param("cluid", recipientUid), param("subject", subject), param("message", message)); - } - - // ---- recipients ---- - - /** @return the client with this unique id, or {@code null} when the server has never seen them */ - DatabaseClient lookupUid(String uniqueId) throws Exception { - try { - List> rows = query("notifyclientnamefromuid", "clientgetnamefromuid", - param("cluid", uniqueId)); - return rows.isEmpty() ? null : fromNameReply(rows.get(0)); - } catch (CommandException e) { - if (e.getErrorId() == ERROR_INVALID_CLIENT_ID) return null; - throw e; - } - } - - /** - * Clients whose last nickname contains {@code nickname}. Needs - * {@code b_virtualserver_client_dbsearch}, which the server never reports to us up front. - */ - List search(String nickname) throws Exception { - List> found = query("notifyclientdbfind", "clientdbfind", - param("pattern", "%" + nickname + "%")); - List clients = new ArrayList<>(); - for (Map row : found) { - if (clients.size() == MAX_SEARCH_RESULTS) break; - List> named = query("notifyclientnamefromdbid", "clientgetnamefromdbid", - param("cldbid", OfflineMessage.orEmpty(row.get("cldbid")))); - if (!named.isEmpty()) clients.add(fromNameReply(named.get(0))); - } - for (DatabaseClient c : clients) names.put(c.uniqueId(), c.nickname()); - return clients; - } - - private static DatabaseClient fromNameReply(Map row) { - int dbId; - try { - dbId = Integer.parseInt(OfflineMessage.orEmpty(row.get("cldbid")).trim()); - } catch (NumberFormatException e) { - dbId = 0; - } - return new DatabaseClient(OfflineMessage.orEmpty(row.get("cluid")), dbId, - OfflineMessage.orEmpty(row.get("name"))); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/PictureDownloads.java b/ts3-client/core/src/main/java/com/ts3client/net/PictureDownloads.java deleted file mode 100644 index 73684e0..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/PictureDownloads.java +++ /dev/null @@ -1,202 +0,0 @@ -package com.ts3client.net; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.StandardCopyOption; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * The pictures descriptions show, fetched from the web on first sight and kept on disk - * for a month after they were last shown. - * - *

Lookups never block: {@link #get} returns {@code null} while a picture is on its - * way, and the listeners hear when one has come or could not be had. - */ -public final class PictureDownloads { - - /** Fetches the pictures whose addresses use a scheme of its own, rather than from the web. */ - public interface Source { - /** @return the picture, or {@code null} when it cannot be had */ - byte[] fetch(String url, long maxBytes) throws IOException; - } - - private static final long MAX_BYTES = 8L << 20; - private static final int TIMEOUT_MS = 10_000; - private static final long KEEP_MS = 30L * 24 * 60 * 60 * 1000; - private static final String USER_AGENT = "ts3client"; - private static final int MAX_REDIRECTS = 5; - - private final File dir; - private final boolean plainHttp; - private final List listeners = new CopyOnWriteArrayList<>(); - private final Set pending = ConcurrentHashMap.newKeySet(); - private final Set failed = ConcurrentHashMap.newKeySet(); - private final Map sources = new ConcurrentHashMap<>(); - private final ExecutorService downloads = Executors.newFixedThreadPool(2, r -> { - Thread t = new Thread(r, "picture-download"); - t.setDaemon(true); - return t; - }); - - /** - * @param plainHttp whether plain http may be used; where it may not (Android), an - * http address is fetched over https, which most hosts also serve - */ - public PictureDownloads(File dir, boolean plainHttp) { - this.dir = dir; - this.plainHttp = plainHttp; - downloads.execute(this::prune); - } - - /** @param listener run off the UI thread whenever a picture has come or failed */ - public void addListener(Runnable listener) { - listeners.add(listener); - } - - /** Fetches addresses starting with {@code scheme} (e.g. {@code "tsattach:"}) from {@code source}. */ - public void addSource(String scheme, Source source) { - sources.put(scheme, source); - } - - /** Asks again for the pictures that could not be had, e.g. once signed in to where they come from. */ - public void retryFailed() { - failed.clear(); - for (Runnable listener : listeners) listener.run(); - } - - public void removeListener(Runnable listener) { - listeners.remove(listener); - } - - /** - * @return the picture's file, or {@code null} while it downloads or when it cannot be - * had (see {@link #failed}). A picture not on disk yet starts downloading. - */ - public File get(String url) { - File file = new File(dir, name(url)); - if (file.isFile()) { - //noinspection ResultOfMethodCallIgnored - file.setLastModified(System.currentTimeMillis()); - return file; - } - if (!failed.contains(url) && pending.add(url)) downloads.execute(() -> download(url, file)); - return null; - } - - /** Whether the picture could not be had this session; it is not asked for again until then. */ - public boolean failed(String url) { - return failed.contains(url); - } - - private void download(String url, File file) { - try { - Source source = source(url); - byte[] data = source != null ? source.fetch(url, MAX_BYTES) : fetch(allowed(url)); - if (data == null) { - failed.add(url); - } else { - //noinspection ResultOfMethodCallIgnored - dir.mkdirs(); - File part = new File(dir, file.getName() + ".part"); - Files.write(part.toPath(), data); - Files.move(part.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING); - } - } catch (IOException | RuntimeException e) { - failed.add(url); - } finally { - pending.remove(url); - } - for (Runnable listener : listeners) listener.run(); - } - - private Source source(String url) { - for (Map.Entry e : sources.entrySet()) { - if (url.startsWith(e.getKey())) return e.getValue(); - } - return null; - } - - /** The address as it may be fetched here: over https where plain http is not allowed. */ - private String allowed(String url) { - boolean http = url.regionMatches(true, 0, "http://", 0, 7); - return plainHttp || !http ? url : "https://" + url.substring(7); - } - - /** - * Follows redirects itself: Java does not follow one that changes protocol, which is how - * many hosts send plain http on to https. - */ - private byte[] fetch(String url) throws IOException { - for (int hop = 0; hop <= MAX_REDIRECTS; hop++) { - HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); - try { - connection.setInstanceFollowRedirects(false); - connection.setConnectTimeout(TIMEOUT_MS); - connection.setReadTimeout(TIMEOUT_MS); - // Some hosts turn away Java's own agent (Wikimedia does). - connection.setRequestProperty("User-Agent", USER_AGENT); - int code = connection.getResponseCode(); - String location = connection.getHeaderField("Location"); - if (code / 100 == 3 && location != null) { - String next = new URL(new URL(url), location).toString(); - if (!next.regionMatches(true, 0, "http", 0, 4)) return null; - url = allowed(next); - continue; - } - return code == HttpURLConnection.HTTP_OK ? read(connection) : null; - } finally { - connection.disconnect(); - } - } - return null; - } - - private static byte[] read(HttpURLConnection connection) throws IOException { - if (connection.getContentLengthLong() > MAX_BYTES) return null; - try (InputStream in = connection.getInputStream()) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - byte[] buffer = new byte[16 * 1024]; - for (int n; (n = in.read(buffer)) >= 0; ) { - out.write(buffer, 0, n); - if (out.size() > MAX_BYTES) return null; - } - return out.toByteArray(); - } - } - - /** Forgets the pictures not shown for a month. */ - private void prune() { - File[] files = dir.listFiles(); - if (files == null) return; - long cutoff = System.currentTimeMillis() - KEEP_MS; - for (File f : files) { - //noinspection ResultOfMethodCallIgnored - if (f.lastModified() < cutoff) f.delete(); - } - } - - private static String name(String url) { - try { - byte[] hash = MessageDigest.getInstance("SHA-1").digest(url.getBytes(StandardCharsets.UTF_8)); - StringBuilder sb = new StringBuilder(); - for (byte b : hash) sb.append(String.format("%02x", b)); - return sb.toString(); - } catch (NoSuchAlgorithmException e) { - throw new IllegalStateException(e); - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/PrivilegeKey.java b/ts3-client/core/src/main/java/com/ts3client/net/PrivilegeKey.java deleted file mode 100644 index 00d73f0..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/PrivilegeKey.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.ts3client.net; - -import java.util.Map; - -/** - * A privilege key (token): a one-time code that puts whoever redeems it into a server - * group, or into a channel group in one channel. - * - * @param groupId the server or channel group it grants - * @param channelId the channel a channel group key applies in; 0 for a server group key - */ -public record PrivilegeKey(String token, boolean channelGroup, int groupId, int channelId, - long createdEpochSeconds, String description) { - - /** Reads a key off a {@code notifytokenlist} event's fields. */ - static PrivilegeKey from(Map fields) { - return new PrivilegeKey(orEmpty(fields.get("token")), - parseLong(fields.get("token_type")) == 1, - (int) parseLong(fields.get("token_id1")), - (int) parseLong(fields.get("token_id2")), - parseLong(fields.get("token_created")), - orEmpty(fields.get("token_description"))); - } - - private static String orEmpty(String s) { - return s == null || s.equals("null") ? "" : s; - } - - private static long parseLong(String s) { - try { - return s == null ? 0 : Long.parseLong(s.trim()); - } catch (NumberFormatException e) { - return 0; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/PrivilegeKeyAdmin.java b/ts3-client/core/src/main/java/com/ts3client/net/PrivilegeKeyAdmin.java deleted file mode 100644 index ba52c20..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/PrivilegeKeyAdmin.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.ts3client.net; - -import com.github.manevolent.ts3j.command.CommandException; -import com.github.manevolent.ts3j.command.SingleCommand; -import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; -import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent; -import com.github.manevolent.ts3j.protocol.ProtocolRole; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * The server's privilege keys: listing, creating, deleting and redeeming them. - * - *

Split out of {@link TeamspeakConnection} like {@link BanAdmin}, and answered the same - * way: {@code tokenlist} and {@code tokenadd} reply with notifications ahead of the - * command's own completion. Every call here blocks and must run off the UI thread; the - * connection's public wrappers do that. - */ -final class PrivilegeKeyAdmin { - - /** What {@code tokenlist} answers when there are no keys at all. */ - private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501; - - private final TeamspeakConnection conn; - - /** The {@code tokenlist} reply in progress; one request may be in flight at a time. */ - private volatile List listing; - /** The key the {@code tokenadd} in flight was answered with. */ - private volatile String created; - - PrivilegeKeyAdmin(TeamspeakConnection conn) { - this.conn = conn; - } - - List list() throws Exception { - List keys = Collections.synchronizedList(new ArrayList<>()); - listing = keys; - try { - conn.socket().executeCommand(new SingleCommand("tokenlist", ProtocolRole.CLIENT)).complete(); - conn.awaitEventsProcessed(); - } catch (CommandException e) { - if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e; - } finally { - listing = null; - } - return new ArrayList<>(keys); - } - - void onListEntry(UnknownTeamspeakEvent e) { - List keys = listing; - if (keys != null) keys.add(PrivilegeKey.from(e.getMap())); - } - - /** - * Creates a key. - * - * @param channelId the channel a channel group key applies in; ignored for a server group - * @return the new key - */ - synchronized String add(boolean channelGroup, int groupId, int channelId, String description) throws Exception { - SingleCommand cmd = new SingleCommand("tokenadd", ProtocolRole.CLIENT); - cmd.add(new CommandSingleParameter("tokentype", channelGroup ? "1" : "0")); - cmd.add(new CommandSingleParameter("tokenid1", Integer.toString(groupId))); - cmd.add(new CommandSingleParameter("tokenid2", channelGroup ? Integer.toString(channelId) : "0")); - cmd.add(new CommandSingleParameter("tokendescription", description)); - created = null; - conn.socket().executeCommand(cmd).complete(); - conn.awaitEventsProcessed(); - String token = created; - if (token == null || token.isEmpty()) throw new IllegalStateException("The server did not return the key"); - return token; - } - - void onAdded(UnknownTeamspeakEvent e) { - created = e.get("token"); - } - - void delete(String token) throws Exception { - conn.socket().executeCommand(new SingleCommand("tokendelete", ProtocolRole.CLIENT, - new CommandSingleParameter("token", token))).complete(); - } - - /** Redeems a key; the server announces the resulting group change itself. */ - void use(String token) throws Exception { - conn.socket().executeCommand(new SingleCommand("tokenuse", ProtocolRole.CLIENT, - new CommandSingleParameter("token", token))).complete(); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ServerLogAdmin.java b/ts3-client/core/src/main/java/com/ts3client/net/ServerLogAdmin.java deleted file mode 100644 index 9930afd..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/ServerLogAdmin.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.ts3client.net; - -import com.github.manevolent.ts3j.command.CommandException; -import com.github.manevolent.ts3j.command.SingleCommand; -import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; -import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent; -import com.github.manevolent.ts3j.protocol.ProtocolRole; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * Reads the virtual server's log with {@code logview}, which answers with one - * {@code notifyserverlog} per line, newest first, each also carrying {@code last_pos}: where - * the lines it returned begin in the log file, and so where the older ones end. - * - *

Split out of {@link TeamspeakConnection} like {@link BanAdmin}. Every call here blocks - * and must run off the UI thread; the connection's public wrapper does that. - */ -final class ServerLogAdmin { - - /** The most lines {@code logview} returns at once. */ - static final int PAGE_LINES = 100; - - /** What {@code logview} may answer for an empty log. */ - private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501; - - private final TeamspeakConnection conn; - - /** The {@code logview} reply in progress; one request may be in flight at a time. */ - private volatile Reply reply; - - private static final class Reply { - final List entries = Collections.synchronizedList(new ArrayList<>()); - volatile long lastPos; - } - - ServerLogAdmin(TeamspeakConnection conn) { - this.conn = conn; - } - - /** - * Reads the newest lines, or with {@code olderFrom} > 0 those ending there (from an - * earlier {@link ServerLogPage#olderFrom()}). - */ - synchronized ServerLogPage read(long olderFrom) throws Exception { - SingleCommand cmd = new SingleCommand("logview", ProtocolRole.CLIENT); - cmd.add(new CommandSingleParameter("lines", Integer.toString(PAGE_LINES))); - if (olderFrom > 0) cmd.add(new CommandSingleParameter("begin_pos", Long.toString(olderFrom))); - cmd.add(new CommandSingleParameter("reverse", "1")); - cmd.add(new CommandSingleParameter("instance", "0")); - Reply r = new Reply(); - reply = r; - try { - conn.socket().executeCommand(cmd).complete(); - conn.awaitEventsProcessed(); - } catch (CommandException e) { - if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e; - } finally { - reply = null; - } - List entries = new ArrayList<>(r.entries); - Collections.reverse(entries); - return new ServerLogPage(entries, entries.isEmpty() ? 0 : r.lastPos); - } - - void onLine(UnknownTeamspeakEvent e) { - Reply r = reply; - if (r == null) return; - String line = e.get("l"); - if (line != null && !line.isEmpty()) r.entries.add(ServerLogEntry.parse(line)); - String lastPos = e.get("last_pos"); - if (lastPos != null) { - try { - r.lastPos = Long.parseLong(lastPos.trim()); - } catch (NumberFormatException ignored) { - // keep what the earlier lines said - } - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ServerLogEntry.java b/ts3-client/core/src/main/java/com/ts3client/net/ServerLogEntry.java deleted file mode 100644 index 8792b2c..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/ServerLogEntry.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.ts3client.net; - -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.Locale; - -/** - * One line of the virtual server's log, as {@code logview} hands it over: - * {@code 2026-10-04 13:11:01.038554|INFO |VirtualServer |1 |message}. - * - * @param timestamp when the server wrote it, in UTC as the server logs; {@code null} if the line had none - * @param channel the server component that wrote it, e.g. {@code VirtualServer} or {@code PktHandler} - */ -public record ServerLogEntry(LocalDateTime timestamp, Level level, String channel, String message) { - - /** The server's log levels, most severe first. */ - public enum Level { - CRITICAL, ERROR, WARNING, INFO, DEBUG, DEVEL - } - - private static final DateTimeFormatter TIMESTAMP = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSSSSS]"); - - /** - * Reads a log line. One whose timestamp is damaged — the server cuts the start off the - * file's very first line — keeps the rest; one that does not follow the format at all - * is kept whole as an info message. - */ - public static ServerLogEntry parse(String line) { - String[] fields = line.split("\\|", 5); - if (fields.length == 5) { - try { - Level level = Level.valueOf(fields[1].trim().toUpperCase(Locale.ROOT)); - return new ServerLogEntry(timestamp(fields[0]), level, fields[2].trim(), fields[4]); - } catch (IllegalArgumentException ignored) { - // not a line of ours; fall through - } - } - return new ServerLogEntry(null, Level.INFO, "", line); - } - - private static LocalDateTime timestamp(String field) { - try { - return LocalDateTime.parse(field.trim(), TIMESTAMP); - } catch (DateTimeParseException e) { - return null; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ServerLogPage.java b/ts3-client/core/src/main/java/com/ts3client/net/ServerLogPage.java deleted file mode 100644 index 16f9d62..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/ServerLogPage.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.ts3client.net; - -import java.util.List; - -/** - * A stretch of the server's log, oldest line first. - * - * @param olderFrom where the log's older lines end, to ask for them next; 0 once the start is reached - */ -public record ServerLogPage(List entries, long olderFrom) { - - public boolean hasOlder() { - return olderFrom > 0; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ServerModel.java b/ts3-client/core/src/main/java/com/ts3client/net/ServerModel.java deleted file mode 100644 index b30505a..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/ServerModel.java +++ /dev/null @@ -1,612 +0,0 @@ -package com.ts3client.net; - -import com.ts3client.net.ban.BanEntry; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Comparator; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * The current server state (channels + clients), updated from ts3j's event thread and read - * from the UI. The maps are guarded by the instance; the {@link ChannelNode}s and - * {@link ClientEntry}s handed out are live, with volatile fields, so a reader sees each value - * as it is now but not several of them changed together. - */ -public final class ServerModel { - - private final Map channels = new LinkedHashMap<>(); - private final Map clients = new LinkedHashMap<>(); - private final Map serverGroups = new LinkedHashMap<>(); - private final Map channelGroups = new LinkedHashMap<>(); - /** - * Permission id -> name, learned from the server's {@code permissionlist} response. - * Entries carry no id of their own: TS3 numbers them by position in the response, - * starting at 1, and the empty "group_id_end" separator records marking category - * boundaries don't count toward that position, so only {@link #putPermissionName} - * advances it. - */ - private final Map permissionNames = new LinkedHashMap<>(); - private final Map permissionIds = new HashMap<>(); - private static final int FIRST_PERMISSION_ID = 1; - private int nextPermissionId = FIRST_PERMISSION_ID; - /** Permission id -> the local client's resolved value, from {@code notifyclientneededpermissions}. */ - private final Map selfPermissionValues = new LinkedHashMap<>(); - /** The local client's {@link #UNREPORTED_PERMISSIONS}, which the needed permissions leave out; absent until known. */ - private final Map unreportedValues = new HashMap<>(); - private String serverName = "TeamSpeak Server"; - /** The {@code virtualserver_*} properties from {@code initserver}, kept up to date by server edits. */ - private final Map serverProperties = new HashMap<>(); - /** The channel group everyone starts in, e.g. "Guest" — not worth offering to (re)assign. */ - private int defaultChannelGroupId; - - public synchronized void clear() { - channels.clear(); - clients.clear(); - serverGroups.clear(); - channelGroups.clear(); - permissionNames.clear(); - permissionIds.clear(); - nextPermissionId = FIRST_PERMISSION_ID; - selfPermissionValues.clear(); - unreportedValues.clear(); - serverProperties.clear(); - defaultChannelGroupId = 0; - } - - // ---- groups ---- - - public synchronized void putServerGroup(Group group) { - if (group != null && group.name != null) serverGroups.put(group.id, group); - } - - public synchronized void putChannelGroup(Group group) { - if (group != null && group.name != null) channelGroups.put(group.id, group); - } - - public synchronized Group channelGroup(int id) { - return channelGroups.get(id); - } - - public synchronized String channelGroupName(int id) { - Group g = channelGroups.get(id); - return g == null ? null : g.name; - } - - public synchronized Group serverGroup(int id) { - return serverGroups.get(id); - } - - /** Resolves a client's server-group ids to groups, ordered for display. */ - public synchronized List serverGroupsOf(int[] ids) { - List groups = new ArrayList<>(); - if (ids != null) { - for (int id : ids) { - Group g = serverGroups.get(id); - if (g != null) groups.add(g); - } - } - groups.sort(Comparator.comparingInt((Group g) -> g.sortId).thenComparingInt(g -> g.id)); - return groups; - } - - /** Resolves server-group ids to their names, keeping unknown ids as "#id". */ - public synchronized List serverGroupNames(int[] ids) { - List names = new ArrayList<>(); - if (ids != null) { - for (int id : ids) { - Group g = serverGroups.get(id); - names.add(g != null ? g.name : "#" + id); - } - } - return names; - } - - /** Regular (non-template, non-query) server groups, ordered for display. */ - public synchronized List allServerGroups() { - return regularGroups(serverGroups); - } - - /** Regular (non-template, non-query) channel groups, ordered for display. */ - public synchronized List allChannelGroups() { - return regularGroups(channelGroups); - } - - private static List regularGroups(Map groups) { - List list = new ArrayList<>(); - for (Group g : groups.values()) { - if (g.isRegular()) list.add(g); - } - list.sort(Comparator.comparingInt((Group g) -> g.sortId).thenComparingInt(g -> g.id)); - return list; - } - - // ---- permissions ---- - - /** Records the next named entry of a {@code permissionlist} response; ignores separators. */ - public synchronized void putPermissionName(String name) { - if (name == null || name.isEmpty()) return; - permissionNames.put(nextPermissionId, name); - permissionIds.putIfAbsent(name, nextPermissionId); - nextPermissionId++; - } - - public synchronized void putSelfPermissionValue(int permId, int value) { - selfPermissionValues.put(permId, value); - } - - /** Whether the server's {@code permissionlist} has arrived, so ids can be named at all. */ - public synchronized boolean hasPermissionNames() { - return !permissionNames.isEmpty(); - } - - /** The name the server gave permission id {@code id}, or {@code null} if unknown. */ - public synchronized String permissionName(int id) { - return permissionNames.get(id); - } - - /** - * The local client's resolved value for a named permission (e.g. - * {@code "i_group_member_add_power"}), or {@code 0} if it isn't known - * yet (the {@code permissionlist} request is still in flight, or the server - * never reported a non-default value for it). - */ - public synchronized int selfPermissionValue(String name) { - return selfPermissionValue(name, 0); - } - - /** As {@link #selfPermissionValue(String)}, with {@code absent} for a permission not (yet) reported. */ - public synchronized int selfPermissionValue(String name, int absent) { - Integer id = permissionIds.get(name); - Integer value = id == null ? null : selfPermissionValues.get(id); - return value == null ? absent : value; - } - - /** - * The permissions {@code notifyclientneededpermissions} never carries, not even for an admin; - * they have to be asked for with {@code permget}. - */ - public static final List UNREPORTED_PERMISSIONS = List.of("i_client_move_power", - "i_client_kick_from_channel_power", "i_client_kick_from_server_power", "i_client_ban_power", - "b_client_complain_delete", "b_client_complain_delete_own"); - - /** Takes on the answer to asking for {@link #UNREPORTED_PERMISSIONS}; those it leaves out count as 0. */ - public synchronized void setUnreportedPermissions(Map values) { - unreportedValues.clear(); - unreportedValues.putAll(values); - } - - /** One of {@link #UNREPORTED_PERMISSIONS}; 0 until known, or when the server would not tell. */ - public synchronized int selfPower(String name) { - return unreportedValues.getOrDefault(name, 0); - } - - // ---- what the local client may do ---- - - /** - * Whether we hold a permission. Until the server has named its permissions nothing can - * be resolved, so everything is offered and the server is left to refuse. - */ - public synchronized boolean permits(String permission) { - return !hasPermissionNames() || selfPermissionValue(permission) > 0; - } - - /** - * Whether we may delete all of {@code bans}: any ban with {@code b_client_ban_delete}, - * only our own with {@code b_client_ban_delete_own}. - * - * @param selfUid our unique identifier, which is how a ban names its creator - */ - public synchronized boolean canDeleteBans(Collection bans, String selfUid) { - if (permits("b_client_ban_delete")) return true; - if (!permits("b_client_ban_delete_own")) return false; - return bans.stream().allMatch(b -> b.createdBy(selfUid)); - } - - /** - * Whether we may remove all of {@code complaints}: any with {@code b_client_complain_delete}, - * only those we filed with {@code b_client_complain_delete_own}. - */ - public synchronized boolean canDeleteComplaints(Collection complaints, int selfDbId) { - if (selfPower("b_client_complain_delete") > 0) return true; - if (selfPower("b_client_complain_delete_own") <= 0) return false; - return complaints.stream().allMatch(c -> c.fromDbId() == selfDbId); - } - - /** Whether we may rewrite {@code ban}: that is deleting it and creating its replacement. */ - public synchronized boolean canEditBan(BanEntry ban, String selfUid) { - return permits("b_client_ban_create") && canDeleteBans(List.of(ban), selfUid); - } - - /** {@code i_client_ban_max_bantime}: the longest ban we may hand out in seconds; 0 or -1 for no limit. */ - public synchronized long maxBanSeconds() { - return selfPermissionValue("i_client_ban_max_bantime"); - } - - /** - * Whether the local client has enough power to assign {@code group}, or to take it - * away when {@code assigned}: the add power always gates it, and the remove power - * additionally gates a group already held. {@code -1} is TS3's "unlimited" sentinel on - * either side: an unlimited local power always passes, and a group that needs - * unlimited power can only be touched by a local client that has it. - */ - public synchronized boolean canToggleGroup(Group group, boolean assigned) { - return hasPower(group.neededMemberAddPower, selfPermissionValue("i_group_member_add_power")) - && (!assigned || hasPower(group.neededMemberRemovePower, - selfPermissionValue("i_group_member_remove_power"))); - } - - /** Every regular server group, with whether {@code client} is in it and whether we may change that. */ - public synchronized List serverGroupChoices(ClientEntry client) { - List out = new ArrayList<>(); - for (Group g : allServerGroups()) { - boolean assigned = client.inServerGroup(g.id); - out.add(new GroupChoice(g, assigned, canToggleGroup(g, assigned))); - } - return out; - } - - /** Every regular channel group, with whether it is {@code client}'s and whether we may make it so. */ - public synchronized List channelGroupChoices(ClientEntry client) { - List out = new ArrayList<>(); - for (Group g : allChannelGroups()) { - boolean assigned = client.channelGroupId == g.id; - out.add(new GroupChoice(g, assigned, canToggleGroup(g, assigned))); - } - return out; - } - - /** The regular server or channel groups we have the power to put someone in, so may make a privilege key for. */ - public synchronized List privilegeKeyGroups(boolean channelGroups) { - List out = new ArrayList<>(); - for (Group g : channelGroups ? allChannelGroups() : allServerGroups()) { - if (canToggleGroup(g, false)) out.add(g); - } - return out; - } - - private static boolean hasPower(int needed, int own) { - if (own == -1) return true; - if (needed == -1) return false; - return own >= needed; - } - - /** - * Whether a channel shows in the tree at all — it doesn't while we are not subscribed - * to it (e.g. it needs more subscribe power than we have). - */ - public synchronized boolean isChannelVisible(int channelId) { - ChannelNode channel = channels.get(channelId); - return channel != null && channel.subscribed; - } - - /** - * Whether we can expect a join to succeed: the channel must be visible to us, and - * not already full. This can't account for a join-power permission requirement — - * unlike group membership, TS3 doesn't expose a channel's join-power threshold as - * a plain property, only as a permission resolved through channel/channel-group/ - * server-group inheritance, which isn't something a regular client can query. - */ - public synchronized boolean canJoinChannel(int channelId) { - ChannelNode channel = channels.get(channelId); - if (channel == null || !channel.subscribed) return false; - if (channel.maxClients < 0) return true; - int inside = 0; - for (ClientEntry c : clients.values()) { - if (c.channelId == channelId && !c.isQuery()) inside++; - } - return inside < channel.maxClients; - } - - public synchronized String getServerName() { - return serverName; - } - - public synchronized void setServerName(String name) { - if (name != null && !name.isEmpty()) this.serverName = name; - } - - /** Takes on the server properties among {@code properties}, keeping the others. */ - public synchronized void putServerProperties(Map properties) { - properties.forEach((key, value) -> { - // An empty property comes as a bare key, without a value. - if (key.startsWith("virtualserver_")) serverProperties.put(key, value == null ? "" : value); - }); - } - - /** @return the server property, empty when unknown */ - public synchronized String serverProperty(String key) { - return serverProperties.getOrDefault(key, ""); - } - - /** The server's own icon, 0 when it has none. */ - public synchronized long serverIconId() { - return IconRepository.parseId(serverProperty("virtualserver_icon_id")); - } - - /** The button the server puts in the toolbar's corner, or {@code null} when it has none. */ - public synchronized HostButton hostButton() { - return HostButton.of(serverProperty("virtualserver_hostbutton_url"), - serverProperty("virtualserver_hostbutton_gfx_url"), - serverProperty("virtualserver_hostbutton_tooltip")); - } - - public synchronized int defaultChannelGroupId() { - return defaultChannelGroupId; - } - - public synchronized void setDefaultChannelGroupId(int id) { - this.defaultChannelGroupId = id; - } - - // ---- channels ---- - - public synchronized ChannelNode putChannel(int id, String name, int parentId, int order) { - ChannelNode c = channels.computeIfAbsent(id, k -> new ChannelNode(id, name)); - if (name != null) c.name = name; - c.parentId = parentId; - c.order = order; - return c; - } - - public synchronized ChannelNode getChannel(int id) { - return channels.get(id); - } - - /** - * Marks the channel we are in as subscribed. The server tells us about it along with - * everything else there, but never announces the subscription for the channel we - * start out in, although it stays subscribed after we leave it. - */ - public synchronized void enteredChannel(int id) { - ChannelNode channel = channels.get(id); - if (channel != null) channel.subscribed = true; - } - - public synchronized void removeChannel(int id) { - ChannelNode c = channels.remove(id); - if (c == null) return; - // Whatever followed it now follows its predecessor. - for (ChannelNode o : channels.values()) { - if (o.parentId == c.parentId && o.order == id) o.order = c.order; - } - } - - /** - * Places a channel after {@code newOrder} (0 = first) under {@code newParentId}, - * repairing the sibling links the server does not re-announce: the channel that - * used to follow it, and the one that follows it now. - */ - public synchronized void relinkChannel(int cid, int newParentId, int newOrder) { - ChannelNode c = channels.get(cid); - if (c == null) return; - for (ChannelNode o : channels.values()) { - if (o.id == cid) continue; - if (o.parentId == c.parentId && o.order == cid) o.order = c.order; - } - for (ChannelNode o : channels.values()) { - if (o.id == cid) continue; - if (o.parentId == newParentId && o.order == newOrder) o.order = cid; - } - c.parentId = newParentId; - c.order = newOrder; - } - - /** - * The channels sharing a parent with {@code channelId}, in the order they appear in the - * tree and excluding the channel itself — what the editor offers as places to sort after. - */ - public synchronized List siblingsOf(int channelId) { - ChannelNode channel = channels.get(channelId); - if (channel == null) return new ArrayList<>(); - // Ordered with the channel still in place: the order links form a chain, and - // pulling a link out of it first would strand everything below. - List siblings = childrenOf(channel.parentId); - siblings.remove(channel); - return siblings; - } - - /** - * The channels directly below {@code parentId} (0 being the top level), in the order - * they appear in the tree — what a new channel can be sorted after. - */ - public synchronized List childrenOf(int parentId) { - List children = new ArrayList<>(); - for (ChannelNode c : channels.values()) { - if (c.parentId == parentId) children.add(c); - } - sortSiblings(children); - return children; - } - - /** Every channel, depth first in the order the tree shows them. */ - public synchronized List channelsInTreeOrder() { - List out = new ArrayList<>(); - addInTreeOrder(0, out); - return out; - } - - private void addInTreeOrder(int parentId, List out) { - for (ChannelNode c : childrenOf(parentId)) { - out.add(c); - addInTreeOrder(c.id, out); - } - } - - /** The channel of that exact name directly below {@code parentId}, or {@code null}. */ - public synchronized ChannelNode findChannelByName(int parentId, String name) { - for (ChannelNode c : channels.values()) { - if (c.parentId == parentId && c.name.equals(name)) return c; - } - return null; - } - - /** The "/"-separated path of a channel from the root, e.g. {@code "Lobby/Games"}. */ - public synchronized String channelPath(int id) { - ChannelNode c = channels.get(id); - if (c == null) return ""; - StringBuilder sb = new StringBuilder(); - for (int guard = 0; c != null && guard < 64; guard++) { - if (sb.length() > 0) sb.insert(0, '/'); - sb.insert(0, c.name == null ? "" : c.name); - c = channels.get(c.parentId); - } - return sb.toString(); - } - - /** - * Resolves a channel reference as stored in a bookmark: either a "/"-separated - * path (matched case-insensitively) or {@code "/"}. - * - * @return the channel, or {@code null} if the server has no such channel - */ - public synchronized ChannelNode findChannelByPath(String path) { - if (path == null) return null; - String trimmed = path.trim(); - while (trimmed.startsWith("/")) trimmed = trimmed.substring(1); - while (trimmed.endsWith("/")) trimmed = trimmed.substring(0, trimmed.length() - 1); - if (trimmed.isEmpty()) return null; - - if (trimmed.chars().allMatch(Character::isDigit)) { - ChannelNode byId = channels.get(Integer.parseInt(trimmed)); - if (byId != null) return byId; - } - for (ChannelNode c : channels.values()) { - if (channelPath(c.id).equalsIgnoreCase(trimmed)) return c; - } - // Fall back to a plain name match so a bookmark keeps working when the - // channel is moved within the tree. - for (ChannelNode c : channels.values()) { - if (c.name != null && c.name.equalsIgnoreCase(trimmed)) return c; - } - return null; - } - - // ---- clients ---- - - public synchronized ClientEntry putClient(int id, String nickname, int channelId) { - ClientEntry c = clients.computeIfAbsent(id, k -> new ClientEntry(id, nickname)); - if (nickname != null) c.nickname = nickname; - c.channelId = channelId; - return c; - } - - public synchronized ClientEntry getClient(int id) { - return clients.get(id); - } - - public synchronized void removeClient(int id) { - clients.remove(id); - } - - /** A snapshot of every client on the server. */ - public synchronized List allClients() { - return new ArrayList<>(clients.values()); - } - - public synchronized ClientEntry findClientByUniqueId(String uniqueId) { - if (uniqueId == null || uniqueId.isEmpty()) return null; - for (ClientEntry c : clients.values()) { - if (uniqueId.equals(c.uniqueId)) return c; - } - return null; - } - - /** An online client by its database id, or {@code null} if none is visible. */ - public synchronized ClientEntry findClientByDatabaseId(int databaseId) { - if (databaseId <= 0) return null; - for (ClientEntry c : clients.values()) { - if (c.databaseId == databaseId) return c; - } - return null; - } - - public synchronized ClientEntry findClientByName(String name) { - for (ClientEntry c : clients.values()) { - if (c.nickname != null && c.nickname.equals(name)) return c; - } - return null; - } - - /** - * Builds an ordered forest of channels (each with its clients attached), sorted - * by TS3's channel order chain and then by client talk power / name. - * - * @return the list of root channels (parentId == 0) - */ - public synchronized List buildTree() { - // Fresh lists, published whole: whoever still walks the previous tree keeps a consistent one. - Map> children = new HashMap<>(); - Map> inside = new HashMap<>(); - List roots = new ArrayList<>(); - for (ChannelNode c : channels.values()) { - ChannelNode parent = channels.get(c.parentId); - if (c.parentId == 0 || parent == null) { - roots.add(c); - } else { - children.computeIfAbsent(parent.id, id -> new ArrayList<>()).add(c); - } - } - for (ClientEntry cl : clients.values()) { - if (cl.isQuery()) continue; // hide server-query clients from the tree - if (channels.containsKey(cl.channelId)) { - inside.computeIfAbsent(cl.channelId, id -> new ArrayList<>()).add(cl); - } - } - - Comparator byClient = Comparator - .comparingInt((ClientEntry c) -> -c.talkPower) - .thenComparing(c -> c.nickname == null ? "" : c.nickname.toLowerCase()); - - sortSiblings(roots); - for (ChannelNode c : channels.values()) { - List below = children.getOrDefault(c.id, List.of()); - sortSiblings(below); - c.children = List.copyOf(below); - List members = inside.getOrDefault(c.id, List.of()); - if (members.size() > 1) members.sort(byClient); - c.clients = List.copyOf(members); - } - return roots; - } - - /** - * Orders one set of sibling channels in place. TS3 stores the position as - * {@code channel_order} = the id of the channel above it (0 = topmost), so the - * siblings form a linked list rather than a sortable key. - */ - private static void sortSiblings(List siblings) { - if (siblings.size() < 2) return; - Map byPredecessor = new LinkedHashMap<>(); - for (ChannelNode c : siblings) byPredecessor.putIfAbsent(c.order, c); - - List ordered = new ArrayList<>(siblings.size()); - java.util.Set placed = new java.util.HashSet<>(); - for (int key = 0; ; ) { - ChannelNode next = byPredecessor.get(key); - if (next == null || !placed.add(next.id)) break; - ordered.add(next); - key = next.id; - } - // A broken chain (duplicate or dangling links) leaves stragglers; keep them - // rather than dropping channels from the tree. - for (ChannelNode c : siblings) { - if (!placed.contains(c.id)) ordered.add(c); - } - siblings.clear(); - siblings.addAll(ordered); - } - - public synchronized int channelCount() { - return channels.size(); - } - - public synchronized int clientCount() { - int n = 0; - for (ClientEntry c : clients.values()) if (!c.isQuery()) n++; - return n; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/Spacers.java b/ts3-client/core/src/main/java/com/ts3client/net/Spacers.java deleted file mode 100644 index 2534bef..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/Spacers.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.ts3client.net; - - -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Parses TeamSpeak 3 "spacer" channel names — cosmetic root channels used as - * separators, e.g. {@code [spacer0]---}, {@code [*spacer1]=}, {@code [cspacer]Rules}. - * The tag selects alignment ({@code l}/{@code c}/{@code r}) or fill ({@code *}). - */ -public final class Spacers { - - /** - * A parsed spacer name. - * - * @param align 'l', 'c', 'r', or '*' (repeat the caption to fill) - */ - public record Spacer(char align, String caption) { - } - - /** The tag's identifying part, which is what keeps two spacers' names apart. */ - private static final Pattern TAG = Pattern.compile("^\\[(?:\\*|[lcr])?spacer([^\\]]*)\\]"); - - private static final Pattern PATTERN = - Pattern.compile("^\\[(\\*|[lcr])?spacer[^\\]]*\\](.*)$"); - - private Spacers() { - } - - /** Returns spacer info if {@code channelName} is a spacer, else {@code null}. */ - public static Spacer parse(String channelName) { - if (channelName == null) return null; - Matcher m = PATTERN.matcher(channelName); - if (!m.matches()) return null; - String tag = m.group(1); - char align = (tag == null || tag.isEmpty()) ? 'l' : tag.charAt(0); - return new Spacer(align, m.group(2)); - } - - public static boolean isSpacer(String channelName) { - return parse(channelName) != null; - } - - /** - * A spacer name no channel among {@code siblings} is using: {@code [spacerN]} with the - * lowest free N. TeamSpeak needs channel names to be unique, and the number in the tag - * is how spacers — which usually all read the same — get away with it. - */ - public static String freeName(List siblings) { - Set taken = new HashSet<>(); - for (ChannelNode sibling : siblings) { - Matcher m = TAG.matcher(sibling.name == null ? "" : sibling.name); - if (m.find()) taken.add(m.group(1)); - } - for (int n = 0; ; n++) { - if (taken.add(Integer.toString(n))) return "[spacer" + n + "]"; - } - } - - /** Builds the visible label for a spacer at roughly the given character width. */ - public static String render(Spacer s, int width) { - String caption = s.caption() == null ? "" : s.caption(); - if (s.align() == '*') { - if (caption.isEmpty()) return ""; - StringBuilder sb = new StringBuilder(); - while (sb.length() < width) sb.append(caption); - return sb.substring(0, Math.max(caption.length(), Math.min(sb.length(), width))); - } - if (s.align() == 'c') { - int pad = Math.max(0, (width - caption.length()) / 2); - return " ".repeat(pad) + caption; - } - if (s.align() == 'r') { - int pad = Math.max(0, width - caption.length()); - return " ".repeat(pad) + caption; - } - return caption; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/TeamspeakConnection.java b/ts3-client/core/src/main/java/com/ts3client/net/TeamspeakConnection.java deleted file mode 100644 index 6fb3cae..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/TeamspeakConnection.java +++ /dev/null @@ -1,1997 +0,0 @@ -package com.ts3client.net; - -import com.github.manevolent.ts3j.api.Client; -import com.github.manevolent.ts3j.command.CommandException; -import com.github.manevolent.ts3j.command.MultiCommand; -import com.github.manevolent.ts3j.command.SingleCommand; -import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; -import com.github.manevolent.ts3j.event.*; -import com.github.manevolent.ts3j.identity.LocalIdentity; -import com.github.manevolent.ts3j.identity.Uid; -import com.github.manevolent.ts3j.protocol.ProtocolRole; -import com.github.manevolent.ts3j.protocol.packet.PacketBody1VoiceWhisper; -import com.github.manevolent.ts3j.protocol.socket.client.LocalTeamspeakClientSocket; -import com.github.manevolent.ts3j.util.Ts3Crypt; -import com.ts3client.audio.AudioBackend; -import com.ts3client.audio.VoiceInput; -import com.ts3client.audio.VoiceOutput; -import com.ts3client.chatlog.ChatLogScope; -import com.ts3client.chatlog.ChatLogStore; -import com.ts3client.config.Settings; -import com.ts3client.contacts.Contact; -import com.ts3client.contacts.ContactStore; -import com.ts3client.net.avatar.Avatar; -import com.ts3client.net.avatar.AvatarNaming; -import com.ts3client.net.avatar.AvatarRepository; -import com.ts3client.net.filetransfer.FileTransfer; -import com.ts3client.net.filetransfer.FileTransferManager; -import com.ts3client.net.ban.BanEntry; -import com.ts3client.net.ban.BanRule; -import com.ts3client.net.filetransfer.RemoteFile; -import com.ts3client.recording.VoiceRecorder; -import com.ts3client.sound.SoundEvent; -import com.ts3client.sound.SoundNotifier; -import com.ts3client.text.TsLink; - -import java.io.File; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.function.BiConsumer; -import java.util.function.Consumer; - -/** - * High-level facade that ties the ts3j protocol socket to the audio subsystem and - * the {@link ServerModel}, translating protocol events into {@link ConnectionListener} - * callbacks for the UI. - */ -public final class TeamspeakConnection implements TS3Listener { - - /** Upper bound for a group icon; anything larger is not an icon. Also used by {@link ChannelAdmin}. */ - static final int MAX_ICON_BYTES = 1024 * 1024; - - /** The longest reason the protocol carries with a kick. */ - public static final int KICK_REASON_LIMIT = 40; - /** The longest reason a complaint may carry. */ - public static final int COMPLAINT_REASON_LIMIT = 200; - /** The longest subject and body an offline message may carry, in characters. */ - public static final int OFFLINE_MESSAGE_SUBJECT_LIMIT = 200; - public static final int OFFLINE_MESSAGE_LIMIT = 4096; - /** What {@link #searchDatabaseClients} reports when the server will not let us search. */ - public static final String SEARCH_NOT_PERMITTED = - "You have no permission to search for users on this server, so you can only use contacts or unique IDs."; - - /** The protocol's reason ids for the two flavours of clientkick. */ - private static final int REASON_KICK_CHANNEL = 4; - private static final int REASON_KICK_SERVER = 5; - - private static final int ERROR_PERMISSIONS_CLIENT_INSUFFICIENT = 0x0a08; - private static final int ERROR_PERMISSIONS_INSUFFICIENT_GROUP_POWER = 0x0a09; - private static final int ERROR_PERMISSIONS_INSUFFICIENT_PERMISSION_POWER = 0x0a0a; - - /** Shortest gap between two "you are talking while muted" reminders. */ - private static final long MUTED_TALK_COOLDOWN_NANOS = 5_000_000_000L; - - /** - * How long the handshake and initial download may take. That download includes the whole - * channel list, which on a big server over a lossy link (mobile data) takes a while. - */ - private static final long CONNECT_TIMEOUT_MS = 30_000L; - - private final Settings settings; - private final AudioBackend audio; - private final ServerModel model = new ServerModel(); - /** Package-private: read directly by {@link ConnectionEventHandler}. */ - final ConnectionListener ui; - private final IconRepository icons; - private final AvatarRepository avatars; - /** Package-private: read directly by {@link ConnectionEventHandler}. */ - final SoundNotifier sounds; - /** Friends, blocked clients and their per-client filters; also read by {@link ConnectionEventHandler}. */ - final ContactStore contacts; - /** The {@link TS3Listener} side of this connection; see its class doc. */ - private final ConnectionEventHandler events = new ConnectionEventHandler(this); - /** Builds {@code getconnectioninfo} snapshots; also package-private for {@link ConnectionEventHandler}. */ - final ConnectionStatsCollector stats = new ConnectionStatsCollector(this); - /** Channel editing and the server's icon store; package-private for {@link ConnectionEventHandler}. */ - final ChannelAdmin channels = new ChannelAdmin(this); - /** The server's ban list, privilege keys, complaints and log; also package-private for {@link ConnectionEventHandler}. */ - final BanAdmin bans = new BanAdmin(this); - final PrivilegeKeyAdmin privilegeKeys = new PrivilegeKeyAdmin(this); - final ComplaintAdmin complaints = new ComplaintAdmin(this); - final ServerLogAdmin serverLog = new ServerLogAdmin(this); - /** Our offline message inbox; package-private for {@link ConnectionEventHandler}. */ - final OfflineMessageAdmin offlineMessages = new OfflineMessageAdmin(this); - private final AvatarAdmin avatarAdmin = new AvatarAdmin(this); - - /* - * Set up by the connect thread and torn down by whichever thread notices the end; read from - * the UI, event and action threads, so each reader copies the field before using it. - */ - /** Package-private: read directly by {@link ConnectionStatsCollector}. */ - volatile LocalTeamspeakClientSocket client; - /** The client whose whisper we heard last, to reply to; 0 for none yet. */ - private volatile int lastWhisperer; - private volatile VoiceInput microphone; - private volatile VoiceOutput playback; - private volatile LocalIdentity identity; - private volatile FileTransferManager fileTransfers; - private volatile ChatLogStore chatLogs; - /** The recording in progress; guarded by this connection. */ - private VoiceRecorder recorder; - /** - * Runs ts3j's event callbacks. Supplying it ourselves (rather than leaving ts3j to make - * its own) is what lets {@link #awaitEventsProcessed()} tell when everything the server - * has already sent has been handled. Closed together with the socket. - */ - private volatile ExecutorService eventExecutor; - /** Runs this connection's requests to the server; created on connect, shut down with the socket. */ - private volatile ExecutorService actions; - - private volatile boolean connected; - /** - * The connect in progress. A disconnect clears it and a newer connect replaces it, which - * tells a superseded attempt that is still failing not to clean up after itself. - */ - private volatile Object connectAttempt; - private volatile int selfClientId = -1; - /** Package-private: read directly by {@link ConnectionStatsCollector}. */ - volatile long connectedAtMs; - private volatile String serverHost; - private volatile int serverPort; - - /** - * Whether this connection owns the capture device. Only one connection may - * capture at a time, so the frontend hands the microphone to a single - * connection and the others keep their (idle) input pipeline. - */ - private volatile boolean microphoneActive; - - /** Speakers muted: only actions marked important are still heard. */ - private volatile boolean deafened; - /** Set while we are leaving on purpose, to tell a clean disconnect from a drop. */ - private volatile boolean leaving; - /** Guards against announcing the same disconnect from both the event and the teardown. */ - private volatile boolean disconnectAnnounced = true; - private volatile long lastMutedTalkNanos; - /** The server's error id for why the last connect was refused; 0 when it was not. */ - private volatile int connectErrorId; - - public TeamspeakConnection(Settings settings, AudioBackend audio, ConnectionListener ui, - SoundNotifier sounds, ContactStore contacts) { - this.settings = settings; - this.audio = audio; - this.ui = ui; - this.sounds = sounds; - this.contacts = contacts; - this.icons = new IconRepository(this::fetchIcon, ui::onIconsUpdated); - this.avatars = new AvatarRepository(this::fetchAvatar, ui::onInfoUpdated); - } - - public ServerModel getModel() { - return model; - } - - public boolean isConnected() { - return connected; - } - - public int getSelfClientId() { - return selfClientId; - } - - public VoiceInput getMicrophone() { - return microphone; - } - - public VoiceOutput getPlayback() { - return playback; - } - - /** - * The error id the server refused the last connect with ({@code 3329} for a ban, - * for one), or 0 when it was not refused or did not get that far. - */ - public int getConnectErrorId() { - return connectErrorId; - } - - /** The identity this connection authenticated with. */ - public LocalIdentity getIdentity() { - return identity; - } - - /** Address this connection was last asked to connect to. */ - public String getServerHost() { - return serverHost == null ? "" : serverHost; - } - - public int getServerPort() { - return serverPort; - } - - /** - * Gives this connection the capture device, or takes it away. Capturing only - * starts once connected; calling this before or during a connect is fine, the - * requested state is applied as soon as the microphone exists. - */ - public synchronized void setMicrophoneActive(boolean active) { - microphoneActive = active; - applyMicrophoneState(); - } - - public boolean isMicrophoneActive() { - return microphoneActive; - } - - /** Starts or stops capture to match {@link #microphoneActive}. */ - private synchronized void applyMicrophoneState() { - VoiceInput mic = microphone; - if (mic == null || !connected) return; - try { - if (microphoneActive) mic.start(); - else mic.stop(); - } catch (Exception e) { - ui.onError("Microphone unavailable: " + rootMessage(e)); - } - pushInputHardware(); - } - - /** - * Reports whether the capture device is actually available on this connection, so - * other clients see "Microphone Disabled" rather than plain silence while another - * tab holds it. {@code clientinit} always claims hardware input, so this is what - * corrects that once tabs start sharing one microphone. - */ - private void pushInputHardware() { - boolean hardware = microphoneActive; - updateSelf(self -> self.inputHardware = hardware); - selfUpdate(cmd -> - cmd.add(new CommandSingleParameter("client_input_hardware", hardware ? "1" : "0")), - "Microphone hardware status update failed"); - } - - // ---- connection lifecycle ---- - - /** - * Connects in the background, joining a specific channel instead of the server's - * default one. - * - * @param phoneticNickname how text-to-speech should say the nickname; may be empty - * @param identity identity to authenticate with; see {@link com.ts3client.config.IdentityStore} - * @param channel channel path ("Lobby/Games") or "/<channelId>"; null/empty for the default channel - * @param channelPassword password for that channel, or null if it has none - */ - public void connect(String address, int port, String nickname, String phoneticNickname, String password, - LocalIdentity identity, String channel, String channelPassword) { - new Thread(() -> doConnect(address, port, nickname, phoneticNickname, password, identity, channel, - channelPassword), "ts3j-connect").start(); - } - - private void doConnect(String address, int port, String nickname, String phoneticNickname, String password, - LocalIdentity withIdentity, String channel, String channelPassword) { - Object attempt = new Object(); - connectAttempt = attempt; - connectErrorId = 0; - // A socket or audio line an earlier connect left behind must not outlive it. - connected = false; - safeCleanup(); - try { - identity = withIdentity; - serverHost = address; - serverPort = port; - - model.clear(); - lastWhisperer = 0; - playback = audio.createOutput(settings); - playback.setMasterVolume(settings.effectiveOutputVolume()); - playback.setReceiveBuffer(settings.receiveBuffer); - playback.setTalkListener((clientId, talking) -> { - ClientEntry c = model.getClient(clientId); - if (c != null) c.talking = talking; - if (c != null && inOwnChannel(c.channelId)) { - sound(talking ? SoundEvent.SPECIAL_MIC_CLICK_OTHER_ON - : SoundEvent.SPECIAL_MIC_CLICK_OTHER_OFF, clientVars(clientId, null)); - } - ui.onTalkStateChanged(clientId, talking); - }); - - microphone = audio.createInput(settings); - microphone.setTalkListener(talking -> { - if (selfClientId >= 0) { - ClientEntry c = model.getClient(selfClientId); - if (c != null) c.talking = talking; - sound(talking ? SoundEvent.SPECIAL_MIC_CLICK_SELF_ON - : SoundEvent.SPECIAL_MIC_CLICK_SELF_OFF); - ui.onTalkStateChanged(selfClientId, talking); - } - }); - microphone.setMutedTalkListener(this::onTalkingWhileMuted); - - client = new LocalTeamspeakClientSocket(); - eventExecutor = Executors.newSingleThreadExecutor(r -> { - Thread t = new Thread(r, "ts3j-events"); - t.setDaemon(true); - return t; - }); - client.setCommandExecutorService(eventExecutor); - actions = Executors.newCachedThreadPool(r -> { - Thread t = new Thread(r, "ts3j-action"); - t.setDaemon(true); - return t; - }); - client.setIdentity(identity); - client.setNickname(nickname); - setIfPresent("client.nickname_phonetic", phoneticNickname); - client.setHWID("ts3jswing-" + Integer.toHexString(nickname.hashCode())); - client.addListener(this); - client.addListener(events); - client.setVoiceHandler(playback::handleVoice); - client.setWhisperHandler(whisper -> { - if (!isWhisperAllowed(whisper.getClientId())) return; - lastWhisperer = whisper.getClientId(); - playback.handleWhisper(whisper); - }); - client.setExceptionHandler(t -> { - // A late packet dispatched after close() rejects on the shut-down - // command executor; harmless during teardown. - if (t instanceof java.util.concurrent.RejectedExecutionException) return; - ui.onError("Network error: " + messageChain(t)); - }); - - applyClientVersion(); - applyDefaultChannel(channel, channelPassword); - - ui.onStatus("Connecting to " + address + ":" + port + "…"); - client.connect(new InetSocketAddress(address, port), - (password == null || password.isEmpty()) ? null : password, - CONNECT_TIMEOUT_MS); - - // Protocol connection established; anything past this point is best-effort. - selfClientId = client.getClientId(); - // Our own row usually arrives among the enter-view events the connect - // handshake carries, i.e. before our id was known here, so it has to be - // marked once it is. - ClientEntry ourselves = model.getClient(selfClientId); - if (ourselves != null) { - ourselves.self = true; - model.enteredChannel(ourselves.channelId); - } - fileTransfers = new FileTransferManager(client, () -> serverHost); - client.setMicrophone(microphone); - icons.retryFailed(); - avatars.retryFailed(); - connected = true; - connectedAtMs = System.currentTimeMillis(); - leaving = false; - disconnectAnnounced = false; - deafened = false; - offlineMessages.reset(); - loadChatLogs(); - ui.onConnected(); - requestPermissionNames(); - requestSelfPowers(); - - ui.onStatus("Retrieving channels…"); - syncAll(); - ui.onModelChanged(); - joinDefaultChannelIfNeeded(channel, channelPassword); - ui.onStatus("Connected to " + model.getServerName()); - sound(SoundEvent.CONNECTION_CONNECTED, serverVars()); - unreadMessagesChanged(0); - - // Only captures if this connection holds the microphone. - applyMicrophoneState(); - } catch (Exception e) { - // Whoever took over reports on their own; cleaning up here would tear down what a newer - // connect has set up in the meantime. - if (connectAttempt != attempt) return; - connected = false; - connectErrorId = refusalId(e); - String failure = "Connection failed: " + rootMessage(e) + versionHint(e); - ui.onError(failure); - safeCleanup(); - // Report the failed attempt as a disconnect too, so the UI leaves the - // "connecting" state and the tab becomes reusable. The status keeps saying why. - ui.onDisconnected("connection failed"); - ui.onStatus(failure); - } - } - - private static int refusalId(Throwable e) { - for (Throwable t = e; t != null; t = t.getCause()) { - if (t instanceof CommandException refusal) return refusal.getErrorId(); - } - return 0; - } - - /** - * "client is modified" is what a server answers when it does not accept the reported - * version: too old for its minimum, not a version it knows for that platform, or a - * signature that does not belong to the two. Easy to run into after editing them by - * hand, and the bare message does not point anywhere. - */ - private String versionHint(Exception e) { - if (!settings.customVersion) return ""; - String message = rootMessage(e); - return message != null && message.contains("client is modified") - ? " — the server did not accept the custom client version; pick a newer one" - + " of the listed versions in Options." - : ""; - } - - /** - * Reports the version and operating system the user configured, which is what - * other clients see in the info panel. Each field falls back to the library's - * built-in one when left empty; the signature has to match the version and - * platform it was issued for, or a server may refuse the connection. - */ - private void applyClientVersion() { - if (!settings.customVersion) return; - setIfPresent("client.version_string", settings.clientVersion); - setIfPresent("client.version_platform", settings.clientPlatform); - setIfPresent("client.version_sign", settings.clientVersionSign); - } - - private void setIfPresent(String option, String value) { - if (value != null && !value.isBlank()) client.setOption(option, value.trim()); - } - - /** - * Asks the server, as part of {@code clientinit}, to place us in a specific - * channel right away instead of the default one. This is the path a real client - * takes for bookmarks, and it avoids being briefly visible in the wrong channel. - */ - private void applyDefaultChannel(String channel, String channelPassword) { - String path = normaliseChannelRef(channel); - if (path == null) return; - client.setOption("client.default_channel", path); - if (channelPassword != null && !channelPassword.isEmpty()) { - client.setOption("client.default_channel_password", Ts3Crypt.hashPassword(channelPassword)); - } - } - - /** - * Fallback for when {@code clientinit} did not put us in the requested channel: - * the path may not have matched exactly, or the channel may have been created - * after the bookmark was saved. Resolves the reference against the now-known - * channel list and moves there. - */ - private void joinDefaultChannelIfNeeded(String channel, String channelPassword) { - if (normaliseChannelRef(channel) == null) return; - LocalTeamspeakClientSocket sock = client; - if (sock == null || !connected) return; // already left again - ChannelNode target = model.findChannelByPath(channel); - if (target == null) { - ui.onError("Channel \"" + channel.trim() + "\" not found on this server."); - return; - } - if (currentChannelId() == target.id) return; // clientinit already put us there - try { - sock.joinChannel(target.id, (channelPassword == null || channelPassword.isEmpty()) - ? null : channelPassword); - } catch (Exception e) { - if (!connected) return; - error("Could not join channel \"" + target.name + "\": ", e); - } - } - - /** - * The channel we are in, taken from the model and, if the client list was not - * readable, asked from the server directly. - * - * @return the channel id, or -1 when unknown - */ - private int currentChannelId() { - ClientEntry self = model.getClient(selfClientId); - if (self != null) return self.channelId; - try { - return client.getClientInfo(selfClientId).getChannelId(); - } catch (Exception e) { - return -1; - } - } - - /** - * @return the channel reference in {@code clientinit} form ("/<id>" for a - * numeric id, otherwise the path), or null when no channel was requested - */ - private static String normaliseChannelRef(String channel) { - if (channel == null) return null; - String path = channel.trim(); - while (path.startsWith("/")) path = path.substring(1); - while (path.endsWith("/")) path = path.substring(0, path.length() - 1); - if (path.isEmpty()) return null; - return path.chars().allMatch(Character::isDigit) ? "/" + path : path; - } - - /** - * Completes the model once connected. Channels and clients already arrived as events - * during {@code connect()}, complete, as the official client gets them. The - * {@code channellist}/{@code clientlist} query commands must not be used to re-read - * them: their rows lack groups, unique ids and away state, and they count heavily - * against the server's flood protection. - */ - private void syncAll() { - try { - client.subscribeAll(); - } catch (Exception e) { - ui.onStatus("Limited subscription: " + rootMessage(e)); - } - // The name comes with initserver; servergetvariables never reports it. - model.setServerName(client.getServerName()); - model.putServerProperties(client.getServerProperties()); - model.setDefaultChannelGroupId( - (int) safeLong(client.getServerProperties().get("virtualserver_default_channel_group"))); - } - - public void disconnect() { - new Thread(() -> disconnectBlocking("Leaving"), "ts3j-disconnect").start(); - } - - /** - * Disconnect synchronously on the calling thread, notifying the UI. Used both - * by the async {@link #disconnect()} and by shutdown paths (Ctrl+C, window - * close) where the JVM must not exit before the leave notification is sent. - */ - public void disconnectBlocking(String reason) { - connectAttempt = null; - leaving = true; - try { - if (client != null) client.disconnect(reason); - } catch (Exception ignored) { - } finally { - safeCleanup(); - connected = false; - announceDisconnect(true); - ui.onDisconnected("You disconnected"); - ui.onStatus("Disconnected"); - } - } - - /** - * Plays the disconnect sound once per connection: leaving on purpose is a - * different action from having the connection drop underneath us, and both the - * socket event and our own teardown can arrive. - */ - private void announceDisconnect(boolean deliberate) { - if (disconnectAnnounced) return; - disconnectAnnounced = true; - sound(deliberate || leaving ? SoundEvent.CONNECTION_DISCONNECTED - : SoundEvent.CONNECTION_LOST_CONNECTION, serverVars()); - } - - /** Reminds the user, at most every few seconds, that the microphone is muted. */ - private void onTalkingWhileMuted() { - if (!settings.mutedTalkWarning) return; - long now = System.nanoTime(); - if (now - lastMutedTalkNanos < MUTED_TALK_COOLDOWN_NANOS) return; - lastMutedTalkNanos = now; - sound(SoundEvent.SPECIAL_TALKING_WHILE_MUTED); - } - - private synchronized void safeCleanup() { - // Finishes the files; there is no server left to tell. - VoiceRecorder rec = recorder; - if (rec != null) { - detachRecorder(); - rec.stop(); - } - VoiceInput mic = microphone; - VoiceOutput out = playback; - LocalTeamspeakClientSocket sock = client; - FileTransferManager ft = fileTransfers; - ExecutorService events = eventExecutor; - ExecutorService pool = actions; - eventExecutor = null; - actions = null; - microphone = null; - playback = null; - client = null; - fileTransfers = null; - chatLogs = null; - selfClientId = -1; - stats.clear(); - - if (ft != null) { - try { - ft.shutdown(); - } catch (Exception ignored) { - } - } - - if (mic != null) { - try { - mic.stop(); - } catch (Exception ignored) { - } - } - if (out != null) { - try { - out.shutdown(); - } catch (Exception ignored) { - } - } - if (sock != null) { - try { - sock.close(); - } catch (Exception ignored) { - } - } - if (events != null) events.shutdownNow(); - if (pool != null) pool.shutdownNow(); - } - - // ---- self actions ---- - - public void setMicMuted(boolean muted) { - VoiceInput mic = microphone; - if (mic != null) mic.setMuted(muted); - sound(muted ? SoundEvent.SOUND_CAPTURE_MUTED : SoundEvent.SOUND_CAPTURE_UNMUTED); - pushSelfFlags(); - } - - /** - * TS3's "Local Mic Mute": silences capture without touching the {@code client_input_muted} - * status the server (and other clients) see, and without a mute/unmute sound. - */ - public void setMicLocalMuted(boolean muted) { - VoiceInput mic = microphone; - if (mic != null) mic.setLocalMuted(muted); - } - - public void setDeafened(boolean deaf) { - // Announce muting while we can still be heard, and unmuting once we can again. - if (deaf) sound(SoundEvent.SOUND_PLAYBACK_MUTED); - deafened = deaf; - VoiceOutput out = playback; - if (out != null) out.setDeafened(deaf); - if (!deaf) sound(SoundEvent.SOUND_PLAYBACK_UNMUTED); - pushSelfFlags(); - } - - private void pushSelfFlags() { - VoiceInput mic = microphone; - VoiceOutput out = playback; - if (mic == null || out == null) return; - boolean micMuted = mic.isMuted(); - boolean deaf = out.isDeafened(); - updateSelf(self -> { - self.inputMuted = micMuted; - self.outputMuted = deaf; - }); - - // Publish the input/output muted flags to the server so others see them. These - // are runtime status, not editable client-database properties, so they go out - // through clientupdate (like nickname/away), not clientedit. - selfUpdate(cmd -> { - cmd.add(new CommandSingleParameter("client_input_muted", micMuted ? "1" : "0")); - cmd.add(new CommandSingleParameter("client_output_muted", deaf ? "1" : "0")); - }, "Mute status update failed"); - } - - public void joinChannel(int channelId, String password) { - act("Could not join channel: ", sock -> - sock.joinChannel(channelId, (password == null || password.isEmpty()) ? null : password)); - } - - /** Moves another client (or ourselves) into a channel. */ - public void moveClient(int clientId, int channelId, String password) { - act("Could not move client: ", sock -> sock.clientMove(clientId, channelId, - (password == null || password.isEmpty()) ? null : password)); - } - - /** Kicks a client out of its channel, back into the server's default one. */ - public void kickFromChannel(int clientId, String reason) { - kick(clientId, REASON_KICK_CHANNEL, reason, "Could not kick client from the channel: "); - } - - /** Kicks a client off the server entirely. */ - public void kickFromServer(int clientId, String reason) { - kick(clientId, REASON_KICK_SERVER, reason, "Could not kick client from the server: "); - } - - private void kick(int clientId, int reasonId, String reason, String errorPrefix) { - act(errorPrefix, sock -> { - SingleCommand cmd = new SingleCommand("clientkick", ProtocolRole.CLIENT); - cmd.add(new CommandSingleParameter("clid", Integer.toString(clientId))); - cmd.add(new CommandSingleParameter("reasonid", Integer.toString(reasonId))); - if (reason != null && !reason.isEmpty()) { - cmd.add(new CommandSingleParameter("reasonmsg", reason)); - } - sock.executeCommand(cmd).complete(); - }); - } - - /** - * Bans a client from the server. - * - * @param seconds how long the ban lasts, or 0 for a permanent one - */ - public void banClient(int clientId, long seconds, String reason) { - act("Could not ban client: ", sock -> sock.banClient(clientId, - seconds <= 0 ? null : (int) Math.min(seconds, Integer.MAX_VALUE), - reason == null || reason.isEmpty() ? null : reason)); - } - - /** - * Re-parents and repositions a channel. - * - * @param orderPredecessorId the channel this one should sit below among its new - * siblings, or 0 to place it first - */ - public void moveChannel(int channelId, int newParentId, int orderPredecessorId) { - ChannelNode channel = model.getChannel(channelId); - // The server refuses channelmove within the same parent ("already member of - // channel"); sorting among the same siblings is an edit of channel_order. - boolean reorder = channel != null && channel.parentId == newParentId; - act("Could not move channel: ", sock -> { - SingleCommand cmd; - if (reorder) { - cmd = new SingleCommand("channeledit", ProtocolRole.CLIENT); - cmd.add(new CommandSingleParameter("cid", Integer.toString(channelId))); - cmd.add(new CommandSingleParameter("channel_order", Integer.toString(orderPredecessorId))); - } else { - cmd = new SingleCommand("channelmove", ProtocolRole.CLIENT); - cmd.add(new CommandSingleParameter("cid", Integer.toString(channelId))); - cmd.add(new CommandSingleParameter("cpid", Integer.toString(newParentId))); - cmd.add(new CommandSingleParameter("order", Integer.toString(orderPredecessorId))); - } - sock.executeCommand(cmd).complete(); - }); - } - - /** - * Asks the server to (re-)send its permission definitions, which arrive as a burst - * of {@code notifypermissionlist} events — the only way to learn permission names, - * since {@code notifyclientneededpermissions} (which resolves our own power for - * them) only ever reports numeric ids. Needed for {@link ServerModel#selfPermissionValue} - * to work; harmless if it's slow or fails, since group-assignment eligibility just - * won't be known yet. - */ - private void requestPermissionNames() { - // Best-effort: the menus fall back to treating unresolved permissions as 0. - attempt(sock -> sock.executeCommand(new SingleCommand("permissionlist", ProtocolRole.CLIENT)).complete()); - } - - /** - * Asks for our own {@link ServerModel#UNREPORTED_PERMISSIONS}, which {@code notifyclientneededpermissions} - * never carries. Asking needs {@code b_client_permissionoverview_own}; refused, we take them - * as none, which is what the groups that lack the one usually have of the others. - */ - void requestSelfPowers() { - List rows = new ArrayList<>(); - for (String name : ServerModel.UNREPORTED_PERMISSIONS) { - rows.add(new SingleCommand("permget", ProtocolRole.CLIENT, new CommandSingleParameter("permsid", name))); - } - submit(sock -> { - Map powers = new HashMap<>(); - for (SingleCommand answer : sock.executeCommand(new MultiCommand("permget", ProtocolRole.CLIENT, rows)).get()) { - Map fields = answer.toMap(); - String name = fields.get("permsid"); - String value = fields.get("permvalue"); - if (name != null && value != null) powers.put(name, Integer.parseInt(value)); - } - model.setUnreportedPermissions(powers); - }, e -> model.setUnreportedPermissions(Map.of())); - } - - /** Assigns or removes a server group for a client (by database id, as {@code servergroupaddclient} needs). */ - public void setClientServerGroup(int clientDatabaseId, int groupId, boolean assign) { - act("Could not " + (assign ? "assign" : "remove") + " server group: ", sock -> { - if (assign) sock.serverGroupAddClient(groupId, clientDatabaseId); - else sock.serverGroupRemoveClient(groupId, clientDatabaseId); - }); - } - - /** Assigns a channel group for a client in the channel it currently sits in. */ - public void setClientChannelGroup(int clientDatabaseId, int channelId, int groupId) { - act("Could not set channel group: ", sock -> { - SingleCommand cmd = new SingleCommand("setclientchannelgroup", ProtocolRole.CLIENT); - cmd.add(new CommandSingleParameter("cgid", Integer.toString(groupId))); - cmd.add(new CommandSingleParameter("cid", Integer.toString(channelId))); - cmd.add(new CommandSingleParameter("cldbid", Integer.toString(clientDatabaseId))); - sock.executeCommand(cmd).complete(); - }); - } - - /** - * Subscribes to (or unsubscribes from) a set of channels in one command. The model - * is left alone: the server answers with the subscription events that update it. - */ - public void setChannelsSubscribed(Collection channelIds, boolean subscribed) { - if (channelIds.isEmpty()) return; - List ids = List.copyOf(channelIds); - String name = subscribed ? "channelsubscribe" : "channelunsubscribe"; - act(subscribed ? "Could not subscribe: " : "Could not unsubscribe: ", sock -> { - List parts = new ArrayList<>(ids.size()); - for (int id : ids) { - parts.add(new SingleCommand(name, ProtocolRole.CLIENT, - new CommandSingleParameter("cid", Integer.toString(id)))); - } - sock.executeCommand(new MultiCommand(name, ProtocolRole.CLIENT, parts)).complete(); - }); - } - - public void sendChannelMessage(String text) { - act("Message failed: ", sock -> { - ClientEntry self = model.getClient(selfClientId); - int cid = self != null ? self.channelId : 0; - sock.sendChannelMessage(cid, text); - persistOutgoingChat(ConnectionListener.ChatScope.CHANNEL, 0, "", text); - sound(SoundEvent.CHAT_SENT_MESSAGE_CHANNEL, channelVars(cid, null)); - }); - } - - public void sendServerMessage(String text) { - act("Message failed: ", sock -> { - sock.sendServerMessage(text); - persistOutgoingChat(ConnectionListener.ChatScope.SERVER, 0, "", text); - sound(SoundEvent.CHAT_SENT_MESSAGE_SERVER, serverVars()); - }); - } - - public void sendPrivateMessage(int clientId, String text) { - act("Message failed: ", sock -> { - sock.sendPrivateMessage(clientId, text); - ClientEntry peer = model.getClient(clientId); - String peerUid = peer != null ? peer.uniqueId : ""; - if (peerUid == null || peerUid.isBlank()) { - try { - Client info = sock.getClientInfo(clientId); - if (info != null) peerUid = info.getUniqueIdentifier(); - } catch (Exception ignored) { - } - } - persistOutgoingChat(ConnectionListener.ChatScope.PRIVATE, clientId, peerUid, text); - sound(SoundEvent.CHAT_SENT_MESSAGE_CLIENT, clientVars(clientId, null)); - }); - } - - public void poke(int clientId, String message) { - act("Poke failed: ", sock -> { - sock.clientPoke(clientId, message); - sound(SoundEvent.OTHER_SENT_POKE, clientVars(clientId, null)); - }); - } - - public void setAway(boolean away, String message) { - sound(away ? SoundEvent.STATUS_SET_AWAY : SoundEvent.STATUS_SET_PRESENT); - updateSelf(self -> { - self.away = away; - self.awayMessage = away && message != null ? message : ""; - }); - selfUpdate(cmd -> { - cmd.add(new CommandSingleParameter("client_away", away ? "1" : "0")); - cmd.add(new CommandSingleParameter("client_away_message", away && message != null ? message : "")); - }, "Away update failed"); - } - - public void setChannelCommander(boolean commander) { - updateSelf(self -> self.channelCommander = commander); - selfUpdate(cmd -> - cmd.add(new CommandSingleParameter("client_is_channel_commander", commander ? "1" : "0")), - "Channel commander update failed"); - } - - /** @param message the reason shown to moderators; ignored when withdrawing the request */ - public void setTalkRequest(boolean request, String message) { - updateSelf(self -> self.talkRequest = request); - selfUpdate(cmd -> { - cmd.add(new CommandSingleParameter("client_talk_request", request ? "1" : "0")); - if (request) cmd.add(new CommandSingleParameter("client_talk_request_msg", message)); - }, "Talk power request failed"); - } - - public void setPhoneticNickname(String phoneticNickname) { - updateSelf(self -> self.phoneticNickname = phoneticNickname); - selfUpdate(cmd -> cmd.add(new CommandSingleParameter("client_nickname_phonetic", phoneticNickname)), - "Setting phonetic nickname failed"); - } - - // ---- recording ---- - - /** - * Starts recording what we hear on this server, our own voice included, and tells the - * server so: other clients see that they are being recorded. - */ - public synchronized VoiceRecorder startRecording(VoiceRecorder.Mode mode, Path file) throws IOException { - VoiceOutput out = playback; - VoiceInput mic = microphone; - if (!connected || out == null || mic == null) throw new IllegalStateException("Not connected"); - if (recorder != null) throw new IllegalStateException("Already recording"); - - Map names = new HashMap<>(); - for (ClientEntry c : model.allClients()) { - if (!c.uniqueId.isEmpty()) names.putIfAbsent(c.uniqueId, c.nickname); - } - VoiceRecorder rec = VoiceRecorder.start(mode, file, audio.opus(), names); - recorder = rec; - out.setVoiceTap((clientId, pcm, frames) -> { - ClientEntry c = model.getClient(clientId); - if (c != null) rec.offer(c.uniqueId, c.nickname, pcm, 1, frames); - }); - mic.setMonitorListener((pcm, channels) -> { - ClientEntry self = model.getClient(selfClientId); - if (self != null) rec.offer(getSelfUniqueId(), self.nickname, pcm, channels, pcm.length / channels); - }); - // A recording that fails to write ends by itself. - rec.whenDone().whenComplete((files, error) -> { - if (error != null) end(rec, true); - }); - publishRecording(true); - return rec; - } - - /** - * Stops the recording, if any; its files are finished in the background. - * - * @return the recording's files once written, or null if nothing was recording - */ - public CompletableFuture> stopRecording() { - return stopRecording(true); - } - - /** @param announce whether to tell the server; pointless when about to leave it */ - public CompletableFuture> stopRecording(boolean announce) { - VoiceRecorder rec = getRecorder(); - return rec != null && end(rec, announce) ? rec.stop() : null; - } - - /** Ends {@code rec} if it is still the one recording. */ - private boolean end(VoiceRecorder rec, boolean announce) { - synchronized (this) { - if (recorder != rec) return false; - detachRecorder(); - } - if (announce && connected) publishRecording(false); - return true; - } - - public synchronized VoiceRecorder getRecorder() { - return recorder; - } - - private synchronized void detachRecorder() { - recorder = null; - VoiceOutput out = playback; - VoiceInput mic = microphone; - if (out != null) out.setVoiceTap(null); - if (mic != null) mic.setMonitorListener(null); - } - - private void publishRecording(boolean recording) { - selfUpdate(cmd -> cmd.add(new CommandSingleParameter("client_is_recording", recording ? "1" : "0")), - "Recording status update failed"); - } - - /** - * Applies a change of our own state to the local model. The server sends - * {@code notifyclientupdated} to the other clients only, so without this - * our own row would keep its old icons until something else refreshed it. - */ - private void updateSelf(java.util.function.Consumer change) { - ClientEntry self = model.getClient(selfClientId); - if (self == null) return; - change.accept(self); - ui.onModelChanged(); - } - - /** Sends a {@code clientupdate} for the local client in the background. */ - private void selfUpdate(java.util.function.Consumer fill, String errorLabel) { - act(errorLabel + ": ", sock -> { - SingleCommand cmd = new SingleCommand("clientupdate", ProtocolRole.CLIENT); - fill.accept(cmd); - sock.executeCommand(cmd).complete(); - }); - } - - public double getPingMillis() { - try { - LocalTeamspeakClientSocket sock = client; - return sock != null ? sock.getPing().getKey() * 1000.0 : -1; - } catch (Exception e) { - return -1; - } - } - - public void setNickname(String nickname) { - act("Rename failed: ", sock -> sock.setNickname(nickname)); - } - - /* - * Info lookups use the commands the official client does. channelinfo/clientinfo would - * answer directly, but they are query commands that count heavily against the server's - * flood protection: clicking through the tree gets every command refused within seconds. - */ - - /** - * Asks for a channel's description. The answer arrives as a channel edit, see - * {@link ConnectionEventHandler#onChannelEdit}. - */ - public void requestChannelInfo(int channelId) { - requestInfo("channelgetdescription", "cid", channelId); - } - - /** - * Asks for a client's version and platform, the only details the enter-view event - * lacks. The answer arrives as a client update, see {@link ConnectionEventHandler#onClientChanged}. - */ - public void requestClientInfo(int clientId) { - requestInfo("clientgetvariables", "clid", clientId); - } - - /** May be refused for lack of permission; the details then stay as they are. */ - private void requestInfo(String command, String idParameter, int id) { - attempt(sock -> sock.executeCommand(new SingleCommand(command, ProtocolRole.CLIENT, - new CommandSingleParameter(idParameter, Integer.toString(id)))).complete()); - } - - /** - * Reads a client's description straight from the server, so an editor opens on the - * live text instead of whatever an earlier info request cached. - */ - public void requestClientDescription(int clientId, BiConsumer callback) { - run(callback, () -> { - Client c = socket().getClientInfo(clientId); - String description = c == null ? "" : orEmpty(c.get("client_description")); - ClientEntry e = model.getClient(clientId); - if (e != null) e.description = description; - return description; - }); - } - - /** - * Changes a client's description. Unlike the nickname or the away state, this is not - * a {@code clientupdate} property even for ourselves: the server only takes it - * through {@code clientedit}, gated by {@code b_client_modify_own_description}. - * - * @param callback given {@code null} on success, or the failure message - */ - public void setClientDescription(int clientId, String description, Consumer callback) { - boolean self = clientId == selfClientId; - run((ignored, error) -> callback.accept(error), () -> { - SingleCommand cmd = new SingleCommand("clientedit", ProtocolRole.CLIENT); - cmd.add(new CommandSingleParameter("clid", Integer.toString(clientId))); - cmd.add(new CommandSingleParameter("client_description", description)); - socket().executeCommand(cmd).complete(); - // Only the other clients are told about our own update, so the local entry - // (and the info panel showing it) has to be caught up here. - if (self) { - ClientEntry e = model.getClient(clientId); - if (e != null) e.description = description; - ui.onInfoUpdated(); - } - return null; - }); - } - - // ---- privilege keys ---- - - /** Reads the server's privilege keys, delivering them (or a failure message) off the UI thread. */ - public void requestPrivilegeKeys(BiConsumer, String> callback) { - run(callback, privilegeKeys::list); - } - - /** - * Creates a privilege key for a server group, or for a channel group in {@code channelId}. - * - * @param callback given the new key, or the failure message - */ - public void addPrivilegeKey(boolean channelGroup, int groupId, int channelId, String description, - BiConsumer callback) { - run(callback, () -> privilegeKeys.add(channelGroup, groupId, channelId, description)); - } - - /** - * Deletes privilege keys one by one, stopping at the first the server refuses. - * - * @param callback given {@code null} on success, or the failure message - */ - public void deletePrivilegeKeys(Collection tokens, Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { - for (String token : tokens) privilegeKeys.delete(token); - return null; - }); - } - - /** @param callback given {@code null} on success, or the failure message */ - public void usePrivilegeKey(String token, Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { - privilegeKeys.use(token); - return null; - }); - } - - // ---- complaints ---- - - /** Complains about an online client to the server's admins. */ - public void complain(ClientEntry client, String reason) { - act("Failed to send complaint: ", sock -> { - complaints.add(client.databaseId, reason); - log("Complaint sent."); - }); - } - - /** Reads the server's complaints, delivering them (or a failure message) off the UI thread. */ - public void requestComplaints(BiConsumer, String> callback) { - run(callback, complaints::list); - } - - /** - * Removes every complaint about each of {@code targetDbIds}, then each of {@code single}, - * stopping at the first the server refuses. - * - * @param callback given {@code null} on success, or the failure message - */ - public void deleteComplaints(Collection targetDbIds, Collection single, - Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { - for (int target : targetDbIds) complaints.deleteAll(target); - for (Complaint complaint : single) complaints.delete(complaint); - return null; - }); - } - - // ---- offline messages ---- - - /** Unread messages in our offline message inbox on this server. */ - public int unreadOfflineMessages() { - ClientEntry self = model.getClient(selfClientId); - return self == null ? 0 : self.unreadMessages; - } - - /** Whether the server lets us send offline messages. */ - public boolean canSendOfflineMessages() { - return model.permits("b_client_offline_textmessage_send"); - } - - /** Our unread count changed from {@code before}; more unread means new mail, which the log announces. */ - void unreadMessagesChanged(int before) { - int unread = unreadOfflineMessages(); - if (unread > before) { - String count = unread == 1 ? "1 unread offline message" : unread + " unread offline messages"; - log("You have " + TsLink.offlineMessagesBBCode(count)); - } - ui.onUnreadMessagesChanged(unread); - } - - /** Lists our offline message inbox, delivering it (or a failure message) off the UI thread. */ - public void requestOfflineMessages(BiConsumer, String> callback) { - run(callback, offlineMessages::list); - } - - /** Reads a message's body, delivering it (or a failure message) off the UI thread. */ - public void requestOfflineMessageBody(int messageId, BiConsumer callback) { - run(callback, () -> offlineMessages.body(messageId)); - } - - /** - * Marks messages read or unread, stopping at the first the server refuses. - * - * @param callback given {@code null} on success, or the failure message - */ - public void markOfflineMessages(Collection messageIds, boolean read, Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { - for (int id : messageIds) offlineMessages.setRead(id, read); - return null; - }); - } - - /** @param callback given {@code null} on success, or the failure message */ - public void deleteOfflineMessages(Collection messageIds, Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { - for (int id : messageIds) offlineMessages.delete(id); - return null; - }); - } - - /** - * Sends one offline message to each recipient, stopping at the first the server refuses. - * - * @param callback given {@code null} on success, or the failure message - */ - public void sendOfflineMessage(Collection recipientUids, String subject, String message, - Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { - for (String uid : recipientUids) offlineMessages.send(uid, subject, message); - log("Offline message sent."); - return null; - }); - } - - /** Looks a client up by unique id; delivers {@code null} when the server has never seen them. */ - public void lookupDatabaseClient(String uniqueId, BiConsumer callback) { - run(callback, () -> offlineMessages.lookupUid(uniqueId)); - } - - /** - * Finds clients whose last nickname contains {@code nickname}. - * - * @param callback given the matches, or {@link #SEARCH_NOT_PERMITTED} or another failure message - */ - public void searchDatabaseClients(String nickname, BiConsumer, String> callback) { - run(callback, () -> { - try { - return offlineMessages.search(nickname); - } catch (CommandException e) { - if (isPermissionError(e)) throw new IllegalStateException(SEARCH_NOT_PERMITTED); - throw e; - } - }); - } - - // ---- server log ---- - - /** - * Reads the server's newest log lines, or with {@code olderFrom} > 0 the ones before an - * earlier page's, delivering them (or a failure message) off the UI thread. - */ - public void requestServerLog(long olderFrom, BiConsumer callback) { - run(callback, () -> serverLog.read(olderFrom)); - } - - // ---- bans ---- - - /** Reads the server's ban list, delivering it (or a failure message) off the UI thread. */ - public void requestBanList(BiConsumer, String> callback) { - run(callback, bans::list); - } - - /** @param callback given {@code null} on success, or the failure message */ - public void addBan(BanRule rule, Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { - bans.add(rule); - return null; - }); - } - - /** - * Rewrites an existing ban. - * - * @param callback given {@code null} on success, or the failure message - */ - public void replaceBan(int banId, BanRule rule, Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { - bans.replace(banId, rule); - return null; - }); - } - - /** - * Deletes bans one by one, stopping at the first the server refuses. - * - * @param callback given {@code null} on success, or the failure message - */ - public void deleteBans(Collection banIds, Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { - for (int id : banIds) bans.delete(id); - return null; - }); - } - - /** - * Our own unique identifier on this server, which is how the server names us as a - * ban's creator; empty while not connected. - */ - // ---- contacts ---- - - public ContactStore getContacts() { - return contacts; - } - - /** The name a client is shown under: its contact's custom name where it has one. */ - public String displayName(ClientEntry client) { - return contacts.displayName(client.uniqueId, client.nickname); - } - - /** - * Whether a whisper from a client is played, per the global whisper policy and the - * client's contact entry. A client that has already left is judged by the policy alone. - */ - boolean isWhisperAllowed(int clientId) { - Settings.WhisperPolicy policy = settings.whisperPolicy; - if (policy == Settings.WhisperPolicy.NOBODY) return false; - ClientEntry c = model.getClient(clientId); - Contact contact = c == null ? null : contacts.find(c.uniqueId); - if (contact != null) return contact.whisperAllowed; - return policy == Settings.WhisperPolicy.ALLOW_UNLESS_DENIED; - } - - /** - * Applies a client's contact entry to its playback — the automatic mute and the - * volume modifier — and records the sighting. Called when the client appears. - */ - void applyContact(ClientEntry client) { - Contact contact = applyContactPlayback(client); - if (contact != null) contacts.markSeen(client.uniqueId, model.getServerName(), serverHost + ":" + serverPort); - } - - private Contact applyContactPlayback(ClientEntry client) { - if (client == null || client.self) return null; - Contact contact = contacts.find(client.uniqueId); - VoiceOutput out = playback; - if (contact != null && out != null) { - if (contact.automute) out.setClientMuted(client.id, true); - out.setClientVolume(client.id, contact.volumeGain()); - } - return contact; - } - - /** - * Re-applies every contact entry to the clients on the server, after the list changed. - * A client that just became a contact is also marked as seen. One seen before keeps - * where it was seen: with it on two servers, each re-application would claim it for its - * own server, which is a change that triggers the other's re-application, and so on. - */ - public void applyContacts() { - if (!connected) return; - for (ClientEntry c : model.allClients()) { - Contact contact = applyContactPlayback(c); - if (contact != null && contact.lastSeen == null) { - contacts.markSeen(c.uniqueId, model.getServerName(), serverHost + ":" + serverPort); - } - } - } - - /** Remembers a per-client volume, in the contact entry when the client has one. */ - public void setClientVolumeModifier(ClientEntry client, double decibels) { - VoiceOutput out = playback; - if (out != null) out.setClientVolume(client.id, Math.pow(10.0, decibels / 20.0)); - Contact contact = contacts.find(client.uniqueId); - if (contact == null) return; - contact.hasVolumeModifier = decibels != 0; - contact.volumeModifier = decibels; - contacts.put(contact); - } - - public double getClientVolumeModifier(ClientEntry client) { - VoiceOutput out = playback; - if (out == null) return 0; - double gain = out.getClientVolume(client.id); - return gain <= 0 ? -60 : 20.0 * Math.log10(gain); - } - - public String getSelfUniqueId() { - ClientEntry self = model.getClient(selfClientId); - if (self != null && !self.uniqueId.isEmpty()) return self.uniqueId; - LocalIdentity id = identity; - return id == null ? "" : id.getUid().toBase64(); - } - - // ---- channel administration ---- - - /** - * Reads a channel's editable properties, delivering them (or a failure message) to - * {@code callback} off the UI thread. - */ - public void requestChannelSettings(int channelId, BiConsumer callback) { - run(callback, () -> channels.readSettings(channelId)); - } - - /** - * Reads the permissions set directly on a channel, as name/value pairs. Fails when the - * server does not let us look at them. - */ - public void requestChannelPermissions(int channelId, - BiConsumer, String> callback) { - run(callback, () -> channels.readPermissions(channelId)); - } - - /** - * Applies an edited channel: its changed properties first, then its needed-power - * permissions. - * - * @param callback given {@code null} on success, or the failure message - */ - public void applyChannelEdit(int channelId, Map changes, - Map setPermissions, - Collection removePermissions, - Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { - channels.edit(channelId, changes); - channels.writePermissions(channelId, setPermissions, removePermissions); - if (changes.containsKey("channel_description")) { - ChannelNode node = model.getChannel(channelId); - // the server does not notify the invoker of their own description change - if (node != null && node.descriptionLoaded) { - node.descriptionLoaded = false; - requestChannelInfo(channelId); - } - } - return null; - }); - } - - /** - * Creates a channel below {@code parentId} (0 being the top level) and gives it the - * channel permissions it was created with. - * - * @param callback given the new channel's id, or the failure message. A channel whose - * permissions could not be set still exists, and is reported as an error - * saying so. - */ - public void createChannel(int parentId, Map properties, - Map permissions, - BiConsumer callback) { - run(callback, () -> { - int channelId = channels.create(parentId, properties); - try { - channels.writePermissions(channelId, permissions, List.of()); - } catch (Exception e) { - throw new IllegalStateException("The channel was created, but its permissions" - + " could not be set: " + rootMessage(e)); - } - return channelId; - }); - } - - /** - * Deletes a channel; with {@code force}, also one that has sub-channels or clients in it. - * - * @param callback given {@code null} on success, or the failure message - */ - public void deleteChannel(int channelId, boolean force, Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { - channels.delete(channelId, force); - return null; - }); - } - - /** The ids of the icons uploaded to this virtual server. */ - public void requestServerIcons(BiConsumer, String> callback) { - run(callback, channels::listIcons); - } - - /** Uploads an image as a server icon and reports the new icon's id. */ - public void uploadIcon(File source, BiConsumer callback) { - run(callback, () -> channels.uploadIcon(source)); - } - - /** Deletes a server icon; {@code callback} is given {@code null} on success. */ - public void deleteIcon(long iconId, Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { - channels.deleteIcon(iconId); - return null; - }); - } - - /** A request made on the socket of the connection it was issued on. */ - private interface Action { - void run(LocalTeamspeakClientSocket sock) throws Exception; - } - - /** Work that produces a value or an error message. */ - private interface Job { - T call() throws Exception; - } - - /** Sends a request in the background, reporting a failure as {@code errorPrefix} and the reason. */ - private void act(String errorPrefix, Action action) { - submit(action, e -> error(errorPrefix, e)); - } - - /** Sends a request in the background whose failure nobody needs to hear about. */ - private void attempt(Action action) { - submit(action, e -> { - }); - } - - private void submit(Action action, Consumer onFailure) { - LocalTeamspeakClientSocket sock = client; - ExecutorService pool = actions; - if (sock == null || pool == null || !connected) return; - try { - pool.execute(() -> { - try { - action.run(sock); - } catch (Exception e) { - // Leaving fails whatever was still in flight; that is no error to report. - if (client == sock && connected) onFailure.accept(e); - } - }); - } catch (RejectedExecutionException ignored) { - // disconnected in the meantime - } - } - - /** - * Runs a blocking server request in the background and hands the result — or the - * failure message — to {@code callback}, which therefore never runs on the UI thread. - */ - private void run(BiConsumer callback, Job job) { - ExecutorService pool = actions; - if (pool == null || client == null || !connected) { - callback.accept(null, "Not connected"); - return; - } - try { - pool.execute(() -> { - try { - callback.accept(job.call(), null); - } catch (Exception e) { - callback.accept(null, connected ? rootMessage(e) : "Not connected"); - } - }); - } catch (RejectedExecutionException e) { - callback.accept(null, "Not connected"); - } - } - - /** The live socket. Package-private for {@link ChannelAdmin}. */ - LocalTeamspeakClientSocket socket() { - LocalTeamspeakClientSocket sock = client; - if (sock == null || !connected) throw new IllegalStateException("Not connected"); - return sock; - } - - /** Package-private for {@link ChannelAdmin} and {@link ConnectionStatsCollector}. */ - FileTransferManager fileTransfers() { - return fileTransfers; - } - - /** - * Blocks until ts3j has finished dispatching every event it had already queued, so a - * caller that just saw a command complete can be sure the notifications the server sent - * alongside it have been handled. Must not be called from the event thread itself. - */ - void awaitEventsProcessed() { - ExecutorService events = eventExecutor; - if (events == null) return; - try { - events.submit(() -> { - }).get(5, TimeUnit.SECONDS); - } catch (Exception ignored) { - // A shutting-down or wedged event thread just means the caller gets what arrived. - } - } - - // ---- icons ---- - - /** Group icons for this server: bundled defaults plus the server's own uploads. */ - public IconRepository getIcons() { - return icons; - } - - /** Reads an icon out of the virtual server's file repository (channel 0). */ - private byte[] fetchIcon(long iconId) throws Exception { - FileTransferManager ft = fileTransfers; - if (ft == null) throw new IllegalStateException("Not connected"); - return ft.downloadToMemory(0, "", "/icon_" + iconId, MAX_ICON_BYTES); - } - - // ---- avatars ---- - - /** Client avatars for this server, downloaded on demand. */ - public AvatarRepository getAvatars() { - return avatars; - } - - /** The avatar a client currently shows, or {@code null} if none or not yet available. */ - public Avatar avatarOf(ClientEntry client) { - return client == null ? null : avatars.get(client.uniqueId, client.avatarFlag); - } - - /** How large an avatar this server lets us upload, in bytes. */ - public int maxAvatarBytes() { - return avatarAdmin.maxUploadBytes(); - } - - /** - * Uploads an image as our avatar and publishes it to the other clients. - * - * @param callback given {@code null} on success, or the failure message - */ - public void setAvatar(File source, Consumer callback) { - run((flag, error) -> { - if (error == null) updateSelf(self -> self.avatarFlag = flag); - callback.accept(error); - }, () -> avatarAdmin.upload(source)); - } - - /** Withdraws our avatar; {@code callback} is given {@code null} on success. */ - public void removeAvatar(Consumer callback) { - run((ignored, error) -> { - if (error == null) updateSelf(self -> self.avatarFlag = ""); - callback.accept(error); - }, () -> { - avatarAdmin.remove(); - return null; - }); - } - - /** Deletes another client's avatar; {@code callback} is given {@code null} on success. */ - public void removeAvatarOf(ClientEntry client, Consumer callback) { - run((ignored, error) -> callback.accept(error), () -> { - avatarAdmin.removeOther(client.uniqueId); - return null; - }); - } - - /** Reads a client's avatar out of the virtual server's file repository (channel 0). */ - private byte[] fetchAvatar(String uniqueId) throws Exception { - FileTransferManager ft = fileTransfers; - if (ft == null) throw new IllegalStateException("Not connected"); - String name = AvatarNaming.fileName(uniqueId); - if (name == null) throw new IllegalArgumentException("Not a client unique id: " + uniqueId); - return ft.downloadToMemory(0, "", "/" + name, AvatarAdmin.MAX_AVATAR_DOWNLOAD_BYTES); - } - - // ---- whisper ---- - - /** Sends the microphone's voice to {@code targets} as a whisper, or to our channel again with null. */ - public void setWhisperTargets(Whisper.Targets targets) { - LocalTeamspeakClientSocket sock = client; - if (sock == null) return; - if (targets == null) { - sock.setWhisperTarget(null); - return; - } - PacketBody1VoiceWhisper.WhisperTargetMultiple target = new PacketBody1VoiceWhisper.WhisperTargetMultiple(); - target.setChannelIds(targets.channelIds()); - target.setClientIds(targets.clientIds()); - sock.setWhisperTarget(target); - } - - /** The client who whispered to us last, if still on the server. */ - public ClientEntry lastWhisperer() { - int id = lastWhisperer; - return id == 0 ? null : model.getClient(id); - } - - // ---- file transfers ---- - - /** Whether a live connection capable of file transfers is available. */ - public boolean canTransferFiles() { - return connected && fileTransfers != null; - } - - /** - * Lists the files under {@code path} in a channel's repository. Blocking; call - * off the UI thread. Throws if not connected or the server denies the request. - */ - public java.util.List listFiles(int channelId, String channelPassword, String path) - throws Exception { - FileTransferManager ft = fileTransfers; - if (ft == null) throw new IllegalStateException("Not connected"); - return ft.list(channelId, channelPassword, path); - } - - public void createDirectory(int channelId, String channelPassword, String dirPath) throws Exception { - FileTransferManager ft = fileTransfers; - if (ft == null) throw new IllegalStateException("Not connected"); - ft.createDirectory(channelId, channelPassword, dirPath); - } - - public void deleteFile(int channelId, String channelPassword, String fullPath) throws Exception { - FileTransferManager ft = fileTransfers; - if (ft == null) throw new IllegalStateException("Not connected"); - ft.delete(channelId, channelPassword, fullPath); - } - - public void renameFile(int channelId, String channelPassword, String oldFullPath, String newFullPath) - throws Exception { - FileTransferManager ft = fileTransfers; - if (ft == null) throw new IllegalStateException("Not connected"); - ft.rename(channelId, channelPassword, oldFullPath, newFullPath); - } - - /** Begins downloading a channel file to {@code target}; progress arrives via {@code listener}. */ - public FileTransfer downloadFile(int channelId, String channelPassword, String remoteFullPath, - File target, FileTransfer.Listener listener) { - FileTransferManager ft = fileTransfers; - if (ft == null) throw new IllegalStateException("Not connected"); - return ft.download(channelId, channelPassword, remoteFullPath, target, announcing(listener)); - } - - /** Begins uploading {@code source} into a channel; progress arrives via {@code listener}. */ - public FileTransfer uploadFile(int channelId, String channelPassword, String remoteFullPath, - File source, boolean overwrite, FileTransfer.Listener listener) { - FileTransferManager ft = fileTransfers; - if (ft == null) throw new IllegalStateException("Not connected"); - return ft.upload(channelId, channelPassword, remoteFullPath, source, overwrite, announcing(listener)); - } - - /** - * Wraps a transfer listener so the completion and failure sounds play once the - * transfer finishes, whoever is watching it. - */ - private FileTransfer.Listener announcing(FileTransfer.Listener listener) { - java.util.concurrent.atomic.AtomicBoolean announced = new java.util.concurrent.atomic.AtomicBoolean(); - return transfer -> { - FileTransfer.State state = transfer.getState(); - if (state != FileTransfer.State.CANCELLED && transfer.isDone() - && announced.compareAndSet(false, true)) { - sound(state == FileTransfer.State.COMPLETED - ? SoundEvent.OTHER_FILETRANSFER_COMPLETE - : SoundEvent.OTHER_FILETRANSFER_FAILED, serverVars()); - } - if (listener != null) listener.onTransferChanged(transfer); - }; - } - - // ---- connection info ---- - - /** - * Fetches connection statistics for a client and delivers them to - * {@code callback} (invoked off the Swing EDT — the callback is responsible - * for marshalling). For the local client the figures are read from the live - * local packet counters; for a remote client they are requested from the - * server via {@code getconnectioninfo}, enriched with {@code clientinfo} for - * version, platform and idle time. May be called repeatedly to poll. - */ - public void requestConnectionInfo(int clientId, Consumer callback) { - if (client == null || !connected) return; - stats.request(clientId, callback); - } - - // ---- events not handled by ConnectionEventHandler ---- - - /** - * Kept here rather than in {@link ConnectionEventHandler}: teardown needs - * {@link #safeCleanup()} and the {@code connected}/announced flags this class - * already owns, so routing it through the event handler would only add an - * extra hop back into private lifecycle state. - */ - @Override - public void onDisconnected(DisconnectedEvent e) { - connected = false; - safeCleanup(); - announceDisconnect(false); - String reason = orEmpty(e.getReasonMessage()); - ui.onDisconnected(reason); - ui.onStatus(reason.isEmpty() ? "Disconnected" : "Disconnected: " + reason); - } - - // ---- sound notifications ---- - - /** - * Plays the sound pack's entry for an action. Muting is passed along so the - * notifier can drop everything the user did not mark as important. Package-private: - * also called by {@link ConnectionEventHandler}. - */ - void sound(SoundEvent event) { - sounds.fire(event, deafened); - } - - void sound(SoundEvent event, Map variables) { - sounds.fire(event, deafened, variables); - } - - private void loadChatLogs() { - chatLogs = null; - if (!settings.chatLogs) return; - try { - String uniqueId = serverUniqueId(); - if (uniqueId == null) { - ui.onStatus("Chat logs unavailable: the server's unique id is not known"); - return; - } - String dir = settings.chatLogDir == null ? "" : settings.chatLogDir.trim(); - // Android < API 34 lacks Path.of; original: - // ChatLogStore logs = new ChatLogStore(dir.isEmpty() ? ChatLogStore.defaultRoot() : Path.of(dir), uniqueId); - ChatLogStore logs = new ChatLogStore(dir.isEmpty() ? ChatLogStore.defaultRoot() : Paths.get(dir), uniqueId); - chatLogs = logs; - logs.begin(); - List serverHistory = logs.serverHtmlHistory(); - List channelHistory = logs.channelHtmlHistory(); - ui.onChatHistory(ConnectionListener.ChatScope.SERVER, serverHistory); - ui.onChatHistory(ConnectionListener.ChatScope.CHANNEL, channelHistory); - ui.onStatus("Loaded chat logs from " + logs.serverDir() - + " (" + serverHistory.size() + " server, " + channelHistory.size() + " channel)"); - } catch (Exception e) { - chatLogs = null; - ui.onStatus("Chat logs unavailable: " + rootMessage(e)); - } - } - - /** - * The server's unique identifier, worked out from its key as TeamSpeak does (a guest is - * never told it); {@code null} before the server has introduced itself. - */ - public String serverUniqueId() { - LocalTeamspeakClientSocket client = this.client; - if (client == null) return null; - Uid uid = client.getServerUid(); - return uid == null ? null : uid.toBase64(); - } - - public void loadPrivateChatHistory(int clientId, String uniqueId) { - ChatLogStore logs = chatLogs; - if (logs == null || uniqueId == null || uniqueId.isBlank()) return; - try { - ClientEntry c = model.getClient(clientId); - ui.onPrivateChatHistory(clientId, c != null ? c.nickname : "Client " + clientId, - logs.privateHtmlHistory(uniqueId)); - } catch (IOException e) { - ui.onStatus("Private chat log unavailable: " + rootMessage(e)); - } - } - - void persistIncomingChat(ConnectionListener.ChatScope scope, int fromClientId, String fromUniqueId, - String fromName, String message) { - ChatLogStore logs = chatLogs; - if (logs == null) return; - try { - logs.appendMessage(toLogScope(scope), false, fromClientId, fromUniqueId, fromName, message); - } catch (IOException e) { - ui.onStatus("Could not write chat log: " + rootMessage(e)); - } - } - - private void persistOutgoingChat(ConnectionListener.ChatScope scope, int peerClientId, String peerUniqueId, - String message) { - ChatLogStore logs = chatLogs; - if (logs == null) return; - try { - ClientEntry self = model.getClient(selfClientId); - String uid = identity != null ? identity.getUid().toBase64() : ""; - String name = self != null ? self.nickname : settings.nickname; - if (scope == ConnectionListener.ChatScope.PRIVATE) { - if (peerUniqueId == null || peerUniqueId.isBlank()) return; - logs.appendPrivateMessage(peerUniqueId, true, selfClientId, uid, name, message); - } else { - logs.appendMessage(toLogScope(scope), true, selfClientId, uid, name, message); - } - } catch (IOException e) { - ui.onStatus("Could not write chat log: " + rootMessage(e)); - } - } - - private static ChatLogScope toLogScope(ConnectionListener.ChatScope scope) { - return switch (scope) { - case SERVER -> ChatLogScope.SERVER; - case CHANNEL -> ChatLogScope.CHANNEL; - case PRIVATE -> ChatLogScope.PRIVATE; - }; - } - - /** Records a line in the server tab's log, the way native TS3 reports server activity. */ - void log(String message) { - if (!connected) return; - ChatLogStore logs = chatLogs; - if (logs == null) { - ui.onServerLog(message); - return; - } - try { - ui.onServerLogHtml(logs.appendServerEvent(message)); - } catch (IOException e) { - ui.onServerLog(message); - ui.onStatus("Could not write server log: " + rootMessage(e)); - } - } - - String channelName(int channelId) { - ChannelNode ch = model.getChannel(channelId); - return ch != null ? ch.name : "channel #" + channelId; - } - - /** - * A channel's name as the log wants it: TeamSpeak's own {@code channel://} link, which - * the chat log turns into the same clickable entry a dragged-in channel produces. A - * channel we no longer know (a deleted one, say) is named in plain text instead. - */ - String channelLink(int channelId) { - ChannelNode ch = model.getChannel(channelId); - return ch != null ? TsLink.channelBBCode(channelId, ch.name) : channelName(channelId); - } - - /** The same for a client, named by the model. */ - String clientLink(int clientId) { - ClientEntry c = model.getClient(clientId); - return c != null ? clientLink(clientId, c.uniqueId, c.nickname) : "Client " + clientId; - } - - /** The same for a client an event describes, which may already be gone from the model. */ - String clientLink(int clientId, String uniqueId, String nickname) { - if (clientId <= 0 || nickname == null || nickname.isEmpty()) return orEmpty(nickname); - return TsLink.clientBBCode(clientId, orEmpty(uniqueId), nickname); - } - - /** The placeholder values a pack may reference for an action involving a client. */ - Map clientVars(int clientId, String fallbackName) { - ClientEntry c = model.getClient(clientId); - Map vars = SoundNotifier.vars( - "servername", model.getServerName(), - "clientname", c != null ? c.nickname : orEmpty(fallbackName), - "clientuid", c != null ? c.uniqueId : ""); - if (c != null) { - ChannelNode ch = model.getChannel(c.channelId); - if (ch != null) vars.put("channelname", ch.name); - } - return vars; - } - - Map channelVars(int channelId, String invokerName) { - ChannelNode ch = model.getChannel(channelId); - return SoundNotifier.vars( - "servername", model.getServerName(), - "channelname", ch != null ? ch.name : "", - "clientname", orEmpty(invokerName)); - } - - Map serverVars() { - return SoundNotifier.vars("servername", model.getServerName()); - } - - /** Reports a failure to the UI and plays the matching server sound. */ - private void error(String prefix, Exception e) { - sound(isPermissionError(e) - ? SoundEvent.SERVER_INSUFFICIENT_PERMISSIONS - : SoundEvent.SERVER_ERROR, serverVars()); - ui.onError(prefix + rootMessage(e)); - } - - /** Whether the server refused for lack of permission, wherever in the cause chain it said so. */ - static boolean isPermissionError(Throwable t) { - for (Throwable c = t; c != null; c = c.getCause() == c ? null : c.getCause()) { - if (c instanceof CommandException ce) { - int id = ce.getErrorId(); - return id == ERROR_PERMISSIONS_CLIENT_INSUFFICIENT - || id == ERROR_PERMISSIONS_INSUFFICIENT_GROUP_POWER - || id == ERROR_PERMISSIONS_INSUFFICIENT_PERMISSION_POWER; - } - } - return false; - } - - /** Whether the client is in the channel we are in ourselves. Package-private: also - * used by {@link ConnectionEventHandler}. */ - boolean inOwnChannel(int channelId) { - ClientEntry self = model.getClient(selfClientId); - return self != null && self.channelId == channelId; - } - - // ---- helpers ---- - - /** Package-private: also used by {@link ConnectionEventHandler}. */ - static long safeLong(BaseEvent e, String key) { - return safeLong(e.get(key)); - } - - /** @return the parsed value, or 0 when it is absent or not a number */ - private static long safeLong(String value) { - try { - return value == null ? 0 : Long.parseLong(value.trim()); - } catch (NumberFormatException ex) { - return 0; - } - } - - /** Package-private: also used by {@link ConnectionEventHandler} and {@link ConnectionStatsCollector}. */ - static String orEmpty(String s) { - return s == null ? "" : s; - } - - /** Every message along the cause chain, outermost first: network errors are vague without context. */ - private static String messageChain(Throwable t) { - StringBuilder chain = new StringBuilder(); - for (Throwable c = t; c != null; c = c.getCause() == c ? null : c.getCause()) { - String m = c.getMessage(); - if (m == null || chain.indexOf(m) >= 0) continue; - if (chain.length() > 0) chain.append(": "); - chain.append(m); - } - return chain.length() > 0 ? chain.toString() : t.getClass().getSimpleName(); - } - - private static String rootMessage(Throwable t) { - Throwable r = t; - while (r.getCause() != null && r.getCause() != r) r = r.getCause(); - String m = r.getMessage(); - return m != null ? m : r.getClass().getSimpleName(); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/TreeMatch.java b/ts3-client/core/src/main/java/com/ts3client/net/TreeMatch.java deleted file mode 100644 index 71a61f7..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/TreeMatch.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.ts3client.net; - -import com.ts3client.text.TextQuery; - -/** What finding in the server tree matches a client or a channel on. */ -public final class TreeMatch { - - private TreeMatch() { - } - - /** A client by their nickname, or by the name the contacts give them ({@code null} for none). */ - public static boolean client(TextQuery query, String nickname, String contactName) { - return query.matches(nickname) || (contactName != null && query.matches(contactName)); - } - - /** A channel by its name; a spacer by its caption, unless that only repeats to fill the row. */ - public static boolean channel(TextQuery query, String name) { - Spacers.Spacer spacer = Spacers.parse(name); - if (spacer == null) return query.matches(name); - return spacer.align() != '*' && query.matches(spacer.caption()); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/Whisper.java b/ts3-client/core/src/main/java/com/ts3client/net/Whisper.java deleted file mode 100644 index 5818065..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/Whisper.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.ts3client.net; - -import com.ts3client.config.WhisperList; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; - -/** - * Where the microphone whispers to instead of talking in our channel: channels and clients, - * found on the server by reference so they follow renames, moves and reconnects. - */ -public final class Whisper { - - /** What the whisper is shown as: the list's, the channel's or the client's name. */ - public final String label; - /** Channel references as {@link ServerModel#findChannelByPath} reads them. */ - private final List channels; - private final List clientUniqueIds; - - private Whisper(String label, List channels, List clientUniqueIds) { - this.label = label; - this.channels = channels; - this.clientUniqueIds = clientUniqueIds; - } - - public static Whisper toChannel(ChannelNode channel) { - return new Whisper(channel.name, List.of("/" + channel.id), List.of()); - } - - public static Whisper toClient(ClientEntry client) { - return new Whisper(client.nickname, List.of(), List.of(client.uniqueId)); - } - - public static Whisper of(WhisperList list) { - List uids = new ArrayList<>(); - for (WhisperList.Client c : list.clients) uids.add(c.uniqueId()); - return new Whisper(list.name, List.copyOf(list.channels), uids); - } - - /** Who hears it on the server as it is now; what is not there is left out. */ - public Targets resolve(ServerModel model) { - Set channelIds = new LinkedHashSet<>(); - for (String ref : channels) { - ChannelNode c = model.findChannelByPath(ref); - if (c != null) channelIds.add(c.id); - } - Set clientIds = new LinkedHashSet<>(); - for (String uid : clientUniqueIds) { - ClientEntry c = model.findClientByUniqueId(uid); - if (c != null) clientIds.add(c.id); - } - return new Targets(channelIds.stream().mapToInt(Integer::intValue).toArray(), - clientIds.stream().mapToInt(Integer::intValue).toArray()); - } - - /** The channel and client ids a whisper goes to. */ - public record Targets(int[] channelIds, int[] clientIds) { - - public boolean isEmpty() { - return channelIds.length == 0 && clientIds.length == 0; - } - - @Override - public boolean equals(Object o) { - return o instanceof Targets t && Arrays.equals(channelIds, t.channelIds) && Arrays.equals(clientIds, t.clientIds); - } - - @Override - public int hashCode() { - return 31 * Arrays.hashCode(channelIds) + Arrays.hashCode(clientIds); - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/avatar/Avatar.java b/ts3-client/core/src/main/java/com/ts3client/net/avatar/Avatar.java deleted file mode 100644 index a290f5c..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/avatar/Avatar.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.ts3client.net.avatar; - -import java.io.File; - -/** - * A downloaded avatar: its bytes, container format and the on-disk copy for views that - * can only reference images by URL. - * - * @param flag the MD5 the server advertises for it ({@code client_flag_avatar}) - * @param file the cached copy, or {@code null} if the disk cache is unavailable - */ -public record Avatar(String flag, byte[] data, ImageFormat format, File file) { - - public boolean isAnimated() { - return format == ImageFormat.GIF; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/avatar/AvatarNaming.java b/ts3-client/core/src/main/java/com/ts3client/net/avatar/AvatarNaming.java deleted file mode 100644 index e8875e9..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/avatar/AvatarNaming.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.ts3client.net.avatar; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Base64; - -/** - * How TeamSpeak names and identifies avatars. - * - *

An avatar lives in the virtual server's file repository (channel 0) as - * {@code /avatar_}, where the name is the client's unique identifier — the - * base64 of a 20-byte SHA-1 — decoded and re-encoded as forty letters {@code a}–{@code p} - * (one per nibble, high nibble first). This is what the client library calls - * {@code identityStringToFilename}, recovered from the official client. - * - *

The {@code client_flag_avatar} property carries the MD5 of the file's bytes, so a - * changed avatar is detectable without re-downloading. - */ -public final class AvatarNaming { - - private static final char[] NIBBLES = "abcdefghijklmnop".toCharArray(); - - private AvatarNaming() { - } - - /** - * @return the repository file name ({@code avatar_…}) of a client's avatar, without - * the leading slash, or {@code null} if the unique id is not a valid one - */ - public static String fileName(String uniqueId) { - byte[] hash; - try { - hash = Base64.getDecoder().decode(uniqueId.trim()); - } catch (IllegalArgumentException | NullPointerException e) { - return null; - } - if (hash.length != 20) return null; - StringBuilder sb = new StringBuilder("avatar_"); - for (byte b : hash) { - sb.append(NIBBLES[(b >> 4) & 0xF]).append(NIBBLES[b & 0xF]); - } - return sb.toString(); - } - - /** The lowercase hex MD5 that TeamSpeak publishes as {@code client_flag_avatar}. */ - public static String flag(byte[] avatar) { - try { - byte[] digest = MessageDigest.getInstance("MD5").digest(avatar); - StringBuilder sb = new StringBuilder(32); - for (byte b : digest) sb.append(String.format("%02x", b)); - return sb.toString(); - } catch (NoSuchAlgorithmException e) { - throw new IllegalStateException(e); - } - } - - /** Whether the flag looks like an MD5 (the server also passes junk through unchanged). */ - public static boolean isFlag(String flag) { - if (flag == null || flag.length() != 32) return false; - for (byte c : flag.getBytes(StandardCharsets.US_ASCII)) { - boolean hex = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); - if (!hex) return false; - } - return true; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/avatar/AvatarRepository.java b/ts3-client/core/src/main/java/com/ts3client/net/avatar/AvatarRepository.java deleted file mode 100644 index 53fa3cb..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/avatar/AvatarRepository.java +++ /dev/null @@ -1,148 +0,0 @@ -package com.ts3client.net.avatar; - -import com.ts3client.config.AppDirs; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * Supplies client avatars, downloading each from the server's file repository once - * and caching it in memory and on disk. - * - *

Avatars are identified by their {@code client_flag_avatar} MD5 rather than by - * client, so a client changing their picture simply asks for a new flag, and two - * clients with the same picture share one download. A file whose MD5 does not match - * the advertised flag is discarded, as the official client does. - * - *

Lookups never block: {@link #get} returns {@code null} while an avatar is still - * being fetched and the listener is notified once it becomes available. - */ -public final class AvatarRepository { - - /** Downloads {@code /avatar_} of the given client from channel 0. */ - public interface Fetcher { - byte[] fetchAvatar(String uniqueId) throws Exception; - } - - private final Fetcher fetcher; - private final Runnable onAvatarLoaded; - private final File cacheDir; - private final Map avatars = new ConcurrentHashMap<>(); - private final Set pending = ConcurrentHashMap.newKeySet(); - private final Set failed = ConcurrentHashMap.newKeySet(); - private final ExecutorService downloads = Executors.newSingleThreadExecutor(r -> { - Thread t = new Thread(r, "ts3j-avatars"); - t.setDaemon(true); - return t; - }); - - /** - * @param onAvatarLoaded run (off the UI thread) whenever a previously missing - * avatar has arrived, so the view can repaint - */ - public AvatarRepository(Fetcher fetcher, Runnable onAvatarLoaded) { - this(fetcher, onAvatarLoaded, new File(AppDirs.profile(), "avatars")); - } - - /** @param cacheDir where downloaded avatars are kept between sessions */ - public AvatarRepository(Fetcher fetcher, Runnable onAvatarLoaded, File cacheDir) { - this.fetcher = fetcher; - this.onAvatarLoaded = onAvatarLoaded; - this.cacheDir = cacheDir; - } - - /** - * @param uniqueId the client whose avatar is wanted - * @param flag the MD5 the client currently advertises; empty means no avatar - * @return the avatar, or {@code null} if the client has none, it is still loading - * or it is unavailable. An avatar that is not cached yet starts downloading. - */ - public Avatar get(String uniqueId, String flag) { - if (!AvatarNaming.isFlag(flag)) return null; - String key = flag.toLowerCase(); - - Avatar cached = avatars.get(key); - if (cached != null) return cached; - - Avatar fromDisk = readDiskCache(key); - if (fromDisk != null) { - avatars.put(key, fromDisk); - return fromDisk; - } - if (uniqueId != null && !uniqueId.isEmpty() && !failed.contains(key) && pending.add(key)) { - downloads.execute(() -> download(uniqueId, key)); - } - return null; - } - - /** Records an avatar we just uploaded ourselves, so it shows without a round trip. */ - public Avatar put(byte[] data) { - String flag = AvatarNaming.flag(data); - Avatar avatar = new Avatar(flag, data, ImageFormat.detect(data), writeDiskCache(flag, data)); - avatars.put(flag, avatar); - failed.remove(flag); - return avatar; - } - - /** Forgets download failures so avatars can be retried on the next reconnect. */ - public void retryFailed() { - failed.clear(); - } - - public void shutdown() { - downloads.shutdownNow(); - } - - private void download(String uniqueId, String flag) { - try { - byte[] data = fetcher.fetchAvatar(uniqueId); - if (data == null || data.length == 0 || !AvatarNaming.flag(data).equals(flag)) { - failed.add(flag); - return; - } - avatars.put(flag, new Avatar(flag, data, ImageFormat.detect(data), writeDiskCache(flag, data))); - if (onAvatarLoaded != null) onAvatarLoaded.run(); - } catch (IllegalStateException e) { - // Not connected (yet); leave it retryable. - } catch (Exception e) { - // Missing or permission-denied avatars are common; don't ask again. - failed.add(flag); - } finally { - pending.remove(flag); - } - } - - private Avatar readDiskCache(String flag) { - for (ImageFormat format : ImageFormat.values()) { - File file = new File(cacheDir, flag + "." + format.extension); - if (!file.isFile()) continue; - try { - byte[] data = Files.readAllBytes(file.toPath()); - if (AvatarNaming.flag(data).equals(flag)) return new Avatar(flag, data, format, file); - } catch (IOException ignored) { - // fall through and re-download - } - } - return null; - } - - private File writeDiskCache(String flag, byte[] data) { - ImageFormat format = ImageFormat.detect(data); - if (format == null) return null; // nothing we could display later anyway - File file = new File(cacheDir, flag + "." + format.extension); - try { - //noinspection ResultOfMethodCallIgnored - cacheDir.mkdirs(); - Files.write(file.toPath(), data); - return file; - } catch (IOException e) { - return null; // the in-memory cache still serves this session - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/avatar/ImageFormat.java b/ts3-client/core/src/main/java/com/ts3client/net/avatar/ImageFormat.java deleted file mode 100644 index 77b4aed..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/avatar/ImageFormat.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.ts3client.net.avatar; - -/** The image container formats TeamSpeak accepts for avatars, told apart by their magic bytes. */ -public enum ImageFormat { - PNG("png"), JPEG("jpg"), GIF("gif"), BMP("bmp"); - - public final String extension; - - ImageFormat(String extension) { - this.extension = extension; - } - - /** @return the format of {@code data}, or {@code null} if it is none of the supported ones */ - public static ImageFormat detect(byte[] data) { - if (data == null || data.length < 6) return null; - if ((data[0] & 0xFF) == 0x89 && data[1] == 'P' && data[2] == 'N' && data[3] == 'G') return PNG; - if ((data[0] & 0xFF) == 0xFF && (data[1] & 0xFF) == 0xD8) return JPEG; - if (data[0] == 'G' && data[1] == 'I' && data[2] == 'F' && data[3] == '8') return GIF; - if (data[0] == 'B' && data[1] == 'M') return BMP; - return null; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ban/BanEntry.java b/ts3-client/core/src/main/java/com/ts3client/net/ban/BanEntry.java deleted file mode 100644 index 75d6b65..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/ban/BanEntry.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.ts3client.net.ban; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** One entry of the server's ban list, as a {@code notifybanlist} event describes it. */ -public final class BanEntry { - - public final int id; - /** The regular expression matched against a joining client's IP, or empty. */ - public final String ip; - /** The regular expression matched against a joining client's nickname, or empty. */ - public final String name; - public final String uid; - public final String mytsid; - /** The nickname the banned client last used, where the server knew one. */ - public final String lastNickname; - public final long createdEpochSeconds; - /** How long the ban lasts from its creation, or 0 when it never expires. */ - public final long durationSeconds; - public final String invokerName; - public final int invokerDatabaseId; - public final String invokerUid; - public final String reason; - /** How many connection attempts the ban has blocked so far. */ - public final int enforcements; - - public BanEntry(int id, String ip, String name, String uid, String mytsid, String lastNickname, - long createdEpochSeconds, long durationSeconds, String invokerName, - int invokerDatabaseId, String invokerUid, String reason, int enforcements) { - this.id = id; - this.ip = orEmpty(ip); - this.name = orEmpty(name); - this.uid = orEmpty(uid); - this.mytsid = orEmpty(mytsid); - this.lastNickname = orEmpty(lastNickname); - this.createdEpochSeconds = createdEpochSeconds; - this.durationSeconds = Math.max(0, durationSeconds); - this.invokerName = orEmpty(invokerName); - this.invokerDatabaseId = invokerDatabaseId; - this.invokerUid = orEmpty(invokerUid); - this.reason = orEmpty(reason); - this.enforcements = enforcements; - } - - /** Reads an entry off a {@code notifybanlist} event's fields. */ - public static BanEntry from(Map fields) { - return new BanEntry( - parseInt(fields.get("banid"), -1), - fields.get("ip"), fields.get("name"), fields.get("uid"), fields.get("mytsid"), - fields.get("lastnickname"), - parseLong(fields.get("created"), 0), parseLong(fields.get("duration"), 0), - fields.get("invokername"), parseInt(fields.get("invokercldbid"), 0), - fields.get("invokeruid"), fields.get("reason"), - parseInt(fields.get("enforcements"), 0)); - } - - public boolean isPermanent() { - return durationSeconds == 0; - } - - /** When the ban lifts, in seconds since the epoch; meaningless for a permanent one. */ - public long expiresEpochSeconds() { - return createdEpochSeconds + durationSeconds; - } - - /** Whether {@code uid} (a client's unique identifier) created this ban. */ - public boolean createdBy(String uid) { - return uid != null && !uid.isEmpty() && uid.equals(invokerUid); - } - - /** What the ban matches, as the official list sums it up: {@code name=…, ip=…, uid=… (last nickname), mytsid=…}. */ - public String targets() { - List parts = new ArrayList<>(4); - if (!name.isEmpty()) parts.add("name=" + name); - if (!ip.isEmpty()) parts.add("ip=" + ip); - if (!uid.isEmpty()) parts.add("uid=" + uid + (lastNickname.isEmpty() ? "" : " (" + lastNickname + ")")); - if (!mytsid.isEmpty()) parts.add("mytsid=" + mytsid); - return String.join(", ", parts); - } - - /** The entry's targets and settings as a rule, which is what editing starts from. */ - public BanRule toRule() { - return new BanRule(ip, name, uid, mytsid, durationSeconds, reason); - } - - private static String orEmpty(String s) { - return s == null ? "" : s; - } - - private static int parseInt(String value, int fallback) { - try { - return value == null || value.isEmpty() ? fallback : Integer.parseInt(value.trim()); - } catch (NumberFormatException e) { - return fallback; - } - } - - private static long parseLong(String value, long fallback) { - try { - return value == null || value.isEmpty() ? fallback : Long.parseLong(value.trim()); - } catch (NumberFormatException e) { - return fallback; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ban/BanPattern.java b/ts3-client/core/src/main/java/com/ts3client/net/ban/BanPattern.java deleted file mode 100644 index db5fb05..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/ban/BanPattern.java +++ /dev/null @@ -1,126 +0,0 @@ -package com.ts3client.net.ban; - -import java.util.regex.Pattern; -import java.util.regex.PatternSyntaxException; - -/** - * The notations a ban's IP and name may be typed in, and their translation to and from - * the regular expressions the server actually matches — the official client's - * "Interpret IP/Name as" choice. - * - *

A wildcard pattern is the text with {@code *} standing for a run of characters - * and everything else taken literally; a fixed string is taken literally throughout. - * In an IP a wildcard covers one address group (decimal for IPv4, hexadecimal for - * IPv6), in a name it covers anything. - */ -public enum BanPattern { - - WILDCARD_IPV4("Wildcard ipv4", "[0-9]+"), - WILDCARD_IPV6("Wildcard ipv6", "[0-9a-fA-F]+"), - FIXED_STRING("Fixed String", null), - REGULAR_EXPRESSION("Regular Expression", null); - - private static final String NAME_WILDCARD = ".*"; - private static final String META = "\\.[]{}()+?|^$*"; - - private final String label; - /** What one {@code *} in an IP stands for; {@code null} where the notation has no wildcards. */ - private final String ipWildcard; - - BanPattern(String label, String ipWildcard) { - this.label = label; - this.ipWildcard = ipWildcard; - } - - public String label() { - return label; - } - - /** The regular expression an IP written in this notation stands for. */ - public String ipToRegex(String text) { - return toRegex(text, ipWildcard); - } - - /** The regular expression a nickname written in this notation stands for. */ - public String nameToRegex(String text) { - return toRegex(text, ipWildcard == null ? null : NAME_WILDCARD); - } - - private String toRegex(String text, String wildcard) { - if (text == null) return ""; - if (this == REGULAR_EXPRESSION) return text; - StringBuilder out = new StringBuilder(text.length() + 8); - for (int i = 0; i < text.length(); i++) { - char c = text.charAt(i); - if (c == '*' && wildcard != null) out.append(wildcard); - else if (META.indexOf(c) >= 0) out.append('\\').append(c); - else out.append(c); - } - return out.toString(); - } - - /** - * Whether {@code regex} is something the server will accept as a pattern; an - * unparsable expression fails the whole {@code banadd}. - */ - public static boolean isValidRegex(String regex) { - if (regex == null || regex.isEmpty()) return true; - try { - Pattern.compile(regex); - return true; - } catch (PatternSyntaxException e) { - return false; - } - } - - /** A pattern written back in one of the friendlier notations, where that is possible. */ - public static final class Decoded { - public final BanPattern pattern; - public final String ip; - public final String name; - - Decoded(BanPattern pattern, String ip, String name) { - this.pattern = pattern; - this.ip = ip; - this.name = name; - } - } - - /** - * Finds the friendliest notation that reproduces an existing ban's IP and name - * expressions exactly, so an editor can show them the way they were most likely - * typed; anything it cannot round-trip is shown as the raw regular expression. - */ - public static Decoded decode(String ipRegex, String nameRegex) { - String ip = ipRegex == null ? "" : ipRegex; - String name = nameRegex == null ? "" : nameRegex; - for (BanPattern p : new BanPattern[] {WILDCARD_IPV4, WILDCARD_IPV6, FIXED_STRING}) { - String ipText = p.fromRegex(ip, p.ipWildcard); - String nameText = p.fromRegex(name, p.ipWildcard == null ? null : NAME_WILDCARD); - if (ipText != null && nameText != null - && p.ipToRegex(ipText).equals(ip) && p.nameToRegex(nameText).equals(name)) { - return new Decoded(p, ipText, nameText); - } - } - return new Decoded(REGULAR_EXPRESSION, ip, name); - } - - /** Inverts {@link #toRegex}; {@code null} where the expression is not in this notation. */ - private String fromRegex(String regex, String wildcard) { - StringBuilder out = new StringBuilder(regex.length()); - for (int i = 0; i < regex.length(); i++) { - if (wildcard != null && regex.startsWith(wildcard, i)) { - out.append('*'); - i += wildcard.length() - 1; - } else if (regex.charAt(i) == '\\') { - if (i + 1 >= regex.length() || META.indexOf(regex.charAt(i + 1)) < 0) return null; - out.append(regex.charAt(++i)); - } else if (META.indexOf(regex.charAt(i)) >= 0) { - return null; - } else { - out.append(regex.charAt(i)); - } - } - return out.toString(); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ban/BanRule.java b/ts3-client/core/src/main/java/com/ts3client/net/ban/BanRule.java deleted file mode 100644 index 4532b72..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/ban/BanRule.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.ts3client.net.ban; - -/** - * What a ban is made of, as {@code banadd} takes it: any combination of an IP pattern, - * a nickname pattern, a unique identifier and a myTeamSpeak id, with a duration and a - * reason. The patterns are regular expressions — see {@link BanPattern} for turning - * friendlier notations into them. - */ -public final class BanRule { - - /** The longest reason the server stores with a ban. */ - public static final int REASON_LIMIT = 80; - - public final String ipRegex; - public final String nameRegex; - public final String uid; - public final String mytsid; - /** The ban's length in seconds, or 0 for a permanent one. */ - public final long durationSeconds; - public final String reason; - - public BanRule(String ipRegex, String nameRegex, String uid, String mytsid, - long durationSeconds, String reason) { - this.ipRegex = trimmed(ipRegex); - this.nameRegex = trimmed(nameRegex); - this.uid = trimmed(uid); - this.mytsid = trimmed(mytsid); - this.durationSeconds = Math.max(0, durationSeconds); - this.reason = trimmed(reason); - } - - /** A rule with nothing to match bans nobody; the server rejects it. */ - public boolean hasTarget() { - return !ipRegex.isEmpty() || !nameRegex.isEmpty() || !uid.isEmpty() || !mytsid.isEmpty(); - } - - public boolean isPermanent() { - return durationSeconds == 0; - } - - private static String trimmed(String s) { - return s == null ? "" : s.trim(); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ban/BanUnit.java b/ts3-client/core/src/main/java/com/ts3client/net/ban/BanUnit.java deleted file mode 100644 index fcc0981..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/ban/BanUnit.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.ts3client.net.ban; - -/** - * The units a ban's length is given in, as the official client asks for it: an amount of - * seconds, minutes, hours or days, or permanent, which takes no amount. - */ -public enum BanUnit { - - SECONDS("seconds", 1), - MINUTES("minutes", 60), - HOURS("hours", 3600), - DAYS("days", 86400), - PERMANENT("permanent", 0); - - private final String label; - private final long seconds; - - BanUnit(String label, long seconds) { - this.label = label; - this.seconds = seconds; - } - - public String label() { - return label; - } - - /** The length of {@code amount} of this unit in seconds; 0 when permanent. */ - public long toSeconds(long amount) { - return amount * seconds; - } - - /** The largest unit that divides {@code seconds} evenly; a length of 0 or less is permanent. */ - public static BanUnit largestFor(long seconds) { - if (seconds <= 0) return PERMANENT; - for (int i = PERMANENT.ordinal() - 1; i > 0; i--) { - if (seconds % values()[i].seconds == 0) return values()[i]; - } - return SECONDS; - } - - /** How many of this unit {@code seconds} is; 0 when permanent. */ - public long amountOf(long seconds) { - return this == PERMANENT ? 0 : seconds / this.seconds; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/filetransfer/FileTransfer.java b/ts3-client/core/src/main/java/com/ts3client/net/filetransfer/FileTransfer.java deleted file mode 100644 index 2dfda15..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/filetransfer/FileTransfer.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.ts3client.net.filetransfer; - -import java.io.File; - -/** - * An observable handle for a single in-flight (or finished) file transfer. Created - * by {@link FileTransferManager}; the actual byte copy runs on a background thread - * and mutates this object, notifying a {@link Listener} on every change so a UI can - * render live progress. All mutating methods are package-private — callers only read. - */ -public final class FileTransfer { - - public enum Direction {UPLOAD, DOWNLOAD} - - public enum State { - /** Announced to the server, file connection not yet established. */ - PENDING, - /** Bytes are actively being transferred. */ - ACTIVE, - COMPLETED, - FAILED, - CANCELLED - } - - /** Notified (off the UI thread) whenever this transfer's progress or state changes. */ - public interface Listener { - void onTransferChanged(FileTransfer transfer); - } - - private final Direction direction; - private final int channelId; - private final String remoteName; - private final File localFile; - private final Listener listener; - - private volatile long totalBytes; - private volatile long transferredBytes; - private volatile State state = State.PENDING; - private volatile String errorMessage; - private volatile boolean cancelRequested; - - private final long startedAtMs = System.currentTimeMillis(); - private volatile long finishedAtMs; - - FileTransfer(Direction direction, int channelId, String remoteName, File localFile, - long totalBytes, Listener listener) { - this.direction = direction; - this.channelId = channelId; - this.remoteName = remoteName; - this.localFile = localFile; - this.totalBytes = totalBytes; - this.listener = listener; - } - - // ---- read-only accessors ---- - - public Direction getDirection() { - return direction; - } - - public int getChannelId() { - return channelId; - } - - public String getRemoteName() { - return remoteName; - } - - public File getLocalFile() { - return localFile; - } - - public long getTotalBytes() { - return totalBytes; - } - - public long getTransferredBytes() { - return transferredBytes; - } - - public State getState() { - return state; - } - - public String getErrorMessage() { - return errorMessage; - } - - public boolean isDone() { - State s = state; - return s == State.COMPLETED || s == State.FAILED || s == State.CANCELLED; - } - - /** Completion fraction in [0, 1], or 0 when the total size is unknown. */ - public double getProgress() { - long total = totalBytes; - if (total <= 0) return isDone() && state == State.COMPLETED ? 1.0 : 0.0; - double p = (double) transferredBytes / total; - return p < 0 ? 0 : (p > 1 ? 1 : p); - } - - /** Average speed in bytes per second over the transfer's lifetime, or 0 if not measurable. */ - public double getAverageSpeed() { - long end = isDone() ? finishedAtMs : System.currentTimeMillis(); - long elapsed = Math.max(1, end - startedAtMs); - return transferredBytes * 1000.0 / elapsed; - } - - /** Requests cancellation; the transfer thread aborts at the next chunk boundary. */ - public void cancel() { - cancelRequested = true; - } - - boolean isCancelRequested() { - return cancelRequested; - } - - // ---- package-private mutators, called by FileTransferManager ---- - - void setTotalBytes(long totalBytes) { - this.totalBytes = totalBytes; - } - - void addTransferred(long delta) { - transferredBytes += delta; - fireChanged(); - } - - void markActive() { - state = State.ACTIVE; - fireChanged(); - } - - void markCompleted() { - finishedAtMs = System.currentTimeMillis(); - state = State.COMPLETED; - fireChanged(); - } - - void markCancelled() { - finishedAtMs = System.currentTimeMillis(); - state = State.CANCELLED; - fireChanged(); - } - - void markFailed(String message) { - finishedAtMs = System.currentTimeMillis(); - errorMessage = message; - state = State.FAILED; - fireChanged(); - } - - private void fireChanged() { - if (listener != null) listener.onTransferChanged(this); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/filetransfer/FileTransferManager.java b/ts3-client/core/src/main/java/com/ts3client/net/filetransfer/FileTransferManager.java deleted file mode 100644 index 5d3e3cd..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/filetransfer/FileTransferManager.java +++ /dev/null @@ -1,522 +0,0 @@ -package com.ts3client.net.filetransfer; - -import com.github.manevolent.ts3j.api.FileTransferParameters; -import com.github.manevolent.ts3j.command.SingleCommand; -import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; -import com.github.manevolent.ts3j.event.TS3Listener; -import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent; -import com.github.manevolent.ts3j.protocol.ProtocolRole; -import com.github.manevolent.ts3j.protocol.socket.client.LocalTeamspeakClientSocket; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.Supplier; - -/** - * Implements the TeamSpeak 3 channel file-transfer protocol on top of a connected - * {@link LocalTeamspeakClientSocket}. - * - *

Directory operations ({@link #list}, {@link #createDirectory}, {@link #delete}, - * {@link #rename}) are ordinary control commands and run synchronously on the caller's - * thread. Byte transfers ({@link #download}, {@link #upload}) are two-phase: an - * {@code ftinit*} control command negotiates a one-time key, host and port, after which - * a raw TCP connection to the server's file port carries the bytes. That copy runs on a - * background thread and reports through the returned {@link FileTransfer} handle. - */ -public final class FileTransferManager { - - private static final int CONNECT_TIMEOUT_MS = 15_000; - /** How long a download may go without receiving anything before it counts as failed. */ - private static final int STALL_TIMEOUT_MS = 30_000; - private static final int BUFFER_SIZE = 64 * 1024; - /** How long to wait for the server's {@code notifystart*} reply after an {@code ftinit*}. */ - private static final long NEGOTIATE_TIMEOUT_MS = 15_000; - - /** TeamSpeak error id returned by {@code ftgetfilelist} for an empty directory. */ - private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501; - /** How long to wait for the server to finish listing a directory. */ - private static final long LIST_TIMEOUT_MS = 15_000; - - private final LocalTeamspeakClientSocket socket; - /** Host we are connected to, used when the server reports no dedicated file-transfer host. */ - private final Supplier fallbackHost; - private final AtomicInteger clientTransferId = new AtomicInteger(1); - /** Every byte moved so far, for the connection info's transfer rate. */ - private final AtomicLong bytesSent = new AtomicLong(); - private final AtomicLong bytesReceived = new AtomicLong(); - private final ExecutorService transferPool = Executors.newCachedThreadPool(r -> { - Thread t = new Thread(r, "ts3j-filetransfer"); - t.setDaemon(true); - return t; - }); - - /** - * In-flight {@code ftinit*} negotiations keyed by our {@code clientftfid}. The server - * answers an init out-of-band with a {@code notifystart*} (success) or a - * {@code notifystatusfiletransfer} (failure) event, which {@link #ftEventListener} - * routes back to the waiting transfer thread. - */ - private final Map>> pendingInits = new ConcurrentHashMap<>(); - - /** - * The {@code ftgetfilelist} in progress. The server answers that command with a - * {@code notifyfilelist} event per entry and a closing {@code notifyfilelistfinished} - * rather than with rows of the command's own reply, so the entries are collected here - * until the listing ends. One listing may be in flight at a time. - */ - private volatile FileListRequest fileListRequest; - private final TS3Listener ftEventListener = new TS3Listener() { - @Override - public void onUnknownEvent(UnknownTeamspeakEvent e) { - handleFileTransferEvent(e); - } - }; - - public FileTransferManager(LocalTeamspeakClientSocket socket, Supplier fallbackHost) { - this.socket = socket; - this.fallbackHost = fallbackHost; - socket.addListener(ftEventListener); - } - - public long bytesSent() { - return bytesSent.get(); - } - - public long bytesReceived() { - return bytesReceived.get(); - } - - // ---- directory operations ---- - - /** - * Lists the files and subdirectories directly under {@code path} in the given - * channel's repository. Returns an empty list for an empty directory. - * - *

Blocks until the server has sent the whole listing, so it must not be called from - * the event thread that delivers it. - */ - public List list(int channelId, String channelPassword, String path) - throws Exception { - String directory = path == null || path.isEmpty() ? "/" : path; - SingleCommand cmd = new SingleCommand("ftgetfilelist", ProtocolRole.CLIENT, - new CommandSingleParameter("cid", Integer.toString(channelId)), - new CommandSingleParameter("cpw", channelPassword == null ? "" : channelPassword), - new CommandSingleParameter("path", directory)); - - FileListRequest request = new FileListRequest(channelId, directory); - fileListRequest = request; - try { - socket.executeCommand(cmd).complete(); - // The command's reply only acknowledges it; the entries are events, and the - // server marks their end with notifyfilelistfinished. - request.finished.get(LIST_TIMEOUT_MS, TimeUnit.MILLISECONDS); - } catch (com.github.manevolent.ts3j.command.CommandException e) { - if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e; - } catch (TimeoutException e) { - throw new IOException("The server did not finish listing " + directory); - } finally { - fileListRequest = null; - } - return new ArrayList<>(request.files); - } - - /** Collects one {@code notifyfilelist} entry for the listing in flight. */ - private void collectListEntry(Map row) { - FileListRequest request = fileListRequest; - if (request == null) return; - String cid = row.get("cid"); - if (cid != null && !cid.isEmpty() && parseLong(cid) != request.channelId) return; - String name = row.get("name"); - if (name == null || name.isEmpty()) return; - request.files.add(new RemoteFile( - name, - row.getOrDefault("path", request.path), - parseLong(row.get("size")), - "0".equals(row.get("type")), - parseLong(row.get("datetime")))); - } - - /** Creates a new directory at {@code dirPath} (a full path such as {@code /new}). */ - public void createDirectory(int channelId, String channelPassword, String dirPath) - throws Exception { - SingleCommand cmd = new SingleCommand("ftcreatedir", ProtocolRole.CLIENT, - new CommandSingleParameter("cid", Integer.toString(channelId)), - new CommandSingleParameter("cpw", channelPassword == null ? "" : channelPassword), - new CommandSingleParameter("dirname", dirPath)); - socket.executeCommand(cmd).complete(); - } - - /** Deletes a file or (recursively) a directory at {@code fullPath}. */ - public void delete(int channelId, String channelPassword, String fullPath) - throws Exception { - SingleCommand cmd = new SingleCommand("ftdeletefile", ProtocolRole.CLIENT, - new CommandSingleParameter("cid", Integer.toString(channelId)), - new CommandSingleParameter("cpw", channelPassword == null ? "" : channelPassword), - new CommandSingleParameter("name", fullPath)); - socket.executeCommand(cmd).complete(); - } - - /** Renames or moves a file within the same channel. */ - public void rename(int channelId, String channelPassword, String oldFullPath, String newFullPath) - throws Exception { - SingleCommand cmd = new SingleCommand("ftrenamefile", ProtocolRole.CLIENT, - new CommandSingleParameter("cid", Integer.toString(channelId)), - new CommandSingleParameter("cpw", channelPassword == null ? "" : channelPassword), - new CommandSingleParameter("oldname", oldFullPath), - new CommandSingleParameter("newname", newFullPath)); - socket.executeCommand(cmd).complete(); - } - - // ---- byte transfers ---- - - /** - * Starts downloading {@code remoteFullPath} from the channel to {@code target}. - * Returns immediately with a handle whose progress the caller can observe; the - * copy proceeds on a background thread. - */ - public FileTransfer download(int channelId, String channelPassword, String remoteFullPath, - File target, FileTransfer.Listener listener) { - FileTransfer transfer = new FileTransfer(FileTransfer.Direction.DOWNLOAD, channelId, - fileName(remoteFullPath), target, -1, listener); - transferPool.execute(() -> runDownload(channelId, channelPassword, remoteFullPath, transfer)); - return transfer; - } - - /** - * Starts uploading {@code source} into the channel at {@code remoteFullPath}. - * Returns immediately with a handle whose progress the caller can observe. - */ - public FileTransfer upload(int channelId, String channelPassword, String remoteFullPath, - File source, boolean overwrite, FileTransfer.Listener listener) { - FileTransfer transfer = new FileTransfer(FileTransfer.Direction.UPLOAD, channelId, - fileName(remoteFullPath), source, source.length(), listener); - transferPool.execute(() -> runUpload(channelId, channelPassword, remoteFullPath, source, overwrite, transfer)); - return transfer; - } - - /** - * Downloads a small file straight into memory, blocking until it is complete. - * Intended for icons and other assets that never reach the disk. - */ - public byte[] downloadToMemory(int channelId, String channelPassword, String remoteFullPath, - int maxBytes) throws Exception { - int ftfid = clientTransferId.getAndIncrement(); - SingleCommand cmd = new SingleCommand("ftinitdownload", ProtocolRole.CLIENT, - new CommandSingleParameter("clientftfid", Integer.toString(ftfid)), - new CommandSingleParameter("name", remoteFullPath), - new CommandSingleParameter("cid", Integer.toString(channelId)), - new CommandSingleParameter("cpw", channelPassword == null ? "" : channelPassword), - new CommandSingleParameter("seekpos", "0"), - new CommandSingleParameter("proto", "0")); - - FileTransferParameters params = negotiate(ftfid, cmd); - long size = params.getFileSize(); - if (size <= 0 || size > maxBytes) { - throw new IOException("Unexpected file size " + size + " for " + remoteFullPath); - } - - byte[] data = new byte[(int) size]; - try (Socket fileSocket = openFileSocket(params); - InputStream in = new BufferedInputStream(fileSocket.getInputStream())) { - sendKey(fileSocket, params); - int offset = 0; - while (offset < data.length) { - int read = in.read(data, offset, data.length - offset); - if (read < 0) throw new IOException("File server closed the connection early"); - offset += read; - bytesReceived.addAndGet(read); - } - } - return data; - } - - private void runDownload(int channelId, String channelPassword, String remoteFullPath, - FileTransfer transfer) { - try { - int ftfid = clientTransferId.getAndIncrement(); - SingleCommand cmd = new SingleCommand("ftinitdownload", ProtocolRole.CLIENT, - new CommandSingleParameter("clientftfid", Integer.toString(ftfid)), - new CommandSingleParameter("name", remoteFullPath), - new CommandSingleParameter("cid", Integer.toString(channelId)), - new CommandSingleParameter("cpw", channelPassword == null ? "" : channelPassword), - new CommandSingleParameter("seekpos", "0"), - new CommandSingleParameter("proto", "0")); - - FileTransferParameters params = negotiate(ftfid, cmd); - long size = params.getFileSize(); - transfer.setTotalBytes(size); - - try (Socket fileSocket = openFileSocket(params); - InputStream in = new BufferedInputStream(fileSocket.getInputStream()); - OutputStream fileOut = new BufferedOutputStream(new FileOutputStream(transfer.getLocalFile()))) { - - sendKey(fileSocket, params); - transfer.markActive(); - - byte[] buffer = new byte[BUFFER_SIZE]; - long remaining = size; - while (remaining > 0) { - if (transfer.isCancelRequested()) { - transfer.markCancelled(); - deleteQuietly(transfer.getLocalFile()); - return; - } - int want = (int) Math.min(buffer.length, remaining); - int read = in.read(buffer, 0, want); - if (read < 0) throw new IOException("File server closed the connection early"); - fileOut.write(buffer, 0, read); - remaining -= read; - bytesReceived.addAndGet(read); - transfer.addTransferred(read); - } - } - transfer.markCompleted(); - } catch (Exception e) { - transfer.markFailed(rootMessage(e)); - deleteQuietly(transfer.getLocalFile()); - } - } - - private void runUpload(int channelId, String channelPassword, String remoteFullPath, - File source, boolean overwrite, FileTransfer transfer) { - try { - long size = source.length(); - int ftfid = clientTransferId.getAndIncrement(); - SingleCommand cmd = new SingleCommand("ftinitupload", ProtocolRole.CLIENT, - new CommandSingleParameter("clientftfid", Integer.toString(ftfid)), - new CommandSingleParameter("name", remoteFullPath), - new CommandSingleParameter("cid", Integer.toString(channelId)), - new CommandSingleParameter("cpw", channelPassword == null ? "" : channelPassword), - new CommandSingleParameter("size", Long.toString(size)), - new CommandSingleParameter("overwrite", overwrite ? "1" : "0"), - new CommandSingleParameter("resume", "0"), - new CommandSingleParameter("proto", "0")); - - FileTransferParameters params = negotiate(ftfid, cmd); - // The server may already hold a prefix of the file (resume); start after it. - long seekpos = params.getMap().containsKey("seekpos") ? params.getLong("seekpos") : 0; - if (seekpos < 0 || seekpos > size) seekpos = 0; - - try (Socket fileSocket = openFileSocket(params); - InputStream fileIn = new BufferedInputStream(new FileInputStream(source)); - OutputStream out = new BufferedOutputStream(fileSocket.getOutputStream())) { - - sendKey(fileSocket, params); - transfer.markActive(); - - if (seekpos > 0) { - skipFully(fileIn, seekpos); - transfer.addTransferred(seekpos); - } - - byte[] buffer = new byte[BUFFER_SIZE]; - long remaining = size - seekpos; - while (remaining > 0) { - if (transfer.isCancelRequested()) { - transfer.markCancelled(); - return; - } - int want = (int) Math.min(buffer.length, remaining); - int read = fileIn.read(buffer, 0, want); - if (read < 0) break; // file shorter than announced; stop - out.write(buffer, 0, read); - remaining -= read; - bytesSent.addAndGet(read); - transfer.addTransferred(read); - } - out.flush(); - } - transfer.markCompleted(); - } catch (Exception e) { - transfer.markFailed(rootMessage(e)); - } - } - - /** - * Sends an {@code ftinit*} command and returns the negotiated parameters. The server - * acknowledges the command itself, then reports the transfer's key/host/port - * asynchronously via a {@code notifystart*} event (or a {@code notifystatusfiletransfer} - * on refusal), which {@link #handleFileTransferEvent} feeds back through {@code pendingInits}. - */ - private FileTransferParameters negotiate(int clientTransferId, SingleCommand cmd) throws Exception { - CompletableFuture> future = new CompletableFuture<>(); - pendingInits.put(clientTransferId, future); - try { - // Await the command-level acknowledgement; a hard error (e.g. bad path) throws here. - socket.executeCommand(cmd).complete(); - Map result; - try { - result = future.get(NEGOTIATE_TIMEOUT_MS, TimeUnit.MILLISECONDS); - } catch (ExecutionException e) { - Throwable cause = e.getCause(); - throw cause instanceof Exception ? (Exception) cause : e; - } catch (TimeoutException e) { - throw new IOException("Timed out waiting for the server to start the transfer"); - } - FileTransferParameters params = new FileTransferParameters(result); - String key = params.getFileTransferKey(); - if (key == null || key.isEmpty()) throw new IOException("Server refused the file transfer"); - return params; - } finally { - pendingInits.remove(clientTransferId); - } - } - - /** - * Routes an incoming file-transfer notification to the negotiation that is waiting for - * it. {@code notifystartdownload}/{@code notifystartupload} carry the key, host and port; - * {@code notifystatusfiletransfer} signals a non-zero status (a refusal) before the - * transfer starts. - */ - private void handleFileTransferEvent(UnknownTeamspeakEvent e) { - String command = e.getCommand(); - if (command == null) return; - Map map = e.getMap(); - if (command.equals("notifyfilelist")) { - collectListEntry(map); - return; - } - if (command.equals("notifyfilelistfinished")) { - FileListRequest request = fileListRequest; - if (request != null) request.finished.complete(null); - return; - } - Integer ftfid = tryParseInt(map.get("clientftfid")); - if (ftfid == null) return; - CompletableFuture> future = pendingInits.get(ftfid); - if (future == null) return; - - if (command.equals("notifystartdownload") || command.equals("notifystartupload")) { - future.complete(map); - } else if (command.equals("notifystatusfiletransfer")) { - int status = (int) parseLong(map.get("status")); - if (status != 0) { - String msg = map.get("msg"); - future.completeExceptionally( - new IOException(msg != null && !msg.isEmpty() ? msg : "File transfer failed (status " + status + ")")); - } - } - } - - private Socket openFileSocket(FileTransferParameters params) throws IOException { - Socket socket = new Socket(); - socket.connect(new InetSocketAddress(resolveHost(params.getFileServerHost()), - params.getFileServerPort()), CONNECT_TIMEOUT_MS); - socket.setSoTimeout(STALL_TIMEOUT_MS); - return socket; - } - - /** Sends the negotiated one-time key that authorises this connection to the file port. */ - private static void sendKey(Socket fileSocket, FileTransferParameters params) throws IOException { - OutputStream out = fileSocket.getOutputStream(); - out.write(params.getFileTransferKey().getBytes(StandardCharsets.US_ASCII)); - out.flush(); - } - - /** - * Picks the host to reach the file server. The {@code ip} the server reports may be - * a comma-separated list, empty, or a wildcard; in those cases fall back to the host - * we are already connected to. - */ - private String resolveHost(String reported) { - if (reported != null) { - String first = reported.split(",")[0].trim(); - if (!first.isEmpty() && !first.startsWith("0.0.0.0")) return first; - } - return fallbackHost.get(); - } - - private static void deleteQuietly(File file) { - if (file != null && file.isFile()) { - //noinspection ResultOfMethodCallIgnored - file.delete(); - } - } - - private static void skipFully(InputStream in, long n) throws IOException { - long remaining = n; - while (remaining > 0) { - long skipped = in.skip(remaining); - if (skipped <= 0) { - if (in.read() < 0) throw new IOException("Unexpected end of file while seeking"); - skipped = 1; - } - remaining -= skipped; - } - } - - public void shutdown() { - socket.removeListener(ftEventListener); - for (CompletableFuture> future : pendingInits.values()) { - future.completeExceptionally(new IOException("Disconnected")); - } - pendingInits.clear(); - transferPool.shutdownNow(); - } - - // ---- helpers ---- - - private static String fileName(String fullPath) { - int slash = fullPath.lastIndexOf('/'); - return slash < 0 ? fullPath : fullPath.substring(slash + 1); - } - - private static long parseLong(String s) { - if (s == null || s.isEmpty()) return 0; - try { - return Long.parseLong(s.trim()); - } catch (NumberFormatException e) { - return 0; - } - } - - private static Integer tryParseInt(String s) { - if (s == null || s.isEmpty()) return null; - try { - return Integer.parseInt(s.trim()); - } catch (NumberFormatException e) { - return null; - } - } - - private static String rootMessage(Throwable t) { - Throwable r = t; - while (r.getCause() != null && r.getCause() != r) r = r.getCause(); - String m = r.getMessage(); - return m != null ? m : r.getClass().getSimpleName(); - } - - /** One in-flight {@code ftgetfilelist} and the entries received for it so far. */ - private static final class FileListRequest { - final int channelId; - final String path; - final List files = new java.util.concurrent.CopyOnWriteArrayList<>(); - final CompletableFuture finished = new CompletableFuture<>(); - - FileListRequest(int channelId, String path) { - this.channelId = channelId; - this.path = path; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/filetransfer/RemoteFile.java b/ts3-client/core/src/main/java/com/ts3client/net/filetransfer/RemoteFile.java deleted file mode 100644 index 52eb45e..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/net/filetransfer/RemoteFile.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.ts3client.net.filetransfer; - -/** - * One entry in a channel's file repository, as returned by {@code ftgetfilelist}. - * A UI-facing value type that keeps the reusable core free of ts3j API classes. - */ -public final class RemoteFile { - - private final String name; - /** Parent directory path, always ending in {@code /} (e.g. {@code /} or {@code /sub/}). */ - private final String parentPath; - private final long size; - private final boolean directory; - private final long lastModifiedEpochSec; - - public RemoteFile(String name, String parentPath, long size, boolean directory, long lastModifiedEpochSec) { - this.name = name; - this.parentPath = parentPath == null || parentPath.isEmpty() ? "/" : parentPath; - this.size = size; - this.directory = directory; - this.lastModifiedEpochSec = lastModifiedEpochSec; - } - - public String getName() { - return name; - } - - public String getParentPath() { - return parentPath; - } - - /** Full server path including the file name, e.g. {@code /sub/clip.ogg}. */ - public String getFullPath() { - String base = parentPath.endsWith("/") ? parentPath : parentPath + "/"; - return base + name; - } - - public long getSize() { - return size; - } - - public boolean isDirectory() { - return directory; - } - - public long getLastModifiedEpochSec() { - return lastModifiedEpochSec; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/proto/ProtobufReader.java b/ts3-client/core/src/main/java/com/ts3client/proto/ProtobufReader.java deleted file mode 100644 index 89b88d7..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/proto/ProtobufReader.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.ts3client.proto; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; - -/** - * Minimal protocol-buffers wire-format cursor: walks a message field by field - * without needing a compiled schema. Callers switch on {@link #fieldNumber()} - * and pull the value with the accessor matching the field's declared type; - * anything else is skipped with {@link #skip()}. - */ -public final class ProtobufReader { - - private static final int VARINT = 0; - private static final int FIXED64 = 1; - private static final int LENGTH_DELIMITED = 2; - private static final int FIXED32 = 5; - - private final byte[] data; - private final int end; - private int pos; - private int fieldNumber; - private int wireType; - - public ProtobufReader(byte[] data) { - this(data, 0, data.length); - } - - private ProtobufReader(byte[] data, int start, int end) { - this.data = data; - this.pos = start; - this.end = end; - } - - /** Advances to the next field; {@code false} at the end of the message. */ - public boolean next() throws IOException { - if (pos >= end) return false; - long tag = readVarint(); - fieldNumber = (int) (tag >>> 3); - wireType = (int) (tag & 7); - if (fieldNumber == 0) throw new IOException("Invalid protobuf tag"); - return true; - } - - public int fieldNumber() { - return fieldNumber; - } - - public long readVarint() throws IOException { - long result = 0; - for (int shift = 0; shift < 64; shift += 7) { - if (pos >= end) throw new IOException("Truncated protobuf varint"); - int b = data[pos++]; - result |= (long) (b & 0x7F) << shift; - if ((b & 0x80) == 0) return result; - } - throw new IOException("Malformed protobuf varint"); - } - - public boolean readBool() throws IOException { - return readVarint() != 0; - } - - public String readString() throws IOException { - int length = readLength(); - String s = new String(data, pos, length, StandardCharsets.UTF_8); - pos += length; - return s; - } - - public byte[] readBytes() throws IOException { - int length = readLength(); - byte[] out = new byte[length]; - System.arraycopy(data, pos, out, 0, length); - pos += length; - return out; - } - - /** A reader positioned over an embedded message; this reader moves past it. */ - public ProtobufReader readMessage() throws IOException { - int length = readLength(); - ProtobufReader nested = new ProtobufReader(data, pos, pos + length); - pos += length; - return nested; - } - - public void skip() throws IOException { - switch (wireType) { - case VARINT -> readVarint(); - case FIXED64 -> pos += 8; - case LENGTH_DELIMITED -> { - int length = readLength(); - pos += length; - } - case FIXED32 -> pos += 4; - default -> throw new IOException("Unsupported protobuf wire type " + wireType); - } - if (pos > end) throw new IOException("Truncated protobuf message"); - } - - private int readLength() throws IOException { - if (wireType != LENGTH_DELIMITED) throw new IOException("Field " + fieldNumber + " is not length-delimited"); - long length = readVarint(); - if (length < 0 || pos + length > end) throw new IOException("Truncated protobuf message"); - return (int) length; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/proto/ProtobufWriter.java b/ts3-client/core/src/main/java/com/ts3client/proto/ProtobufWriter.java deleted file mode 100644 index fa8fbcf..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/proto/ProtobufWriter.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.ts3client.proto; - -import java.io.ByteArrayOutputStream; -import java.nio.charset.StandardCharsets; - -/** Builds a protocol-buffers message field by field; the counterpart of {@link ProtobufReader}. */ -public final class ProtobufWriter { - - private final ByteArrayOutputStream out = new ByteArrayOutputStream(); - - public ProtobufWriter varint(int field, long value) { - tag(field, 0); - rawVarint(value); - return this; - } - - public ProtobufWriter string(int field, String value) { - return bytes(field, value.getBytes(StandardCharsets.UTF_8)); - } - - public ProtobufWriter bytes(int field, byte[] value) { - tag(field, 2); - rawVarint(value.length); - out.write(value, 0, value.length); - return this; - } - - public ProtobufWriter message(int field, ProtobufWriter message) { - return bytes(field, message.toByteArray()); - } - - public byte[] toByteArray() { - return out.toByteArray(); - } - - private void tag(int field, int wireType) { - rawVarint(((long) field << 3) | wireType); - } - - private void rawVarint(long value) { - while ((value & ~0x7FL) != 0) { - out.write((int) (value & 0x7F) | 0x80); - value >>>= 7; - } - out.write((int) value); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/recording/MixdownSink.java b/ts3-client/core/src/main/java/com/ts3client/recording/MixdownSink.java deleted file mode 100644 index a9d6fd4..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/recording/MixdownSink.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.ts3client.recording; - -import com.ts3client.audio.VoiceFormat; -import com.ts3client.audio.ogg.OpusHeaders; -import com.ts3client.audio.opus.OpusCodec; -import com.ts3client.audio.opus.OpusEncoder; - -import java.io.IOException; -import java.nio.file.Path; -import java.util.List; -import java.util.TreeMap; - -/** Mixes every speaker down onto one mono track, written to the file as it goes. */ -final class MixdownSink implements RecordingSink { - - private static final int BITRATE = 64_000; - /** How long a frame waits for the other speakers' frames of the same moment before it is mixed. */ - private static final int MIX_DELAY_FRAMES = 25; - - private final Path file; - private final OpusEncoder encoder; - private final OggOpusStream stream; - /** Frames not yet mixed, by their place on the timeline. */ - private final TreeMap pending = new TreeMap<>(); - private long mixed; - - MixdownSink(Path file, OpusCodec opus) throws IOException { - this.file = file; - this.encoder = RecordingEncoders.mono(opus, BITRATE); - try { - this.stream = new OggOpusStream(file, OpusHeaders.mono(OggOpusStream.PRE_SKIP, VoiceFormat.SAMPLE_RATE), - OpusHeaders.tags(opus.version(), List.of())); - } catch (IOException e) { - encoder.close(); - throw e; - } - } - - @Override - public void write(Track track, long index, float[] frame) { - if (index < mixed) return; // too late to be mixed in - pending.merge(index, frame, (sum, more) -> { - for (int i = 0; i < sum.length; i++) sum[i] += more[i]; - return sum; - }); - } - - @Override - public void advance(long now) throws IOException { - mixUpTo(now - MIX_DELAY_FRAMES); - } - - private void mixUpTo(long end) throws IOException { - for (; mixed < end; mixed++) { - float[] frame = pending.remove(mixed); - if (frame == null) { - frame = RecordingEncoders.SILENT_FRAME; - } else { - for (int i = 0; i < frame.length; i++) frame[i] = Math.max(-1f, Math.min(1f, frame[i])); - } - stream.write(encoder.encode(frame)); - } - } - - @Override - public List finish(long end) throws IOException { - long frames = pending.isEmpty() ? end : Math.max(end, pending.lastKey() + 1); - frames = Math.max(frames, mixed); - mixUpTo(frames); - // One more frame brings out what the encoder's delay still holds. - stream.write(encoder.encode(RecordingEncoders.SILENT_FRAME)); - stream.finish(frames); - encoder.close(); - return List.of(file); - } - - @Override - public void abort() { - try { - stream.close(); - } catch (IOException ignored) { - } - encoder.close(); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/recording/MultitrackSink.java b/ts3-client/core/src/main/java/com/ts3client/recording/MultitrackSink.java deleted file mode 100644 index eaac326..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/recording/MultitrackSink.java +++ /dev/null @@ -1,242 +0,0 @@ -package com.ts3client.recording; - -import com.ts3client.audio.VoiceFormat; -import com.ts3client.audio.ogg.OpusHeaders; -import com.ts3client.audio.ogg.SelfDelimitedOpus; -import com.ts3client.audio.opus.OpusCodec; -import com.ts3client.audio.opus.OpusEncoder; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * Gives every speaker a channel of their own: one uncoupled mono Opus stream each, up to - * {@link OpusHeaders#MAX_DISCRETE_CHANNELS} to a file. How many channels a file has goes in - * its header, so tracks are encoded into spool files as the recording runs and only put - * together into the Ogg files once it stops. A track is silent from the start of the - * recording until its speaker first speaks. - */ -final class MultitrackSink implements RecordingSink { - - private static final int BITRATE = 48_000; - /** Pauses up to this long are encoded as they are; longer ones are filled with a stock silent packet. */ - private static final int ENCODED_PAUSE_FRAMES = 50; - /** - * Frames of silence a fresh encoder encodes before its first speech: its first packets - * after the stock silence come out faded in. - */ - private static final int PRIMING_FRAMES = 5; - - private final Path file; - private final OpusCodec opus; - private final Path spoolDir; - private final byte[] silence; - /** In the order speakers first spoke, which is the order of the channels. */ - private final Map spools = new LinkedHashMap<>(); - - MultitrackSink(Path file, OpusCodec opus) throws IOException { - this.file = file; - this.opus = opus; - this.silence = RecordingEncoders.silentPacket(opus, BITRATE); - Path dir = file.toAbsolutePath().getParent(); - this.spoolDir = Files.createTempDirectory(dir, "." + file.getFileName() + "-"); - } - - @Override - public void write(Track track, long index, float[] frame) throws IOException { - Spool spool = spools.get(track); - if (spool == null) { - spool = new Spool(Math.max(0, index - PRIMING_FRAMES), spoolDir.resolve(spools.size() + ".spool")); - spools.put(track, spool); - } - spool.write(index, frame); - } - - @Override - public void advance(long now) { - } - - @Override - public List finish(long end) throws IOException { - long frames = end; - for (Spool spool : spools.values()) frames = Math.max(frames, spool.next); - for (Spool spool : spools.values()) spool.close(); - // Every track reaches one frame past the end, the encoder's delay. - long total = frames + 1; - - List tracks = new ArrayList<>(spools.keySet()); - List files = new ArrayList<>(); - int perFile = OpusHeaders.MAX_DISCRETE_CHANNELS; - // Even nobody speaking leaves a file behind, as long as the recording ran. - for (int first = 0; first < Math.max(1, tracks.size()); first += perFile) { - Path path = first == 0 ? file : numbered(file, first / perFile + 1); - mux(tracks.subList(first, Math.min(tracks.size(), first + perFile)), path, total, frames); - files.add(path); - } - deleteSpools(); - return files; - } - - /** {@code name.ogg} becomes {@code name-2.ogg}. */ - private static Path numbered(Path file, int number) { - String name = file.getFileName().toString(); - int dot = name.lastIndexOf('.'); - String numbered = dot > 0 - ? name.substring(0, dot) + "-" + number + name.substring(dot) - : name + "-" + number; - return file.resolveSibling(numbered); - } - - private void mux(List tracks, Path path, long total, long frames) throws IOException { - int channels = Math.max(1, tracks.size()); - byte[] head = channels == 1 - ? OpusHeaders.mono(OggOpusStream.PRE_SKIP, VoiceFormat.SAMPLE_RATE) - : OpusHeaders.discrete(channels, OggOpusStream.PRE_SKIP, VoiceFormat.SAMPLE_RATE); - List comments = new ArrayList<>(); - for (int i = 0; i < tracks.size(); i++) { - comments.add("CHANNEL" + (i + 1) + "_NAME=" + tracks.get(i).name); - comments.add("CHANNEL" + (i + 1) + "_UID=" + tracks.get(i).speakerId); - } - - List readers = new ArrayList<>(); - try (OggOpusStream stream = new OggOpusStream(path, head, OpusHeaders.tags(opus.version(), comments))) { - for (Track track : tracks) readers.add(new SpoolReader(spools.get(track))); - List packets = new ArrayList<>(channels); - for (long f = 0; f < total; f++) { - packets.clear(); - for (SpoolReader reader : readers) packets.add(reader.packetAt(f)); - if (packets.isEmpty()) packets.add(silence); - stream.write(SelfDelimitedOpus.join(packets)); - } - stream.finish(frames); - } finally { - for (SpoolReader reader : readers) reader.close(); - } - } - - @Override - public void abort() { - for (Spool spool : spools.values()) { - try { - spool.close(); - } catch (IOException ignored) { - } - } - deleteSpools(); - } - - private void deleteSpools() { - for (Spool spool : spools.values()) { - try { - Files.deleteIfExists(spool.path); - } catch (IOException ignored) { - } - } - try { - Files.deleteIfExists(spoolDir); - } catch (IOException ignored) { - } - } - - /** - * One track's packets from its first frame on. Each entry is a packet's length and bytes, - * or a negative count of frames of silence. - */ - private final class Spool { - final long start; - final Path path; - private final DataOutputStream out; - /** The frame after the last one written. */ - long next; - /** Encodes the current talk burst; a new burst after a long pause gets a fresh one. */ - private OpusEncoder encoder; - - Spool(long start, Path path) throws IOException { - this.start = start; - this.next = start; - this.path = path; - this.out = new DataOutputStream(new BufferedOutputStream(Files.newOutputStream(path), 1 << 14)); - } - - void write(long index, float[] frame) throws IOException { - if (index - next > ENCODED_PAUSE_FRAMES) { - endBurst(); - int silent = (int) (index - next - PRIMING_FRAMES); - out.writeInt(-silent); - next += silent; - } - while (next < index) packet(encoder().encode(RecordingEncoders.SILENT_FRAME)); - packet(encoder().encode(frame)); - } - - private OpusEncoder encoder() { - if (encoder == null) encoder = RecordingEncoders.mono(opus, BITRATE); - return encoder; - } - - private void packet(byte[] packet) throws IOException { - out.writeInt(packet.length); - out.write(packet); - next++; - } - - /** Lets the encoder play out the audio its delay still holds. */ - private void endBurst() throws IOException { - if (encoder == null) return; - packet(encoder.encode(RecordingEncoders.SILENT_FRAME)); - encoder.close(); - encoder = null; - } - - void close() throws IOException { - try { - endBurst(); - } finally { - out.close(); - } - } - } - - private final class SpoolReader implements AutoCloseable { - private final Spool spool; - private final DataInputStream in; - private int silentFrames; - - SpoolReader(Spool spool) throws IOException { - this.spool = spool; - this.in = new DataInputStream(new BufferedInputStream(Files.newInputStream(spool.path), 1 << 14)); - } - - /** Must be asked for every frame in turn. */ - byte[] packetAt(long frame) throws IOException { - if (frame < spool.start || frame >= spool.next) return silence; - if (silentFrames > 0) { - silentFrames--; - return silence; - } - int length = in.readInt(); - if (length < 0) { - silentFrames = -length - 1; - return silence; - } - return in.readNBytes(length); - } - - @Override - public void close() { - try { - in.close(); - } catch (IOException ignored) { - } - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/recording/OggOpusStream.java b/ts3-client/core/src/main/java/com/ts3client/recording/OggOpusStream.java deleted file mode 100644 index 3147065..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/recording/OggOpusStream.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.ts3client.recording; - -import com.ts3client.audio.VoiceFormat; -import com.ts3client.audio.ogg.OggPageWriter; -import com.ts3client.audio.ogg.OpusHeaders; - -import java.io.BufferedOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.concurrent.ThreadLocalRandom; - -/** An Ogg Opus file written a 20 ms packet at a time. */ -final class OggOpusStream implements AutoCloseable { - - static final int PRE_SKIP = OpusHeaders.LIBOPUS_PRE_SKIP; - - private final OutputStream file; - private final OggPageWriter ogg; - /** The latest packet, held back until it is known whether it ends the stream. */ - private byte[] held; - private long packets; - - OggOpusStream(Path path, byte[] head, byte[] tags) throws IOException { - file = new BufferedOutputStream(Files.newOutputStream(path), 1 << 16); - ogg = new OggPageWriter(file, ThreadLocalRandom.current().nextInt()); - ogg.write(head, 0); - ogg.flush(); - ogg.write(tags, 0); - ogg.flush(); - } - - void write(byte[] packet) throws IOException { - if (held != null) ogg.write(held, packets * VoiceFormat.FRAME_SIZE); - held = packet; - packets++; - } - - /** - * Ends the stream after {@code frames} frames of audio; the packets written must reach - * past them by the encoder's delay. - */ - void finish(long frames) throws IOException { - if (held != null) ogg.write(held, PRE_SKIP + frames * VoiceFormat.FRAME_SIZE); - held = null; - ogg.finish(); - file.close(); - } - - @Override - public void close() throws IOException { - file.close(); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/recording/RecordingEncoders.java b/ts3-client/core/src/main/java/com/ts3client/recording/RecordingEncoders.java deleted file mode 100644 index 31c7e2a..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/recording/RecordingEncoders.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.ts3client.recording; - -import com.ts3client.audio.VoiceFormat; -import com.ts3client.audio.opus.OpusCodec; -import com.ts3client.audio.opus.OpusEncoder; - -/** The Opus encoders a recording's tracks are encoded with. */ -final class RecordingEncoders { - - static final float[] SILENT_FRAME = new float[VoiceFormat.FRAME_SIZE]; - - private RecordingEncoders() { - } - - static OpusEncoder mono(OpusCodec opus, int bitrate) { - OpusEncoder encoder = opus.createEncoder(VoiceFormat.SAMPLE_RATE, VoiceFormat.FRAME_SIZE, 1, - OpusCodec.Application.AUDIO); - encoder.setBitrate(bitrate); - encoder.setVbr(true); - encoder.setComplexity(10); - return encoder; - } - - /** A packet that decodes to a frame of silence, to stand in where a track has nothing. */ - static byte[] silentPacket(OpusCodec opus, int bitrate) { - try (OpusEncoder encoder = mono(opus, bitrate)) { - byte[] packet = null; - // Past the first frames, which still carry the encoder's start-up. - for (int i = 0; i < 4; i++) packet = encoder.encode(SILENT_FRAME); - return packet; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/recording/RecordingSink.java b/ts3-client/core/src/main/java/com/ts3client/recording/RecordingSink.java deleted file mode 100644 index b49cd39..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/recording/RecordingSink.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.ts3client.recording; - -import java.io.IOException; -import java.nio.file.Path; -import java.util.List; - -/** Where a recording's frames are encoded and stored; driven from the recorder's one thread. */ -interface RecordingSink { - - /** @param index the frame's place on the timeline, past every earlier frame of the track */ - void write(Track track, long index, float[] frame) throws IOException; - - /** The clock reached frame {@code now}; frames well behind it may be finalised. */ - void advance(long now) throws IOException; - - /** - * Writes everything out, ending the recording at frame {@code end} or after the last - * frame written, whichever is later. - * - * @return the files written - */ - List finish(long end) throws IOException; - - /** Gives up after a failure, releasing what is held. */ - void abort(); -} diff --git a/ts3-client/core/src/main/java/com/ts3client/recording/Track.java b/ts3-client/core/src/main/java/com/ts3client/recording/Track.java deleted file mode 100644 index b5db749..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/recording/Track.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.ts3client.recording; - -import java.util.concurrent.TimeUnit; - -/** - * One speaker in a recording: where each of their frames goes on the recording's timeline. - * - *

Frames arrive as they are played, 20 ms apart within a talk burst, so a burst is - * laid down back to back from where its first frame arrived; scheduling jitter then never - * tears holes into it. Only when the speaker's clock drifts too far from the recording's - * is the burst moved back into place. - */ -final class Track { - - /** A pause longer than this starts a new talk burst, placed afresh. */ - private static final long BURST_GAP_NANOS = TimeUnit.MILLISECONDS.toNanos(60); - /** How many frames a burst may run behind or ahead of the clock before it is moved. */ - private static final int MAX_DRIFT_FRAMES = 5; - - final String speakerId; - final String name; - - private long next = -1; - private long lastNanos; - - Track(String speakerId, String name) { - this.speakerId = speakerId; - this.name = name; - } - - /** - * @param due the frame the clock says was playing when the frame arrived - * @return where the frame goes, never before an earlier one; -1 to drop it, for a burst - * that has run too far ahead - */ - long place(long due, long nanos) { - long index; - if (next < 0 || nanos - lastNanos > BURST_GAP_NANOS) { - index = Math.max(next, due); - } else if (next - due > MAX_DRIFT_FRAMES) { - return -1; - } else { - index = due - next > MAX_DRIFT_FRAMES ? due : next; - } - next = index + 1; - lastNanos = nanos; - return index; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/recording/VoiceRecorder.java b/ts3-client/core/src/main/java/com/ts3client/recording/VoiceRecorder.java deleted file mode 100644 index 69fd4f5..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/recording/VoiceRecorder.java +++ /dev/null @@ -1,171 +0,0 @@ -package com.ts3client.recording; - -import com.ts3client.audio.VoiceFormat; -import com.ts3client.audio.opus.OpusCodec; - -import java.io.IOException; -import java.nio.file.Path; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.LongSupplier; - -/** - * Records voice into Ogg Opus: everyone mixed down onto one mono track, or every speaker - * on a channel of their own. Speakers are told apart by their unique id, so somebody who - * reconnects keeps their channel. - * - *

Frames are handed in as they are played and encoded on a thread of the recorder's - * own; {@link #offer} never blocks, so it may be called from audio threads. - */ -public final class VoiceRecorder { - - public enum Mode { - /** All speakers mixed down to mono. */ - MIXED, - /** A channel per speaker, as many files as it takes. */ - MULTITRACK - } - - private static final int FRAME = VoiceFormat.FRAME_SIZE; - private static final long FRAME_NANOS = TimeUnit.SECONDS.toNanos(FRAME) / VoiceFormat.SAMPLE_RATE; - /** How often the writer looks at the clock while nobody speaks. */ - private static final long IDLE_POLL_MILLIS = 100; - - private record Frame(String speakerId, String nickname, long nanos, float[] mono) { - } - - private record Stop(long nanos) { - } - - private final Mode mode; - private final Path file; - private final Map namesAtStart; - private final RecordingSink sink; - private final LongSupplier clock; - private final long startNanos; - private final LinkedBlockingQueue queue = new LinkedBlockingQueue<>(); - private final AtomicBoolean stopped = new AtomicBoolean(); - private final CompletableFuture> done = new CompletableFuture<>(); - /** Touched only by the writer thread. */ - private final Map tracks = new HashMap<>(); - - /** - * Starts recording into {@code file}; a multitrack recording with more speakers than one - * file holds continues into {@code name-2.ogg} and so on. - * - * @param namesAtStart nicknames by unique id of everyone present now, which name their - * channels; later arrivals are named as they first speak - */ - public static VoiceRecorder start(Mode mode, Path file, OpusCodec opus, Map namesAtStart) - throws IOException { - return start(mode, file, opus, namesAtStart, System::nanoTime); - } - - /** @param clock nanoseconds, as {@link System#nanoTime} counts them */ - static VoiceRecorder start(Mode mode, Path file, OpusCodec opus, Map namesAtStart, - LongSupplier clock) throws IOException { - RecordingSink sink = mode == Mode.MIXED ? new MixdownSink(file, opus) : new MultitrackSink(file, opus); - VoiceRecorder recorder = new VoiceRecorder(mode, file, namesAtStart, sink, clock); - Thread writer = new Thread(recorder::run, "ts3j-recorder"); - writer.setDaemon(true); - writer.start(); - return recorder; - } - - private VoiceRecorder(Mode mode, Path file, Map namesAtStart, RecordingSink sink, - LongSupplier clock) { - this.clock = clock; - this.startNanos = clock.getAsLong(); - this.mode = mode; - this.file = file; - this.namesAtStart = Map.copyOf(namesAtStart); - this.sink = sink; - } - - public Mode mode() { - return mode; - } - - public Path file() { - return file; - } - - /** - * Takes a frame a speaker is being heard with. Copied, so the caller may reuse it. - * - * @param pcm interleaved samples in [-1, 1] - * @param frames samples per channel, at most one 20 ms frame - */ - public void offer(String speakerId, String nickname, float[] pcm, int channels, int frames) { - if (stopped.get() || frames <= 0 || speakerId == null || speakerId.isEmpty()) return; - long now = clock.getAsLong(); - float[] mono = new float[FRAME]; - int n = Math.min(frames, FRAME); - if (channels == 1) { - System.arraycopy(pcm, 0, mono, 0, n); - } else { - for (int i = 0; i < n; i++) { - float sum = 0; - for (int c = 0; c < channels; c++) sum += pcm[i * channels + c]; - mono[i] = sum / channels; - } - } - queue.add(new Frame(speakerId, nickname, now, mono)); - } - - /** - * Stops recording. The files are finished on the recorder's thread, which for a long - * multitrack recording takes a moment. - * - * @return the files written, once they are; failed if the recording could not be written - */ - public CompletableFuture> stop() { - if (stopped.compareAndSet(false, true)) queue.add(new Stop(clock.getAsLong())); - return done; - } - - /** Completes when the recording ends, whether stopped or failed. */ - public CompletableFuture> whenDone() { - return done; - } - - private void run() { - try { - while (true) { - Object item = queue.poll(IDLE_POLL_MILLIS, TimeUnit.MILLISECONDS); - if (item instanceof Stop stop) { - done.complete(sink.finish(frameAt(stop.nanos()))); - return; - } - // Frames are queued in the order they were played, so a frame's own time is - // as far as the clock may be trusted while more are still queued behind it. - if (item instanceof Frame frame) { - place(frame); - sink.advance(frameAt(frame.nanos())); - } else { - sink.advance(frameAt(clock.getAsLong())); - } - } - } catch (Throwable e) { - stopped.set(true); - sink.abort(); - done.completeExceptionally(e); - } - } - - private void place(Frame frame) throws IOException { - Track track = tracks.computeIfAbsent(frame.speakerId(), id -> - new Track(id, namesAtStart.getOrDefault(id, frame.nickname()))); - long index = track.place(frameAt(frame.nanos()), frame.nanos()); - if (index >= 0) sink.write(track, index, frame.mono()); - } - - private long frameAt(long nanos) { - return Math.max(0, (nanos - startNanos) / FRAME_NANOS); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/session/SelfState.java b/ts3-client/core/src/main/java/com/ts3client/session/SelfState.java deleted file mode 100644 index 0b85907..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/session/SelfState.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.ts3client.session; - -/** - * The state of the local client on one server, as the tree shows it for any other - * client — the states are listed in the order the official client gives them - * priority, the strongest one first. - */ -public enum SelfState { - - DISCONNECTED("Not connected", null), - DEAFENED("Speakers muted", "OUTPUT_MUTED"), - MIC_MUTED("Microphone muted", "INPUT_MUTED"), - MIC_LOCAL_MUTED("Microphone locally muted", "INPUT_MUTED_LOCAL"), - AWAY("Away", "AWAY"), - COMMANDER_TALKING("Talking (channel commander)", "PLAYER_COMMANDER_ON"), - COMMANDER("Channel commander", "PLAYER_COMMANDER_OFF"), - TALKING("Talking", "PLAYER_ON"), - IDLE("Connected", "PLAYER_OFF"); - - private final String label; - private final String iconKey; - - SelfState(String label, String iconKey) { - this.label = label; - this.iconKey = iconKey; - } - - public String label() { - return label; - } - - /** The icon pack key the state is drawn with, or {@code null} for the app's own icon. */ - public String iconKey() { - return iconKey; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/session/ServerLink.java b/ts3-client/core/src/main/java/com/ts3client/session/ServerLink.java deleted file mode 100644 index c2b0b8d..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/session/ServerLink.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.ts3client.session; - -import com.ts3client.config.Bookmark; - -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.util.Locale; - -/** - * A {@code ts3server://} link, as web pages and chats hand them out: - * {@code ts3server://host[:port]?port=…&nickname=…&password=…&channel=A/B&cid=… - * &channelpassword=…&token=…&addbookmark=…}. Every parameter is optional. - */ -public final class ServerLink { - - public static final String SCHEME = "ts3server"; - private static final String PREFIX = SCHEME + "://"; - private static final int DEFAULT_PORT = 9987; - - public final String address; - public final int port; - /** Empty for the identity's or the global nickname. */ - public final String nickname; - public final String password; - /** A "/"-separated path or {@code "/"}, as {@link Bookmark#channel}; empty for the default channel. */ - public final String channel; - public final String channelPassword; - /** A privilege key to use once connected; empty for none. */ - public final String token; - /** A name to bookmark the server under, or empty when the link does not ask for a bookmark. */ - public final String bookmarkLabel; - - private ServerLink(String address, int port, String nickname, String password, String channel, - String channelPassword, String token, String bookmarkLabel) { - this.address = address; - this.port = port; - this.nickname = nickname; - this.password = password; - this.channel = channel; - this.channelPassword = channelPassword; - this.token = token; - this.bookmarkLabel = bookmarkLabel; - } - - /** Where a bookmark leads, as a link without a privilege key would. */ - public static ServerLink of(Bookmark b) { - return new ServerLink(b.address.trim(), b.port, orEmpty(b.nickname), orEmpty(b.password), orEmpty(b.channel), - orEmpty(b.channelPassword), "", ""); - } - - private static String orEmpty(String s) { - return s == null ? "" : s; - } - - public static boolean isLink(String href) { - return href != null && href.regionMatches(true, 0, PREFIX, 0, PREFIX.length()); - } - - /** Parses a link, or returns {@code null} if it is not one or names no server. */ - public static ServerLink parse(String href) { - if (!isLink(href)) return null; - String rest = href.substring(PREFIX.length()).trim(); - int query = rest.indexOf('?'); - String authority = query < 0 ? rest : rest.substring(0, query); - String params = query < 0 ? "" : rest.substring(query + 1); - int slash = authority.indexOf('/'); - if (slash >= 0) authority = authority.substring(0, slash); - - String host = authority; - int port = DEFAULT_PORT; - if (authority.startsWith("[")) { - int close = authority.indexOf(']'); - if (close < 0) return null; - host = authority.substring(1, close); - port = portAfter(authority.substring(close + 1), port); - } else if (authority.indexOf(':') == authority.lastIndexOf(':') && authority.indexOf(':') >= 0) { - host = authority.substring(0, authority.indexOf(':')); - port = portAfter(authority.substring(authority.indexOf(':')), port); - } - host = decode(host).trim(); - if (host.isEmpty()) return null; - - String nickname = "", password = "", channel = "", channelId = "", channelPassword = "", token = "", label = ""; - for (String pair : params.split("&")) { - int eq = pair.indexOf('='); - String key = (eq < 0 ? pair : pair.substring(0, eq)).toLowerCase(Locale.ROOT); - String value = eq < 0 ? "" : decode(pair.substring(eq + 1)); - switch (key) { - case "port" -> port = parsePort(value, port); - case "nickname" -> nickname = value.trim(); - case "password" -> password = value; - case "channel" -> channel = value.trim(); - case "cid" -> channelId = value.trim(); - case "channelpassword" -> channelPassword = value; - case "token" -> token = value.trim(); - case "addbookmark" -> label = value.trim(); - default -> { - } - } - } - // A channel id is exact, where a path may have been renamed since the link was made. - if (isChannelId(channelId)) channel = "/" + channelId; - return new ServerLink(host, port, nickname, password, channel, channelPassword, token, label); - } - - /** Whether this link leads to the server at {@code address}:{@code port}. */ - public boolean pointsAt(String address, int port) { - return this.port == port && address != null && this.address.equalsIgnoreCase(address.trim()); - } - - /** A bookmark of the server the link leads to, under the name it asks for, else its address. */ - public Bookmark toBookmark() { - Bookmark b = new Bookmark(bookmarkLabel.isEmpty() ? address : bookmarkLabel, address, port, nickname, password); - b.channel = channel; - b.channelPassword = channelPassword; - return b; - } - - /** A positive number; 0 names no channel. */ - private static boolean isChannelId(String s) { - return !s.isEmpty() && s.chars().allMatch(Character::isDigit) && s.chars().anyMatch(c -> c != '0'); - } - - private static int portAfter(String colonPort, int fallback) { - return colonPort.startsWith(":") ? parsePort(colonPort.substring(1), fallback) : fallback; - } - - private static int parsePort(String value, int fallback) { - try { - int port = Integer.parseInt(value.trim()); - return port > 0 && port <= 65535 ? port : fallback; - } catch (NumberFormatException e) { - return fallback; - } - } - - /** Percent-decodes; a '+' stays one, as TeamSpeak reads its links. */ - private static String decode(String s) { - try { - return URLDecoder.decode(s.replace("+", "%2B"), "UTF-8"); - } catch (UnsupportedEncodingException | IllegalArgumentException e) { - return s; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java b/ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java deleted file mode 100644 index 8e9a8d5..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java +++ /dev/null @@ -1,844 +0,0 @@ -package com.ts3client.session; - -import com.ts3client.audio.AudioBackend; -import com.ts3client.config.Bookmark; -import com.ts3client.config.IdentityEntry; -import com.ts3client.config.IdentityStore; -import com.ts3client.config.Settings; -import com.ts3client.myts.ChatAttachment; -import com.ts3client.myts.ChatAttachments; -import com.ts3client.myts.MyTsException; -import com.ts3client.contacts.ContactStore; -import com.ts3client.net.ChannelNode; -import com.ts3client.net.ClientEntry; -import com.ts3client.net.ConnectionListener; -import com.ts3client.net.ServerModel; -import com.ts3client.net.TeamspeakConnection; -import com.ts3client.net.Whisper; -import com.ts3client.recording.VoiceRecorder; -import com.ts3client.sound.SoundNotifier; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.stream.Collectors; - -/** - * One server connection and the local client's state on it, independent of any UI: the - * connection lifecycle, the microphone/speaker/away flags, chat sending and channel - * lookups. A frontend keeps one per server tab and hears from it through {@link Listener}. - * - *

Listener callbacks arrive on connection threads, so frontends marshal them onto their - * UI thread. The getters may be called from any thread. - */ -public final class ServerSession { - - /** Everything a {@link ConnectionListener} hears, plus what the session adds. */ - public interface Listener extends ConnectionListener { - - /** - * The session's title, status, connecting state or self flags changed. Also - * delivers what {@link #onStatus} does, so frontends usually only need this one. - */ - void onSessionChanged(); - - /** A line for the chat's own log: connection progress, errors, pokes. */ - void onSystemMessage(String text); - - /** - * The local client sent a chat message. - * - * @param peerClientId the recipient of a private message, else 0 - * @param peerName the recipient's display name for a private message, else empty - */ - void onOwnChat(ChatScope scope, int peerClientId, String peerName, String text); - - /** - * The server's icon is known or changed (0: it has none), and is on its way to the - * icon cache, so bookmarks leading here can show it while not connected. - */ - default void onServerIconChanged(long iconId) { - } - } - - private final Settings settings; - private final IdentityStore identities; - private final Listener listener; - private final TeamspeakConnection conn; - - private volatile String title = "New connection"; - private volatile String status = "Not connected"; - private volatile boolean connecting; - /** Identity used for the current connection, so it can be saved into a bookmark. */ - private volatile String identityId = ""; - /** How the last connect was made, for {@link #reconnect}; null before the first one. */ - private volatile Target lastTarget; - /** The channel we were in when the connection last went, to return to on a reconnect. */ - private volatile String lastChannelPath = ""; - /** The server icon last reported through {@link Listener#onServerIconChanged}; -1 for none yet. */ - private volatile long serverIconId = -1; - /** The link whose privilege key to use once connected to its server; null for none. */ - private volatile ServerLink tokenLink; - - private record Target(String address, int port, String nickname, String password, String channelPassword) { - } - - private volatile boolean micMuted; - private volatile boolean micLocalMuted; - private volatile boolean deafened; - private volatile boolean away; - /** Away message currently published, empty when away carries no message. */ - private volatile String awayMessage = ""; - private volatile boolean commander; - /** Where the microphone whispers to; null when it talks in our channel. */ - private volatile Whisper whisper; - /** {@link #whisper} as last resolved on the server, to resend only when it changes. */ - private volatile Whisper.Targets whisperTargets; - - public ServerSession(Settings settings, IdentityStore identities, AudioBackend audio, - SoundNotifier sounds, ContactStore contacts, Listener listener) { - this.settings = settings; - this.identities = identities; - this.listener = listener; - this.conn = new TeamspeakConnection(settings, audio, new Events(), sounds, contacts); - } - - public TeamspeakConnection connection() { - return conn; - } - - /** The server's name once known, the address before that. */ - public String title() { - return title; - } - - public String status() { - return status; - } - - public boolean isConnected() { - return conn.isConnected(); - } - - /** Connected or still connecting — i.e. this session is not free for a new server. */ - public boolean isBusy() { - return connecting || conn.isConnected(); - } - - public String address() { - return conn.getServerHost(); - } - - public int port() { - return conn.getServerPort(); - } - - public String identityId() { - return identityId; - } - - /** - * A bookmark leading back here: this server under its name, with the nickname, password and - * identity of the last connect, joining {@code channel}. Null before a first connect. - */ - public Bookmark toBookmark(String channel) { - Target target = lastTarget; - if (target == null) return null; - Bookmark b = new Bookmark(title, target.address(), target.port(), target.nickname(), target.password()); - b.identityId = identityId; - b.channel = channel == null ? "" : channel; - return b; - } - - // ---- connection lifecycle ---- - - /** - * @param nickname this server's own nickname, as a bookmark may name; empty for the - * identity's, else the global one - * @param identityId identity to use, or empty for the default one - * @param channel channel path to join on connect, or empty for the default channel - * @param channelPassword password for that channel, if any - */ - public void connect(String address, int port, String nickname, String password, String identityId, - String channel, String channelPassword) { - synchronized (this) { - if (isBusy()) return; - connecting = true; - } - lastTarget = new Target(address, port, nickname, password, channelPassword); - lastChannelPath = channel == null ? "" : channel; - title = address + ":" + port; - listener.onSystemMessage("Connecting to " + address + ":" + port - + (channel == null || channel.isBlank() ? "" : " (channel \"" + channel + "\")") + " …"); - setStatus("Loading identity…"); - - // Resolving may have to generate a first identity, which takes a while. - new Thread(() -> { - final IdentityEntry entry; - try { - entry = identities.resolve(settings, identityId); - } catch (Exception e) { - connecting = false; - reportError("Could not load identity: " + e.getMessage()); - return; - } - this.identityId = entry.getId(); - listener.onSystemMessage("Using identity \"" + entry.getName() + "\"."); - conn.connect(address, port, nicknameFor(nickname, entry), entry.getPhoneticNickname(), password, - entry.getIdentity(), channel, channelPassword); - }, "identity-resolve").start(); - } - - /** Whether we are on the server a {@code ts3server://} link leads to. */ - public boolean isOn(ServerLink link) { - return conn.isConnected() && link.pointsAt(address(), port()); - } - - /** Does what a link to the server we are on asks: goes to its channel, uses its privilege key. */ - public void follow(ServerLink link) { - if (!isOn(link)) return; - ChannelNode target = link.channel.isEmpty() ? null : conn.getModel().findChannelByPath(link.channel); - ChannelNode current = currentChannel(); - if (target != null && (current == null || target.id != current.id)) { - conn.joinChannel(target.id, link.channelPassword.isEmpty() ? null : link.channelPassword); - } - tokenLink = link.token.isEmpty() ? null : link; - useConnectToken(); - } - - /** Connects where a {@code ts3server://} link leads, using its privilege key once on. */ - public void open(ServerLink link, String identityId) { - tokenLink = link.token.isEmpty() ? null : link; - switchTo(link.address, link.port, link.nickname, link.password, identityId, link.channel, link.channelPassword); - } - - private String nicknameFor(String serverNickname, IdentityEntry identity) { - if (serverNickname != null && !serverNickname.isBlank()) return serverNickname.trim(); - if (!identity.getNickname().isBlank()) return identity.getNickname(); - return settings.nickname; - } - - /** - * Replaces this session's connection: leaves the server it is on, then connects to the - * new one in its place — what left-clicking a bookmark does. - */ - public void switchTo(String address, int port, String nickname, String password, String identityId, - String channel, String channelPassword) { - if (!isBusy()) { - connect(address, port, nickname, password, identityId, channel, channelPassword); - return; - } - new Thread(() -> { - // Reports the disconnect before returning, which clears the connecting flag. - conn.disconnectBlocking("Switching servers"); - connect(address, port, nickname, password, identityId, channel, channelPassword); - }, "ts3j-switch-server").start(); - } - - /** - * Connects again to the server of the last connect, with the same identity, returning to - * the channel we were in — for a connection that dropped, or a network that changed. - * Leaves the server first if still on it. Does nothing before a first connect. - */ - public void reconnect() { - Target target = lastTarget; - if (target == null) return; - String channel = conn.isConnected() ? currentChannelPath() : lastChannelPath; - switchTo(target.address(), target.port(), target.nickname(), target.password(), identityId, - channel, target.channelPassword()); - } - - /** Leaves the server, or gives up a connect that is still under way. */ - public void disconnect() { - if (isBusy()) conn.disconnect(); - } - - /** Synchronous teardown for shutdown paths, so the server sees us leave and recordings are written. */ - public void shutdown() { - CompletableFuture> recording = conn.stopRecording(false); - if (isBusy()) conn.disconnectBlocking("Leaving"); - if (recording != null) { - try { - recording.join(); - } catch (RuntimeException ignored) { - // Already reported. - } - } - } - - /** - * {@link #shutdown()}s every session at once, so leaving takes as long as the slowest - * server rather than all of them together: a frontend may have little time left. - */ - public static void shutdownAll(List sessions) { - List leaving = new ArrayList<>(); - for (ServerSession s : sessions) { - Thread t = new Thread(s::shutdown, "ts3-leave"); - t.start(); - leaving.add(t); - } - for (Thread t : leaving) { - try { - t.join(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return; - } - } - } - - /** Releases the background resources of a session that is being thrown away. */ - public void dispose() { - conn.getIcons().shutdown(); - } - - // ---- self state ---- - - public boolean isMicMuted() { - return micMuted; - } - - public boolean isMicLocalMuted() { - return micLocalMuted; - } - - public boolean isDeafened() { - return deafened; - } - - public boolean isAway() { - return away; - } - - public String awayMessage() { - return awayMessage; - } - - public boolean isCommander() { - return commander; - } - - public void setMicMuted(boolean muted) { - micMuted = muted; - conn.setMicMuted(muted); - listener.onSessionChanged(); - } - - /** TS3's "Local Mic Mute": silences capture without publishing a status change. */ - public void setMicLocalMuted(boolean muted) { - micLocalMuted = muted; - conn.setMicLocalMuted(muted); - listener.onSessionChanged(); - } - - public void setDeafened(boolean deaf) { - deafened = deaf; - conn.setDeafened(deaf); - listener.onSessionChanged(); - } - - /** - * @param message the away message, or null to keep the one already set — the - * message outlives coming back, so toggling away again restores it - */ - public void setAway(boolean away, String message) { - this.away = away; - if (message != null) this.awayMessage = message; - conn.setAway(away, awayMessage); - listener.onSessionChanged(); - } - - public void setCommander(boolean commander) { - this.commander = commander; - conn.setChannelCommander(commander); - listener.onSessionChanged(); - } - - /** Hands the capture device to (or takes it from) this connection. */ - public void setMicrophoneActive(boolean active) { - conn.setMicrophoneActive(active); - } - - public void setNickname(String nickname) { - if (conn.isConnected()) conn.setNickname(nickname); - } - - public boolean isTalkRequested() { - ClientEntry self = self(); - return conn.isConnected() && self != null && self.talkRequest; - } - - /** @param message the reason shown to moderators, may be empty */ - public void requestTalkPower(String message) { - if (conn.isConnected()) conn.setTalkRequest(true, message); - } - - public void cancelTalkRequest() { - if (conn.isConnected()) conn.setTalkRequest(false, ""); - } - - public String phoneticNickname() { - ClientEntry self = self(); - return self == null ? "" : self.phoneticNickname; - } - - /** Applies to this server only; the identity keeps its own phonetic nickname for new connections. */ - public void setPhoneticNickname(String phoneticNickname) { - if (conn.isConnected()) conn.setPhoneticNickname(phoneticNickname); - } - - // ---- whisper ---- - - public Whisper whisper() { - return whisper; - } - - /** Whispers to {@code whisper} from now on, or talks in our channel again with null. */ - public void setWhisper(Whisper whisper) { - this.whisper = whisper; - whisperTargets = null; - if (whisper == null) conn.setWhisperTargets(null); - else updateWhisperTargets(); - listener.onSessionChanged(); - } - - /** Whether whispering finds nobody there now, so nobody hears it. */ - public boolean isWhisperingToNobody() { - Whisper.Targets targets = whisperTargets; - return whisper != null && targets != null && targets.isEmpty(); - } - - /** The client who whispered to us last, to whisper back to; null when none is on. */ - public ClientEntry lastWhisperer() { - return conn.isConnected() ? conn.lastWhisperer() : null; - } - - /** Follows the whisper's channels and clients around the server. */ - private void updateWhisperTargets() { - Whisper w = whisper; - if (w == null || !conn.isConnected()) return; - Whisper.Targets targets = w.resolve(conn.getModel()); - if (targets.equals(whisperTargets)) return; - boolean wasEmpty = isWhisperingToNobody(); - whisperTargets = targets; - conn.setWhisperTargets(targets); - if (targets.isEmpty() != wasEmpty) listener.onSessionChanged(); - } - - /** What the local client looks like on this server. */ - public SelfState selfState() { - if (!conn.isConnected()) return SelfState.DISCONNECTED; - if (deafened) return SelfState.DEAFENED; - if (micMuted) return SelfState.MIC_MUTED; - if (micLocalMuted) return SelfState.MIC_LOCAL_MUTED; - if (away) return SelfState.AWAY; - ClientEntry self = self(); - boolean talking = self != null && self.talking; - if (commander) return talking ? SelfState.COMMANDER_TALKING : SelfState.COMMANDER; - return talking ? SelfState.TALKING : SelfState.IDLE; - } - - /** Clears all flags on a fresh connection; the server starts us out clean, so nothing to publish. */ - private void resetSelfState() { - micMuted = false; - micLocalMuted = false; - deafened = false; - away = false; - awayMessage = ""; - commander = false; - } - - private ClientEntry self() { - return conn.getModel().getClient(conn.getSelfClientId()); - } - - // ---- recording ---- - - public boolean isRecording() { - return conn.getRecorder() != null; - } - - /** The recording in progress, or null. */ - public VoiceRecorder.Mode recordingMode() { - VoiceRecorder rec = conn.getRecorder(); - return rec == null ? null : rec.mode(); - } - - /** A file name for a recording started now, unique within {@code dir}. */ - public Path recordingFile(Path dir) { - String server = title.replaceAll("[\\\\/:*?\"<>|\\p{Cntrl}]", "_").strip(); - String name = (server.isEmpty() ? "recording" : server) + " " - + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss")); - Path file = dir.resolve(name + ".ogg"); - for (int n = 2; Files.exists(file); n++) file = dir.resolve(name + " (" + n + ").ogg"); - return file; - } - - public void startRecording(VoiceRecorder.Mode mode, Path file) { - if (!conn.isConnected() || isRecording()) return; - VoiceRecorder rec; - try { - Path dir = file.toAbsolutePath().getParent(); - if (dir != null) Files.createDirectories(dir); - rec = conn.startRecording(mode, file); - } catch (IOException | RuntimeException e) { - listener.onSystemMessage("Failed to start recording: " + e.getMessage()); - return; - } - boolean multitrack = mode == VoiceRecorder.Mode.MULTITRACK; - listener.onSystemMessage((multitrack ? "Started multitrack recording: " : "Started recording: ") + file); - rec.whenDone().whenComplete((files, error) -> { - if (error != null) { - Throwable cause = error.getCause() != null ? error.getCause() : error; - listener.onSystemMessage("Recording failed: " + cause.getMessage()); - } else { - listener.onSystemMessage((multitrack ? "Stopped multitrack recording: " : "Stopped recording: ") - + files.stream().map(Path::toString).collect(Collectors.joining(", "))); - } - listener.onSessionChanged(); - }); - listener.onSessionChanged(); - } - - /** Stops the recording; its files are finished in the background, then reported. */ - public void stopRecording() { - if (conn.stopRecording() != null) listener.onSessionChanged(); - } - - // ---- chat ---- - - /** - * Sends a chat message and reports it back through {@link Listener#onOwnChat}. - * - * @param clientId the recipient of a private message; ignored otherwise - */ - public void sendChat(ConnectionListener.ChatScope scope, int clientId, String text) { - if (!conn.isConnected()) { - listener.onSystemMessage("Not connected."); - return; - } - switch (scope) { - case SERVER -> { - conn.sendServerMessage(text); - listener.onOwnChat(scope, 0, "", text); - } - case PRIVATE -> { - conn.sendPrivateMessage(clientId, text); - listener.onOwnChat(scope, clientId, peerName(clientId), text); - } - default -> { - conn.sendChannelMessage(text); - listener.onOwnChat(scope, 0, "", text); - } - } - } - - /** - * Shares a file in a chat as TeamSpeak 6 does: stores it in this user's myTeamSpeak - * cloud storage, then sends the message pointing to it. Runs in the background; a failure - * is reported through {@link Listener#onSystemMessage}. - * - * @param data read and closed in the background - */ - public void sendAttachment(ConnectionListener.ChatScope scope, int clientId, ChatAttachments attachments, - InputStream data, long size, String fileName) { - String room = conn.serverUniqueId(); - if (!conn.isConnected() || room == null) { - closeQuietly(data); - listener.onSystemMessage("Not connected."); - return; - } - Thread t = new Thread(() -> { - try (InputStream in = data) { - ChatAttachment attachment = attachments.upload(in, size, fileName, room); - sendChat(scope, clientId, attachment.toMessage()); - } catch (IOException | MyTsException e) { - listener.onSystemMessage("Could not share " + fileName + ": " + e.getMessage()); - } - }, "ts3-attachment-upload"); - t.setDaemon(true); - t.start(); - } - - private static void closeQuietly(InputStream in) { - try { - in.close(); - } catch (IOException ignored) { - } - } - - private String peerName(int clientId) { - ClientEntry c = conn.getModel().getClient(clientId); - return c != null ? conn.displayName(c) : "Client " + clientId; - } - - // ---- channels ---- - - /** The channel we are in, or null when not connected. */ - public ChannelNode currentChannel() { - if (!conn.isConnected()) return null; - ClientEntry self = self(); - return self == null ? null : conn.getModel().getChannel(self.channelId); - } - - /** Path of the channel we are in, or empty when not connected. */ - public String currentChannelPath() { - if (!conn.isConnected()) return ""; - ClientEntry self = self(); - return self == null ? "" : conn.getModel().channelPath(self.channelId); - } - - /** Joins the channel at a "/"-separated path, as the hotkey action names it. */ - public void joinChannelPath(String path) { - if (!conn.isConnected() || path == null || path.isBlank()) return; - ChannelNode target = conn.getModel().findChannelByPath(path); - if (target != null) conn.joinChannel(target.id, null); - } - - /** Every channel of this server as a "/"-separated path, in the tree's own order. */ - public List channelPaths() { - List out = new ArrayList<>(); - if (!conn.isConnected()) return out; - for (ChannelNode root : conn.getModel().buildTree()) collectPaths(root, out); - return out; - } - - private void collectPaths(ChannelNode channel, List out) { - out.add(conn.getModel().channelPath(channel.id)); - for (ChannelNode child : channel.children) collectPaths(child, out); - } - - // ---- permissions ---- - - /** Whether the server grants us {@code b_client_ban_list}; offered while unknown. */ - public boolean canViewBanList() { - return permits("b_client_ban_list"); - } - - /** Whether the server grants us {@code b_client_complain_list}; offered while unknown. */ - public boolean canViewComplaints() { - return permits("b_client_complain_list"); - } - - /** Whether the server grants us {@code b_virtualserver_log_view}; offered while unknown. */ - public boolean canViewServerLog() { - return permits("b_virtualserver_log_view"); - } - - /** Whether the server grants us {@code b_virtualserver_token_list}; offered while unknown. */ - public boolean canListPrivilegeKeys() { - return permits("b_virtualserver_token_list"); - } - - /** Whether the server lets us upload an avatar ({@code i_client_max_avatar_filesize}); offered while unknown. */ - public boolean canSetAvatar() { - return permits("i_client_max_avatar_filesize"); - } - - /** Whether the server lets us delete other clients' avatars; offered while unknown. */ - public boolean canDeleteOtherAvatars() { - return permits("b_client_avatar_delete_other"); - } - - private boolean permits(String permission) { - return conn.isConnected() && conn.getModel().permits(permission); - } - - /** Whether we publish an avatar on this server. */ - public boolean hasAvatar() { - if (!conn.isConnected()) return false; - ClientEntry self = conn.getModel().getClient(conn.getSelfClientId()); - return self != null && !self.avatarFlag.isEmpty(); - } - - public boolean canMoveClients() { - return hasPower("i_client_move_power"); - } - - public boolean canKickFromChannel() { - return hasPower("i_client_kick_from_channel_power"); - } - - public boolean canKickFromServer() { - return hasPower("i_client_kick_from_server_power"); - } - - public boolean canBanClients() { - return hasPower("i_client_ban_power"); - } - - public boolean canCreateChannels() { - return permitsAny("b_channel_create_temporary", "b_channel_create_semi_permanent", - "b_channel_create_permanent"); - } - - public boolean canEditChannels() { - return permitsAny("b_channel_modify_name", "b_channel_modify_topic", "b_channel_modify_description", - "b_channel_modify_password", "b_channel_modify_codec", "b_channel_modify_maxclients"); - } - - public boolean canDeleteChannels() { - return permitsAny("b_channel_delete_temporary", "b_channel_delete_semi_permanent", - "b_channel_delete_permanent"); - } - - private boolean permitsAny(String... permissions) { - if (!conn.isConnected()) return false; - for (String p : permissions) { - if (conn.getModel().permits(p)) return true; - } - return false; - } - - /** - * Whether we have any of a power; whether it beats the client's needed power only the - * server knows, so it is left to refuse. - */ - private boolean hasPower(String power) { - return conn.isConnected() && conn.getModel().selfPower(power) != 0; - } - - // ---- connection events ---- - - private void setStatus(String text) { - status = text; - listener.onStatus(text); - listener.onSessionChanged(); - } - - private void reportError(String message) { - listener.onSystemMessage("Error: " + message); - listener.onError(message); - setStatus(message); - } - - private void useConnectToken() { - ServerLink link = tokenLink; - tokenLink = null; - Target target = lastTarget; - if (link == null || target == null || !link.pointsAt(target.address(), target.port())) return; - conn.usePrivilegeKey(link.token, error -> listener.onSystemMessage(error == null - ? "Privilege key used." : "Could not use the privilege key: " + error)); - } - - private void checkServerIcon() { - if (!conn.isConnected()) return; - long id = conn.getModel().serverIconId(); - if (id == serverIconId) return; - serverIconId = id; - conn.getIcons().get(id); - listener.onServerIconChanged(id); - } - - /** Applies what a connection event means for the session, then passes it on. */ - private final class Events implements ConnectionListener { - - @Override - public void onStatus(String text) { - setStatus(text); - } - - @Override - public void onConnected() { - connecting = false; - resetSelfState(); - listener.onConnected(); - listener.onSystemMessage("Connected."); - listener.onSessionChanged(); - checkServerIcon(); - useConnectToken(); - } - - @Override - public void onDisconnected(String reason) { - connecting = false; - // Channels and clients are this server's; another one has its own. - whisper = null; - whisperTargets = null; - serverIconId = -1; - conn.getModel().clear(); - listener.onDisconnected(reason); - listener.onSystemMessage("Disconnected" + (reason == null || reason.isEmpty() ? "." : ": " + reason)); - listener.onSessionChanged(); - } - - @Override - public void onModelChanged() { - // By the time a connection is reported gone, it no longer knows where we were. - String channel = currentChannelPath(); - if (!channel.isEmpty()) lastChannelPath = channel; - String name = conn.getModel().getServerName(); - if (conn.isConnected() && name != null && !name.isBlank() && !name.equals(title)) { - title = name; - listener.onSessionChanged(); - } - checkServerIcon(); - updateWhisperTargets(); - listener.onModelChanged(); - } - - @Override - public void onInfoUpdated() { - listener.onInfoUpdated(); - } - - @Override - public void onIconsUpdated() { - listener.onIconsUpdated(); - } - - /** Passes the sender on under their contact display name. */ - @Override - public void onChat(ChatScope scope, int fromClientId, String fromUniqueId, String fromName, String message) { - String name = conn.getContacts().displayName(fromUniqueId, fromName); - listener.onChat(scope, fromClientId, fromUniqueId, name, message); - } - - @Override - public void onChatHistory(ChatScope scope, List htmlEntries) { - listener.onChatHistory(scope, htmlEntries); - } - - @Override - public void onPrivateChatHistory(int clientId, String nickname, List htmlEntries) { - listener.onPrivateChatHistory(clientId, nickname, htmlEntries); - } - - @Override - public void onTalkStateChanged(int clientId, boolean talking) { - listener.onTalkStateChanged(clientId, talking); - } - - @Override - public void onError(String message) { - reportError(message); - } - - @Override - public void onPoke(String fromName, String message) { - listener.onSystemMessage("You were poked by " + fromName + ": " + message); - listener.onPoke(fromName, message); - } - - @Override - public void onServerLog(String message) { - listener.onServerLog(message); - } - - @Override - public void onServerLogHtml(String html) { - listener.onServerLogHtml(html); - } - - @Override - public void onUnreadMessagesChanged(int unread) { - listener.onUnreadMessagesChanged(unread); - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/session/Sessions.java b/ts3-client/core/src/main/java/com/ts3client/session/Sessions.java deleted file mode 100644 index 0173277..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/session/Sessions.java +++ /dev/null @@ -1,165 +0,0 @@ -package com.ts3client.session; - -import com.ts3client.audio.VoiceInput; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * Every server the client is on, and what they share. Only one of them can capture with the - * microphone at a time, so it is handed from one to another here; the away state and the - * nickname are the user's own, so they can be set on every server at once. - * - *

Driven from one thread, the frontend's. - */ -public final class Sessions { - - private final List sessions = new ArrayList<>(); - private final Runnable onMicrophoneMoved; - private ServerSession microphoneOwner; - /** - * Opens and closes capture lines, which can block briefly, off the frontend's thread. One - * thread, so quick successive hand-overs stop and start in the order they were made. - */ - private final ExecutorService handover = Executors.newSingleThreadExecutor(r -> { - Thread t = new Thread(r, "mic-handover"); - t.setDaemon(true); - return t; - }); - - /** @param onMicrophoneMoved told whenever the microphone changes hands */ - public Sessions(Runnable onMicrophoneMoved) { - this.onMicrophoneMoved = onMicrophoneMoved; - } - - public void add(ServerSession session) { - sessions.add(session); - } - - /** Forgets a session that is being closed; the microphone moves on if it had it. */ - public void remove(ServerSession session) { - sessions.remove(session); - if (microphoneOwner == session) microphoneOwner = null; - assignMicrophoneIfFree(); - } - - public boolean anyConnected() { - for (ServerSession s : sessions) { - if (s.isConnected()) return true; - } - return false; - } - - // ---- the microphone ---- - - /** The session capturing with the microphone, or null when none is. */ - public ServerSession microphoneOwner() { - return microphoneOwner; - } - - /** Moves the microphone to {@code session}, taking it from whoever held it. */ - public void giveMicrophoneTo(ServerSession session) { - if (microphoneOwner == session) return; - ServerSession previous = microphoneOwner; - microphoneOwner = session; - handover.execute(() -> { - if (previous != null) previous.setMicrophoneActive(false); - if (session != null) session.setMicrophoneActive(true); - }); - onMicrophoneMoved.run(); - } - - /** Gives the microphone to some connected session when nobody who could use it holds it. */ - public void assignMicrophoneIfFree() { - if (microphoneOwner != null && sessions.contains(microphoneOwner) && microphoneOwner.isConnected()) return; - ServerSession previous = microphoneOwner; - microphoneOwner = null; - for (ServerSession s : sessions) { - if (s.isConnected()) { - giveMicrophoneTo(s); - return; - } - } - if (previous != null) onMicrophoneMoved.run(); - } - - public void connected(ServerSession session) { - assignMicrophoneIfFree(); - } - - /** - * A disconnected session cannot capture; the microphone moves on if it had it. The session - * lets go of it too, or a reconnect would capture alongside whoever holds it by then. - */ - public void disconnected(ServerSession session) { - if (microphoneOwner == session) { - microphoneOwner = null; - handover.execute(() -> session.setMicrophoneActive(false)); - } - assignMicrophoneIfFree(); - } - - /** Opens the microphone while push-to-talk is held. */ - public void setPushToTalk(boolean talking) { - VoiceInput mic = microphoneOf(microphoneOwner); - if (mic != null) mic.setPushToTalk(talking); - } - - /** Transmits on the server holding the microphone while held, in any input mode. */ - public void setForceTransmit(boolean talking) { - VoiceInput mic = microphoneOf(microphoneOwner); - if (mic != null) mic.setForceTransmit(talking); - } - - /** Tells every connected microphone about a key press, as TS3 tells all its connections. */ - public void keyPressed() { - for (ServerSession s : sessions) { - VoiceInput mic = microphoneOf(s); - if (mic != null) mic.keyPressed(); - } - } - - private static VoiceInput microphoneOf(ServerSession session) { - return session == null || !session.isConnected() ? null : session.connection().getMicrophone(); - } - - // ---- the user's own state ---- - - public void setAwayEverywhere(boolean away, String message) { - for (ServerSession s : sessions) { - if (s.isConnected()) s.setAway(away, message); - } - } - - /** @return true when every connected server has us away, and there is one */ - public boolean isAwayEverywhere() { - boolean any = false; - for (ServerSession s : sessions) { - if (!s.isConnected()) continue; - any = true; - if (!s.isAway()) return false; - } - return any; - } - - /** The away message to suggest: {@code preferred}'s, else any server's that has one. */ - public String awayMessage(ServerSession preferred) { - if (preferred != null && !preferred.awayMessage().isEmpty()) return preferred.awayMessage(); - for (ServerSession s : sessions) { - if (s.isConnected() && !s.awayMessage().isEmpty()) return s.awayMessage(); - } - return ""; - } - - public void setNickname(String nickname) { - for (ServerSession s : sessions) s.setNickname(nickname); - } - - /** Leaves every server, waiting until each has been told. */ - public void shutdown() { - ServerSession.shutdownAll(new ArrayList<>(sessions)); - handover.shutdown(); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/sound/NotificationSettings.java b/ts3-client/core/src/main/java/com/ts3client/sound/NotificationSettings.java deleted file mode 100644 index 1755fa9..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/sound/NotificationSettings.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.ts3client.sound; - -import java.util.EnumSet; -import java.util.Properties; -import java.util.Set; - -/** - * Per-action notification configuration: whether an action makes a sound at all, - * and whether it is important — important actions are the only ones still - * heard while the speakers are muted. - * - *

Only deviations from the defaults are persisted, so a pack gaining new events - * (or a default changing) does not need a migration. - */ -public final class NotificationSettings { - - private static final String PREFIX = "sound.event."; - private static final String ENABLED = ".enabled"; - private static final String IMPORTANT = ".important"; - - private final Set disabled = EnumSet.noneOf(SoundEvent.class); - private final Set important = EnumSet.noneOf(SoundEvent.class); - - public NotificationSettings() { - resetToDefaults(); - } - - public boolean isEnabled(SoundEvent event) { - return !disabled.contains(event); - } - - public void setEnabled(SoundEvent event, boolean enabled) { - if (enabled) disabled.remove(event); - else disabled.add(event); - } - - public boolean isImportant(SoundEvent event) { - return important.contains(event); - } - - public void setImportant(SoundEvent event, boolean value) { - if (value) important.add(event); - else important.remove(event); - } - - public void resetToDefaults() { - disabled.clear(); - important.clear(); - for (SoundEvent e : SoundEvent.values()) { - if (e.importantByDefault()) important.add(e); - if (!e.enabledByDefault()) disabled.add(e); - } - } - - public NotificationSettings copy() { - NotificationSettings copy = new NotificationSettings(); - copy.copyFrom(this); - return copy; - } - - public void copyFrom(NotificationSettings other) { - disabled.clear(); - disabled.addAll(other.disabled); - important.clear(); - important.addAll(other.important); - } - - public void load(Properties props) { - resetToDefaults(); - for (SoundEvent e : SoundEvent.values()) { - String enabled = props.getProperty(PREFIX + e.id() + ENABLED); - if (enabled != null) setEnabled(e, Boolean.parseBoolean(enabled)); - String flag = props.getProperty(PREFIX + e.id() + IMPORTANT); - if (flag != null) setImportant(e, Boolean.parseBoolean(flag)); - } - } - - public void store(Properties props) { - for (SoundEvent e : SoundEvent.values()) { - put(props, PREFIX + e.id() + ENABLED, isEnabled(e) != e.enabledByDefault(), - Boolean.toString(isEnabled(e))); - put(props, PREFIX + e.id() + IMPORTANT, isImportant(e) != e.importantByDefault(), - Boolean.toString(isImportant(e))); - } - } - - private static void put(Properties props, String key, boolean deviates, String value) { - if (deviates) props.setProperty(key, value); - else props.remove(key); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/sound/OggOpusFile.java b/ts3-client/core/src/main/java/com/ts3client/sound/OggOpusFile.java deleted file mode 100644 index 55e8cb8..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/sound/OggOpusFile.java +++ /dev/null @@ -1,148 +0,0 @@ -package com.ts3client.sound; - -import com.ts3client.audio.VoiceFormat; -import com.ts3client.audio.ogg.OggPageWriter; -import com.ts3client.audio.ogg.OpusHeaders; -import com.ts3client.audio.opus.OpusCodec; -import com.ts3client.audio.opus.OpusDecoder; -import com.ts3client.audio.opus.OpusEncoder; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Ogg Opus files (RFC 7845), the compact form of a sound pack's sounds: decoded to mono - * 48 kHz for playback, and written from it by {@link SoundPackConverter}. - */ -public final class OggOpusFile { - - public static final String EXTENSION = ".opus"; - - /** Opus always decodes at 48 kHz; 120 ms is the longest packet. */ - private static final int MAX_PACKET_SAMPLES = 5760; - private static final int FRAME_SAMPLES = VoiceFormat.FRAME_SIZE; - private static final int PRE_SKIP = OpusHeaders.LIBOPUS_PRE_SKIP; - - private OggOpusFile() { - } - - /** Decodes a file to mono samples in [-1, 1] at 48 kHz. */ - static float[] readMono(File file, OpusCodec opus) throws IOException { - List pages = pages(Files.readAllBytes(file.toPath())); - List packets = packets(pages); - if (packets.size() < 2) throw new IOException("no Opus stream"); - ByteBuffer head = ByteBuffer.wrap(packets.get(0)).order(ByteOrder.LITTLE_ENDIAN); - if (head.remaining() < 19 || !new String(packets.get(0), 0, 8, StandardCharsets.US_ASCII).equals("OpusHead")) { - throw new IOException("not an Opus stream"); - } - int channels = head.get(9) & 0xff; - int preSkip = head.getShort(10) & 0xffff; - if (channels < 1 || channels > 2) throw new IOException("unsupported channel count " + channels); - - float[] mono = new float[0]; - int length = 0; - float[] frame = new float[MAX_PACKET_SAMPLES * channels]; - try (OpusDecoder decoder = opus.createDecoder(VoiceFormat.SAMPLE_RATE, MAX_PACKET_SAMPLES, channels)) { - for (byte[] packet : packets.subList(2, packets.size())) { - int n = decoder.decode(packet, frame); - if (length + n > mono.length) mono = Arrays.copyOf(mono, Math.max(mono.length * 2, length + n)); - for (int i = 0; i < n; i++) { - float sum = 0; - for (int c = 0; c < channels; c++) sum += frame[i * channels + c]; - mono[length + i] = sum / channels; - } - length += n; - } - } - // The last page's granule position marks where the sound ends, past the padding. - long end = pages.get(pages.size() - 1).granule; - int stop = (int) Math.min(length, end >= preSkip ? end : length); - return stop <= preSkip ? new float[0] : Arrays.copyOfRange(mono, preSkip, stop); - } - - /** - * Encodes mono 48 kHz samples into a file. - * - * @param inputRate the rate the sound was recorded at, kept in the header for reference - */ - static void write(File file, float[] mono, int inputRate, OpusEncoder encoder) throws IOException { - List audio = new ArrayList<>(); - float[] frame = new float[FRAME_SAMPLES]; - // Encoded past the end by the encoder's delay, so the tail comes out whole. - int total = PRE_SKIP + mono.length; - for (int start = 0; start < total; start += FRAME_SAMPLES) { - Arrays.fill(frame, 0f); - if (start < mono.length) System.arraycopy(mono, start, frame, 0, Math.min(FRAME_SAMPLES, mono.length - start)); - audio.add(encoder.encode(frame)); - } - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - OggPageWriter ogg = new OggPageWriter(out, file.getName().hashCode()); - ogg.write(OpusHeaders.mono(PRE_SKIP, inputRate), 0); - ogg.flush(); - ogg.write(OpusHeaders.tags("ts3j", List.of()), 0); - ogg.flush(); - for (int i = 0; i < audio.size(); i++) { - // The last packet's position marks where the sound ends, short of the padding. - boolean end = i == audio.size() - 1; - ogg.write(audio.get(i), end ? total : (long) (i + 1) * FRAME_SAMPLES); - } - ogg.finish(); - Files.write(file.toPath(), out.toByteArray()); - } - - // ---- Ogg framing ---- - - private record Page(long granule, byte[] segments, byte[] data) { - } - - private static List pages(byte[] file) throws IOException { - List pages = new ArrayList<>(); - ByteBuffer in = ByteBuffer.wrap(file).order(ByteOrder.LITTLE_ENDIAN); - while (in.remaining() >= 27) { - int start = in.position(); - if (in.getInt() != 0x5367674f) throw new IOException("lost Ogg page sync"); // "OggS" - in.position(start + 6); - long granule = in.getLong(); - in.position(start + 26); - int count = in.get() & 0xff; - byte[] segments = new byte[count]; - in.get(segments); - int size = 0; - for (byte s : segments) size += s & 0xff; - if (size > in.remaining()) throw new IOException("truncated Ogg page"); - byte[] data = new byte[size]; - in.get(data); - pages.add(new Page(granule, segments, data)); - } - if (pages.isEmpty()) throw new IOException("not an Ogg file"); - return pages; - } - - /** Joins the pages' segments into packets; a packet may run on into the next page. */ - private static List packets(List pages) { - List packets = new ArrayList<>(); - ByteArrayOutputStream packet = new ByteArrayOutputStream(); - for (Page page : pages) { - int offset = 0; - for (byte segment : page.segments) { - int size = segment & 0xff; - packet.write(page.data, offset, size); - offset += size; - if (size < 255) { - packets.add(packet.toByteArray()); - packet.reset(); - } - } - } - return packets; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/sound/PackSoundPlayer.java b/ts3-client/core/src/main/java/com/ts3client/sound/PackSoundPlayer.java deleted file mode 100644 index 190bb30..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/sound/PackSoundPlayer.java +++ /dev/null @@ -1,229 +0,0 @@ -package com.ts3client.sound; - -import com.ts3client.audio.AudioIo; -import com.ts3client.audio.AudioPlayback; -import com.ts3client.audio.VoiceFormat; -import com.ts3client.audio.opus.OpusCodec; - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -/** - * Plays sound-pack files (wave or Ogg Opus) on the configured playback device. - * - *

All notification sounds share one playback line and are mixed together, so - * two events firing at once never fight over the device, and the line is dropped - * again after a long enough quiet spell. Files are decoded once, resampled to the - * device's 48 kHz and cached, so repeat events cost nothing but the mix. - */ -public final class PackSoundPlayer implements SoundPlayer { - - /** - * How long the playback line is held after the last sound. Opening it costs a - * device round-trip, which is audible as a lag before a sound the user just - * triggered, so it is kept around for a spell of quiet rather than per sound. - */ - private static final long IDLE_KEEP_OPEN_NANOS = 30_000_000_000L; - private static final long FRAME_NANOS = VoiceFormat.FRAME_SIZE * 1_000_000_000L / VoiceFormat.SAMPLE_RATE; - /** - * How far ahead of real time the mixer renders. The line would happily take a - * few hundred milliseconds at once, but anything written is fixed: a sound that - * fires while another plays can only join the mix past what is already queued, - * so the lead is kept to a couple of frames, enough to ride out scheduling jitter. - */ - private static final long LEAD_NANOS = 3 * FRAME_NANOS; - /** Sound files are small; this caps the decoded cache anyway. */ - private static final int MAX_CACHED_FILES = 64; - - /** A decoded, 48 kHz mono sound being rendered. */ - private static final class Voice { - final float[] pcm; - final double volume; - int position; - - Voice(float[] pcm, double volume) { - this.pcm = pcm; - this.volume = volume; - } - } - - private final Map cache = new LinkedHashMap<>(16, 0.75f, true) { - @Override - protected boolean removeEldestEntry(Map.Entry eldest) { - return size() > MAX_CACHED_FILES; - } - }; - - private final List voices = new ArrayList<>(); - private final Object lock = new Object(); - - private final AudioIo io; - private final OpusCodec opus; - private volatile String outputDevice; - private volatile boolean running = true; - private Thread mixer; - - public PackSoundPlayer(AudioIo io, OpusCodec opus, String outputDevice) { - this.io = io; - this.opus = opus; - this.outputDevice = outputDevice; - } - - @Override - public void setOutputDevice(String device) { - this.outputDevice = device == null ? "" : device; - } - - @Override - public void play(File file, double volume) { - if (file == null || !file.isFile() || volume <= 0) return; - float[] pcm; - try { - pcm = decode(file); - } catch (Exception e) { - return; // unplayable file: stay silent rather than break the action - } - if (pcm.length == 0) return; - - synchronized (lock) { - if (!running) return; - voices.add(new Voice(pcm, Math.min(1.0, volume))); - if (mixer == null) { - mixer = new Thread(this::mixLoop, "ts3j-sounds"); - mixer.setDaemon(true); - mixer.start(); - } - lock.notifyAll(); - } - } - - @Override - public void shutdown() { - synchronized (lock) { - running = false; - voices.clear(); - lock.notifyAll(); - } - } - - // ---- mixing ---- - - /** - * Renders the active sounds onto one line, idling (rather than writing silence) - * between them and giving the device back after {@link #IDLE_KEEP_OPEN_NANOS}. - * - *

Latency matters here because a sound is heard against the click that caused - * it: the loop idles rather than writing silence, and while rendering it paces - * itself against the clock instead of filling the line, so at any moment no more - * than {@link #LEAD_NANOS} of audio is committed and a newly fired sound starts - * right behind it. - */ - private void mixLoop() { - AudioPlayback line = null; - try { - float[] mix = new float[VoiceFormat.FRAME_SIZE]; - long due = 0; // when the next frame is due to leave the speaker - while (awaitVoices()) { - if (line == null) { - line = io.openPlayback(outputDevice, VoiceFormat.MAX_CHANNELS); - line.start(); - } - long now = System.nanoTime(); - if (due < now) { - due = now; // fresh start or fell behind: resync - } else if (due - now > LEAD_NANOS) { - Thread.sleep((due - now - LEAD_NANOS) / 1_000_000L); - } - due += FRAME_NANOS; - renderFrame(mix); - line.write(toBytes(mix, line.channels()), 0, mix.length * 2 * line.channels()); - } - } catch (Exception e) { - synchronized (lock) { - voices.clear(); - mixer = null; - } - } finally { - if (line != null) line.close(); - } - } - - /** - * Blocks until there is something to render. - * - * @return false when the idle timeout expired or the player was shut down, in - * which case this thread is done and {@link #play} will start a fresh one - */ - private boolean awaitVoices() throws InterruptedException { - synchronized (lock) { - long deadline = System.nanoTime() + IDLE_KEEP_OPEN_NANOS; - while (running && voices.isEmpty()) { - long remaining = deadline - System.nanoTime(); - if (remaining <= 0) break; - lock.wait(Math.max(1, remaining / 1_000_000L)); - } - if (running && !voices.isEmpty()) return true; - mixer = null; - return false; - } - } - - /** Sums the active sounds into {@code mix}, dropping the ones that ran out. */ - private void renderFrame(float[] mix) { - Arrays.fill(mix, 0f); - synchronized (lock) { - for (Iterator it = voices.iterator(); it.hasNext(); ) { - Voice v = it.next(); - int n = Math.min(mix.length, v.pcm.length - v.position); - for (int i = 0; i < n; i++) { - mix[i] += v.pcm[v.position + i] * v.volume; - } - v.position += n; - if (v.position >= v.pcm.length) it.remove(); - } - } - } - - /** Interleaves the mono mix across the line's channels as signed 16-bit LE. */ - private static byte[] toBytes(float[] mix, int channels) { - byte[] out = new byte[mix.length * 2 * channels]; - for (int i = 0, k = 0; i < mix.length; i++) { - float v = Math.max(-1f, Math.min(1f, mix[i])); - short s = (short) Math.round(v * 32767.0); - for (int c = 0; c < channels; c++, k += 2) { - out[k] = (byte) (s & 0xFF); - out[k + 1] = (byte) ((s >> 8) & 0xFF); - } - } - return out; - } - - // ---- decoding ---- - - private float[] decode(File file) throws Exception { - String key = file.getAbsolutePath() + '@' + file.lastModified(); - synchronized (cache) { - float[] cached = cache.get(key); - if (cached != null) return cached; - } - float[] pcm = readMono48k(file); - synchronized (cache) { - cache.put(key, pcm); - } - return pcm; - } - - /** Decodes a sound file to mono 48 kHz float samples. */ - private float[] readMono48k(File file) throws Exception { - if (file.getName().toLowerCase(Locale.ROOT).endsWith(OggOpusFile.EXTENSION)) { - return OggOpusFile.readMono(file, opus); - } - return WaveFile.readMono(file).at48k(); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/sound/SoundEvent.java b/ts3-client/core/src/main/java/com/ts3client/sound/SoundEvent.java deleted file mode 100644 index 19006a9..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/sound/SoundEvent.java +++ /dev/null @@ -1,220 +0,0 @@ -package com.ts3client.sound; - -/** - * The catalogue of actions a sound pack can react to, using TeamSpeak's own event - * ids so the packs shipped with the official client (and third-party ones) load - * unchanged — see {@link SoundPack}. - * - *

Events are grouped for display and each carries a default "important" flag: - * important sounds are the only ones still played while the speakers are muted - * (see {@link SoundNotifier}). The user can change both the flag and whether an - * event makes a sound at all; that lives in {@link NotificationSettings}. - */ -public enum SoundEvent { - - // ---- connection ---- - CONNECTION_CONNECTED(Category.CONNECTION, "Connection established"), - CONNECTION_DISCONNECTED(Category.CONNECTION, "Disconnected"), - CONNECTION_LOST_CONNECTION(Category.CONNECTION, "Connection lost", true), - - // ---- notifications aimed at us ---- - OTHER_RECEIVED_POKE(Category.OTHER, "You were poked", true), - OTHER_SENT_POKE(Category.OTHER, "You poked someone"), - OTHER_FILETRANSFER_COMPLETE(Category.OTHER, "File transfer complete"), - OTHER_FILETRANSFER_FAILED(Category.OTHER, "File transfer failed", true), - OTHER_WHISPERLIST_EMPTY(Category.OTHER, "Whisper list is empty"), - OTHER_WHISPERTARGET_NOT_FOUND(Category.OTHER, "Whisper target not found"), - OTHER_WHISPERTARGET_TOO_MANY(Category.OTHER, "Too many whisper targets"), - SPECIAL_WHISPER_NOTIFY(Category.OTHER, "Whisper received", true), - - // ---- microphone / test sounds ---- - SPECIAL_MIC_CLICK_SELF_ON(Category.SPECIAL, "Mic clicks self on", false, false), - SPECIAL_MIC_CLICK_SELF_OFF(Category.SPECIAL, "Mic clicks self off", false, false), - SPECIAL_MIC_CLICK_OTHER_ON(Category.SPECIAL, "Mic clicks other on", false, false), - SPECIAL_MIC_CLICK_OTHER_OFF(Category.SPECIAL, "Mic clicks other off", false, false), - SPECIAL_TALKING_WHILE_MUTED(Category.SPECIAL, "Talking while muted", true), - SPECIAL_SOUND_TEST(Category.SPECIAL, "Playback test sound"), - SPECIAL_3D_TEST(Category.SPECIAL, "3D sound test"), - - // ---- channels ---- - CHANNEL_CREATED_BY_YOU(Category.CHANNEL, "Created by you"), - CHANNEL_CREATED_BY_OTHER(Category.CHANNEL, "Created by other"), - CHANNEL_DELETED_BY_YOU(Category.CHANNEL, "Deleted by you"), - CHANNEL_DELETED_BY_OTHER(Category.CHANNEL, "Deleted by other"), - CHANNEL_DELETED_BY_SERVER(Category.CHANNEL, "Deleted by the server"), - CHANNEL_EDITED_CURRENT_BY_YOU(Category.CHANNEL, "Your channel edited by you"), - CHANNEL_EDITED_CURRENT_BY_OTHER(Category.CHANNEL, "Your channel edited by other"), - CHANNEL_EDITED_OTHER_BY_YOU(Category.CHANNEL, "Other channel edited by you"), - CHANNEL_EDITED_OTHER_BY_OTHER(Category.CHANNEL, "Other channel edited by other"), - CHANNEL_EDITED_OTHER_BY_SERVER(Category.CHANNEL, "Other channel edited by the server"), - CHANNEL_MOVED_BY_YOU(Category.CHANNEL, "Moved by you"), - CHANNEL_MOVED_BY_OTHER(Category.CHANNEL, "Moved by other"), - - // ---- server ---- - SERVER_EDITED_BY_YOU(Category.SERVER, "Edited by you"), - SERVER_EDITED_BY_OTHER(Category.SERVER, "Edited by other"), - SERVER_INSUFFICIENT_PERMISSIONS(Category.SERVER, "Insufficient permissions", true), - SERVER_ERROR(Category.SERVER, "Server error", true), - - // ---- other clients ---- - CLIENT_CONNECTION_CONNECTED_SERVER(Category.CLIENT, "Connected to server"), - CLIENT_CONNECTION_CONNECTED_CURRENT_CHANNEL(Category.CLIENT, "Connected to current channel"), - CLIENT_CONNECTION_DISCONNECTED_SERVER(Category.CLIENT, "Disconnected from server"), - CLIENT_CONNECTION_DISCONNECTED_CURRENT_CHANNEL(Category.CLIENT, "Disconnected from current channel"), - CLIENT_CONNECTION_LOST_CONNECTION_SERVER(Category.CLIENT, "Lost connection to server"), - CLIENT_CONNECTION_LOST_CONNECTION_CURRENT_CHANNEL(Category.CLIENT, "Lost connection in current channel"), - CLIENT_SWITCHED_TO_CURRENT_CHANNEL_APPEARS(Category.CLIENT, "Switched to current channel, appears"), - CLIENT_SWITCHED_TO_CURRENT_CHANNEL_STAYS(Category.CLIENT, "Switched to current channel, stays"), - CLIENT_SWITCHED_FROM_CURRENT_CHANNEL_DISAPPEARS(Category.CLIENT, "Switched away from current channel, disappears"), - CLIENT_SWITCHED_FROM_CURRENT_CHANNEL_STAYS(Category.CLIENT, "Switched away from current channel, stays"), - CLIENT_SWITCHED_TO_OTHER_CHANNEL_APPEARS(Category.CLIENT, "Switched to different channel, appears"), - CLIENT_SWITCHED_TO_OTHER_CHANNEL_DISAPPEARS(Category.CLIENT, "Switched to different channel, disappears"), - CLIENT_SWITCHED_TO_OTHER_CHANNEL_STAYS(Category.CLIENT, "Switched to different channel, stays"), - CLIENT_MOVED_TO_CURRENT_CHANNEL_APPEARS(Category.CLIENT, "Moved to current channel, appears"), - CLIENT_MOVED_TO_CURRENT_CHANNEL_STAYS(Category.CLIENT, "Moved to current channel, stays"), - CLIENT_MOVED_FROM_CURRENT_CHANNEL_DISAPPEARS(Category.CLIENT, "Moved away from current channel, disappears"), - CLIENT_MOVED_FROM_CURRENT_CHANNEL_STAYS(Category.CLIENT, "Moved away from current channel, stays"), - CLIENT_MOVED_TO_OTHER_CHANNEL_APPEARS(Category.CLIENT, "Moved to different channel, appears"), - CLIENT_MOVED_TO_OTHER_CHANNEL_DISAPPEARS(Category.CLIENT, "Moved to different channel, disappears"), - CLIENT_MOVED_TO_OTHER_CHANNEL_STAYS(Category.CLIENT, "Moved to different channel, stays"), - CLIENT_RENAMED_BY_YOU(Category.CLIENT, "Renamed by you"), - CLIENT_RENAMED_BY_OTHER(Category.CLIENT, "Renamed by other"), - CLIENT_WAS_KICKED_FROM_CHANNEL_TO_CURRENT_CHANNEL_APPEARS(Category.CLIENT, - "Kicked from channel to current channel, appears"), - CLIENT_WAS_KICKED_FROM_CHANNEL_TO_CURRENT_CHANNEL_STAYS(Category.CLIENT, - "Kicked from channel to current channel, stays"), - CLIENT_WAS_KICKED_FROM_CHANNEL_FROM_CURRENT_CHANNEL_DISAPPEARS(Category.CLIENT, - "Kicked away from current channel, disappears"), - CLIENT_WAS_KICKED_FROM_CHANNEL_FROM_CURRENT_CHANNEL_STAYS(Category.CLIENT, - "Kicked away from current channel, stays"), - CLIENT_WAS_KICKED_FROM_CHANNEL_TO_OTHER_CHANNEL_APPEARS(Category.CLIENT, - "Kicked from channel to different channel, appears"), - CLIENT_WAS_KICKED_FROM_CHANNEL_TO_OTHER_CHANNEL_DISAPPEARS(Category.CLIENT, - "Kicked from channel to different channel, disappears"), - CLIENT_WAS_KICKED_FROM_CHANNEL_TO_OTHER_CHANNEL_STAYS(Category.CLIENT, - "Kicked from channel to different channel, stays"), - CLIENT_WAS_KICKED_FROM_SERVER_SERVER(Category.CLIENT, "Kicked from server"), - CLIENT_WAS_KICKED_FROM_SERVER_CURRENT_CHANNEL(Category.CLIENT, "Kicked from server, from current channel"), - CLIENT_WAS_BANNED_SERVER(Category.CLIENT, "Banned from server"), - CLIENT_WAS_BANNED_CURRENT_CHANNEL(Category.CLIENT, "Banned from server, from current channel"), - CLIENT_SERVERGROUP_ADDED_BY_SERVER(Category.CLIENT, "Server group assigned by the server"), - CLIENT_SERVERGROUP_ADDED_BY_USER(Category.CLIENT, "Server group assigned by other"), - CLIENT_SERVERGROUP_REMOVED_BY_SERVER(Category.CLIENT, "Server group revoked by the server"), - CLIENT_SERVERGROUP_REMOVED_BY_USER(Category.CLIENT, "Server group revoked by other"), - CLIENT_CHANNELGROUP_CHANGED_BY_SERVER(Category.CLIENT, "Channel group changed by the server"), - CLIENT_CHANNELGROUP_CHANGED_BY_USER(Category.CLIENT, "Channel group changed by other"), - CLIENT_RECORDING_START(Category.CLIENT, "Starts recording"), - CLIENT_RECORDING_STOP(Category.CLIENT, "Stops recording"), - CLIENT_RECORDING_IN_CHANNEL(Category.CLIENT, "Is recording in current channel"), - CLIENT_REQUESTED_TALK_POWER(Category.CLIENT, "Talk power requested"), - - // ---- ourselves ---- - YOU_SWITCHED_CHANNEL(Category.SELF, "You switched channel"), - YOU_WERE_MOVED_TO_DIFFERENT_CHANNEL(Category.SELF, "You were moved", true), - YOU_WERE_KICKED_FROM_CHANNEL(Category.SELF, "You were kicked from channel", true), - YOU_WERE_KICKED_FROM_SERVER(Category.SELF, "You were kicked from server", true), - YOU_WERE_BANNED(Category.SELF, "You were banned", true), - YOU_WERE_GRANTED_TALK_POWER(Category.SELF, "Talk power granted", true), - YOU_WERE_REVOKED_TALK_POWER(Category.SELF, "Talk power revoked", true), - YOU_SERVERGROUP_ADDED_BY_SERVER(Category.SELF, "Server group assigned by the server"), - YOU_SERVERGROUP_ADDED_BY_USER(Category.SELF, "Server group assigned by other"), - YOU_SERVERGROUP_REMOVED_BY_SERVER(Category.SELF, "Server group revoked by the server"), - YOU_SERVERGROUP_REMOVED_BY_USER(Category.SELF, "Server group revoked by other"), - YOU_CHANNELGROUP_CHANGED_BY_SERVER(Category.SELF, "Channel group changed by the server"), - YOU_CHANNELGROUP_CHANGED_BY_USER(Category.SELF, "Channel group changed by other"), - - // ---- chat ---- - CHAT_SENT_MESSAGE_CLIENT(Category.CHAT, "You sent a client message"), - CHAT_SENT_MESSAGE_CHANNEL(Category.CHAT, "You sent a channel message"), - CHAT_SENT_MESSAGE_SERVER(Category.CHAT, "You sent a server message"), - CHAT_RECEIVED_MESSAGE_CLIENT(Category.CHAT, "You received a client message", true), - CHAT_RECEIVED_MESSAGE_CHANNEL(Category.CHAT, "You received a channel message"), - CHAT_RECEIVED_MESSAGE_SERVER(Category.CHAT, "You received a server message"), - - // ---- status ---- - SOUND_CAPTURE_MUTED(Category.STATUS, "Microphone muted", true), - SOUND_CAPTURE_UNMUTED(Category.STATUS, "Microphone activated", true), - SOUND_PLAYBACK_MUTED(Category.STATUS, "Sound muted", true), - SOUND_PLAYBACK_UNMUTED(Category.STATUS, "Sound resumed", true), - STATUS_SET_AWAY(Category.STATUS, "Set to away"), - STATUS_SET_PRESENT(Category.STATUS, "Set to present"); - - /** Display grouping, mirroring the sections of TeamSpeak's notification list. */ - public enum Category { - CONNECTION("Connection"), - OTHER("Notifications"), - SPECIAL("Microphone & tests"), - CHANNEL("Channel"), - SERVER("Server"), - CLIENT("Clients"), - SELF("Yourself"), - CHAT("Chat"), - STATUS("Status"); - - private final String label; - - Category(String label) { - this.label = label; - } - - public String label() { - return label; - } - } - - private final Category category; - private final String label; - private final boolean importantByDefault; - private final boolean enabledByDefault; - - SoundEvent(Category category, String label) { - this(category, label, false, true); - } - - SoundEvent(Category category, String label, boolean importantByDefault) { - this(category, label, importantByDefault, true); - } - - SoundEvent(Category category, String label, boolean importantByDefault, boolean enabledByDefault) { - this.category = category; - this.label = label; - this.importantByDefault = importantByDefault; - this.enabledByDefault = enabledByDefault; - } - - /** The key used in a sound pack's {@code settings.ini}; identical to {@link #name()}. */ - public String id() { - return name(); - } - - public Category category() { - return category; - } - - public String label() { - return label; - } - - /** Whether this action counts as important until the user says otherwise. */ - public boolean importantByDefault() { - return importantByDefault; - } - - /** - * Whether the action makes a sound out of the box. The mic clicks are mapped by - * most packs but off by default, as they are in the official client. - */ - public boolean enabledByDefault() { - return enabledByDefault; - } - - /** @return the event with this pack key, or {@code null} for an unknown one */ - public static SoundEvent byId(String id) { - if (id == null) return null; - try { - return valueOf(id.trim().toUpperCase(java.util.Locale.ROOT)); - } catch (IllegalArgumentException e) { - return null; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/sound/SoundNotifier.java b/ts3-client/core/src/main/java/com/ts3client/sound/SoundNotifier.java deleted file mode 100644 index 397083e..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/sound/SoundNotifier.java +++ /dev/null @@ -1,165 +0,0 @@ -package com.ts3client.sound; - -import com.ts3client.config.AppDirs; -import com.ts3client.config.Settings; - -import java.io.File; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Plays the sound a {@link SoundPack} assigns to an action, honouring the user's - * per-action configuration. - * - *

An action is heard when the pack maps it, the user left it enabled and either - * the speakers are on or the action is marked important — the muted case - * is what the important flag exists for. - * - *

A sound that is already starting is not started again: one server action often - * arrives as a burst of events (a channel deleted with its subchannels, every tab on - * the same server hearing the same move), and stacking identical copies of a sound - * only makes it louder and garbled. - */ -public final class SoundNotifier { - - /** Contact class in a pack's {@code ${clientType}} placeholder: friend, neutral or blocked. */ - private static final String DEFAULT_CLIENT_TYPE = "neutral"; - - /** How close together two plays of the same sound count as one. */ - private static final long COALESCE_NANOS = 250_000_000L; - - private final Settings settings; - private volatile SoundPlayer player; - private volatile SoundPack pack; - private volatile List available = List.of(); - private volatile boolean soundsMuted; - /** When each resolved sound last started, for {@link #COALESCE_NANOS}. */ - private final Map lastStarted = new HashMap<>(); - - public SoundNotifier(Settings settings) { - this.settings = settings; - reload(); - } - - /** Attaches the platform's player; without one the notifier stays silent. */ - public void setPlayer(SoundPlayer player) { - this.player = player; - } - - /** Re-scans the installed packs and selects the configured one. */ - public void reload() { - available = SoundPacks.findAll(new File(AppDirs.profile(), "sound"), settings.soundPackDir); - pack = SoundPacks.select(available, settings.soundPack); - } - - public List availablePacks() { - return available; - } - - public SoundPack pack() { - return pack; - } - - /** Switches packs and remembers the choice in the settings. */ - public void setPack(SoundPack pack) { - this.pack = pack; - settings.soundPack = pack == null ? "" : pack.id(); - } - - /** - * Silences every notification sound until turned back on — TS3's "Mute Sounds" - * hotkey action. Unlike deafening, this is not tied to a server and even important - * actions stay quiet. - */ - public void setMuted(boolean muted) { - this.soundsMuted = muted; - } - - public boolean isMuted() { - return soundsMuted; - } - - /** - * Plays the sound for an action. - * - * @param muted whether playback is currently muted, in which case only actions - * marked important are heard - */ - public void fire(SoundEvent event, boolean muted) { - fire(event, muted, null); - } - - /** - * @param variables values for the pack's {@code ${...}} placeholders, e.g. - * {@code clientname} or {@code channelname} - */ - public void fire(SoundEvent event, boolean muted, Map variables) { - if (soundsMuted) return; - NotificationSettings notifications = settings.notifications; - if (!notifications.isEnabled(event)) return; - if (muted && !notifications.isImportant(event)) return; - render(event, variables); - } - - /** Plays an action's sound regardless of its configuration, for the options dialog. */ - public void preview(SoundEvent event) { - render(event, null); - } - - /** Whether the current pack would make any sound for this action. */ - public boolean hasSound(SoundEvent event) { - SoundPack p = pack; - if (p == null) return false; - SoundScript script = p.script(event); - if (script == null) return false; - return script.kind() != SoundScript.Kind.SAY || (player != null && player.canSpeak()); - } - - private void render(SoundEvent event, Map variables) { - SoundPack p = pack; - SoundPlayer out = player; - if (p == null || out == null) return; - SoundScript script = p.script(event); - if (script == null) return; - - String resolved = script.resolve(withDefaults(variables)); - double volume = Math.max(0, Math.min(1.0, settings.effectiveSoundVolume())); - if (volume <= 0) return; - if (!claimStart(script.kind() + ":" + resolved)) return; - - if (script.kind() == SoundScript.Kind.SAY) { - out.say(resolved, volume); - return; - } - File file = p.file(resolved); - if (file != null) out.play(file, volume); - } - - /** @return false when the same sound already started within {@link #COALESCE_NANOS} */ - private boolean claimStart(String sound) { - long now = System.nanoTime(); - synchronized (lastStarted) { - Long last = lastStarted.get(sound); - if (last != null && now - last < COALESCE_NANOS) return false; - lastStarted.put(sound, now); - if (lastStarted.size() > 64) lastStarted.values().removeIf(t -> now - t >= COALESCE_NANOS); - } - return true; - } - - private static Map withDefaults(Map variables) { - Map vars = variables == null ? new HashMap<>() : new HashMap<>(variables); - vars.putIfAbsent("clientType", DEFAULT_CLIENT_TYPE); - return vars; - } - - /** Builds a variable map from alternating name/value pairs. */ - public static Map vars(String... nameValuePairs) { - Map vars = new HashMap<>(); - for (int i = 0; i + 1 < nameValuePairs.length; i += 2) { - vars.put(nameValuePairs[i], nameValuePairs[i + 1] == null ? "" : nameValuePairs[i + 1]); - } - return vars; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/sound/SoundPack.java b/ts3-client/core/src/main/java/com/ts3client/sound/SoundPack.java deleted file mode 100644 index b05d9f9..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/sound/SoundPack.java +++ /dev/null @@ -1,167 +0,0 @@ -package com.ts3client.sound; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.EnumMap; -import java.util.Locale; -import java.util.Map; - -/** - * A TeamSpeak sound pack: a directory of wave files plus a {@code settings.ini} - * mapping {@link SoundEvent}s to {@link SoundScript}s. - * - *

The format is TeamSpeak's, so the packs shipped with the official client - * (and the ones on its add-on site) can be used as they are: - * - *

- * [info]
- * name    = Default Sound Pack (Female)
- * version = 1.0
- * author  = TeamSpeak Systems GmbH
- *
- * [soundfiles]
- * CONNECTION_CONNECTED = play("connected.wav")
- * CLIENT_MOVED_TO_CURRENT_CHANNEL_STAYS = play("${clientType}_moved_tocurrentchannel.wav")
- * CHANNEL_CREATED_BY_OTHER =
- * 
- */ -public final class SoundPack { - - private static final String INI = "settings.ini"; - - private final String id; - private final File directory; - private final String name; - private final String version; - private final String author; - private final Map scripts; - - private SoundPack(String id, File directory, String name, String version, String author, - Map scripts) { - this.id = id; - this.directory = directory; - this.name = name; - this.version = version; - this.author = author; - this.scripts = scripts; - } - - /** Stable identifier used in the settings: the pack's directory name. */ - public String id() { - return id; - } - - public File directory() { - return directory; - } - - public String name() { - return name; - } - - public String version() { - return version; - } - - public String author() { - return author; - } - - /** @return what this pack does for the event, or {@code null} when it stays silent */ - public SoundScript script(SoundEvent event) { - return scripts.get(event); - } - - /** - * Resolves the wave file for a {@code play(...)} script. Pack authors write the - * names as they appear on their (often case-insensitive) file system, so a - * mismatched case is retried against the directory listing. A pack whose sounds - * were converted to Opus keeps its scripts: {@code x.wav} is found as {@code x.opus}. - * - * @return the file, or {@code null} if the pack does not contain it - */ - public File file(String fileName) { - if (fileName == null || fileName.isEmpty()) return null; - File found = find(fileName); - if (found == null && fileName.regionMatches(true, fileName.length() - 4, ".wav", 0, 4)) { - found = find(fileName.substring(0, fileName.length() - 4) + OggOpusFile.EXTENSION); - } - return found; - } - - private File find(String fileName) { - File direct = new File(directory, fileName); - if (direct.isFile()) return direct; - - File[] entries = directory.listFiles(); - if (entries != null) { - for (File f : entries) { - if (f.isFile() && f.getName().equalsIgnoreCase(fileName)) return f; - } - } - return null; - } - - @Override - public String toString() { - return name; - } - - /** - * Reads a pack from a directory holding a {@code settings.ini}. - * - * @return the pack, or {@code null} when the directory is not one - */ - public static SoundPack load(File directory) { - if (directory == null || !directory.isDirectory()) return null; - File ini = new File(directory, INI); - if (!ini.isFile()) { - File[] entries = directory.listFiles(); - if (entries != null) { - for (File f : entries) { - if (f.isFile() && f.getName().equalsIgnoreCase(INI)) ini = f; - } - } - if (!ini.isFile()) return null; - } - - Map scripts = new EnumMap<>(SoundEvent.class); - Map info = new java.util.HashMap<>(); - try (BufferedReader in = new BufferedReader( - new InputStreamReader(Files.newInputStream(ini.toPath()), StandardCharsets.UTF_8))) { - String section = ""; - String line; - while ((line = in.readLine()) != null) { - String trimmed = line.trim(); - if (trimmed.isEmpty() || trimmed.startsWith("#") || trimmed.startsWith(";")) continue; - if (trimmed.startsWith("[") && trimmed.endsWith("]")) { - section = trimmed.substring(1, trimmed.length() - 1).trim().toLowerCase(Locale.ROOT); - continue; - } - int eq = trimmed.indexOf('='); - if (eq < 0) continue; - String key = trimmed.substring(0, eq).trim(); - String value = trimmed.substring(eq + 1).trim(); - - if ("info".equals(section)) { - info.put(key.toLowerCase(Locale.ROOT), value); - continue; - } - SoundEvent event = SoundEvent.byId(key); - SoundScript script = SoundScript.parse(value); - if (event != null && script != null) scripts.put(event, script); - } - } catch (IOException e) { - return null; - } - - String id = directory.getName(); - String name = info.getOrDefault("name", id); - return new SoundPack(id, directory, name, - info.getOrDefault("version", ""), info.getOrDefault("author", ""), scripts); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/sound/SoundPackConverter.java b/ts3-client/core/src/main/java/com/ts3client/sound/SoundPackConverter.java deleted file mode 100644 index 2ea293a..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/sound/SoundPackConverter.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.ts3client.sound; - -import com.ts3client.audio.VoiceFormat; -import com.ts3client.audio.opus.OpusCodec; -import com.ts3client.audio.opus.OpusEncoder; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.StandardCopyOption; -import java.util.Locale; - -/** - * Copies sound packs with their wave files encoded as Ogg Opus, about a fifteenth of - * the size. The scripts are left as they are: {@link SoundPack#file} finds a pack's - * {@code x.wav} as {@code x.opus}. - */ -public final class SoundPackConverter { - - /** Clear of any audible difference for notification sounds, at a fifteenth of the WAVs' size. */ - public static final int BITRATE = 64_000; - - private SoundPackConverter() { - } - - /** Converts every file under {@code source} into the same place under {@code target}. */ - public static void convert(File source, File target, OpusCodec opus) throws IOException { - File[] entries = source.listFiles(); - if (entries == null) throw new IOException("Cannot list " + source); - Files.createDirectories(target.toPath()); - for (File entry : entries) { - String name = entry.getName(); - if (entry.isDirectory()) { - convert(entry, new File(target, name), opus); - } else if (name.toLowerCase(Locale.ROOT).endsWith(".wav")) { - File out = new File(target, name.substring(0, name.length() - 4) + OggOpusFile.EXTENSION); - encode(entry, out, opus); - } else { - Files.copy(entry.toPath(), new File(target, name).toPath(), StandardCopyOption.REPLACE_EXISTING); - } - } - } - - private static void encode(File wave, File out, OpusCodec opus) throws IOException { - WaveFile.Audio audio = WaveFile.readMono(wave); - try (OpusEncoder encoder = opus.createEncoder(VoiceFormat.SAMPLE_RATE, VoiceFormat.FRAME_SIZE, 1, - OpusCodec.Application.AUDIO)) { - encoder.setBitrate(BITRATE); - encoder.setVbr(true); - encoder.setComplexity(10); - OggOpusFile.write(out, audio.at48k(), audio.sampleRate(), encoder); - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/sound/SoundPacks.java b/ts3-client/core/src/main/java/com/ts3client/sound/SoundPacks.java deleted file mode 100644 index 021d0eb..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/sound/SoundPacks.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.ts3client.sound; - -import com.ts3client.config.InstallDirs; - -import java.io.File; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * Finds the sound packs installed on this machine: the client's own - * {@code sound/} folder, an extra folder the user configured, and the - * {@code sound/} folder of an installed TeamSpeak 3 client (whose packs are - * usable as they are, see {@link SoundPack}). - */ -public final class SoundPacks { - - private SoundPacks() { - } - - /** - * Loads every pack found under {@code extraDirectory} and the well-known - * locations, newest search root winning on a name clash. - * - * @param userDirectory the client's own pack folder (may not exist yet) - * @param extraDirectory an additional folder chosen by the user, or {@code null} - * @return the packs, ordered by display name - */ - public static List findAll(File userDirectory, String extraDirectory) { - Map byId = new LinkedHashMap<>(); - for (File root : InstallDirs.searchRoots("sound", userDirectory, extraDirectory)) { - File[] entries = root.listFiles(File::isDirectory); - if (entries == null) continue; - for (File dir : entries) { - SoundPack pack = SoundPack.load(dir); - if (pack != null) byId.putIfAbsent(pack.id(), pack); - } - } - List packs = new ArrayList<>(byId.values()); - packs.sort(Comparator.comparing(p -> p.name().toLowerCase(java.util.Locale.ROOT))); - return packs; - } - - /** @return the pack with this id, or the first one available, or {@code null} */ - public static SoundPack select(List packs, String id) { - for (SoundPack p : packs) { - if (p.id().equals(id)) return p; - } - return packs.isEmpty() ? null : packs.get(0); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/sound/SoundPlayer.java b/ts3-client/core/src/main/java/com/ts3client/sound/SoundPlayer.java deleted file mode 100644 index 11e3e14..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/sound/SoundPlayer.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.ts3client.sound; - -import java.io.File; - -/** - * Renders notification sounds. Kept separate from the voice pipeline so the core - * stays free of any concrete audio stack; the desktop frontend supplies an - * implementation that mixes onto the configured playback device. - */ -public interface SoundPlayer { - - /** - * Plays a wave file, mixing it with anything already playing. - * - * @param volume linear gain, 0..1 - */ - void play(File file, double volume); - - /** Speaks a sentence from a text-to-speech pack; a no-op where TTS is unavailable. */ - default void say(String text, double volume) { - } - - /** Whether {@link #say} actually produces sound on this platform. */ - default boolean canSpeak() { - return false; - } - - /** Follows the playback device selected in the options. */ - default void setOutputDevice(String device) { - } - - void shutdown(); -} diff --git a/ts3-client/core/src/main/java/com/ts3client/sound/SoundScript.java b/ts3-client/core/src/main/java/com/ts3client/sound/SoundScript.java deleted file mode 100644 index b418d8d..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/sound/SoundScript.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.ts3client.sound; - -import java.util.Map; - -/** - * One action from a sound pack: either {@code play("file.wav")} or - * {@code say("some text")}, with TeamSpeak's {@code ${variable}} placeholders - * still in place until {@link #resolve(Map)} fills them in. - */ -public record SoundScript(Kind kind, String argument) { - - public enum Kind { - /** Play a wave file from the pack's directory. */ - PLAY, - /** Speak a sentence (text-to-speech packs). */ - SAY - } - - /** - * Parses the right-hand side of a {@code settings.ini} entry. - * - * @return the script, or {@code null} for an empty value (the pack stays silent - * for that event) or one whose function we don't know - */ - public static SoundScript parse(String value) { - if (value == null) return null; - String v = value.trim(); - if (v.isEmpty()) return null; - - Kind kind = v.startsWith("play(") ? Kind.PLAY : v.startsWith("say(") ? Kind.SAY : null; - if (kind == null) return null; - - int open = v.indexOf('('); - int close = v.lastIndexOf(')'); - if (close <= open) return null; - String arg = v.substring(open + 1, close).trim(); - if (arg.length() >= 2 && arg.startsWith("\"") && arg.endsWith("\"")) { - arg = arg.substring(1, arg.length() - 1); - } - return arg.isEmpty() ? null : new SoundScript(kind, arg); - } - - /** Substitutes {@code ${name}} placeholders; unknown ones resolve to an empty string. */ - public String resolve(Map variables) { - String text = argument; - int from = 0; - StringBuilder out = new StringBuilder(); - while (true) { - int start = text.indexOf("${", from); - if (start < 0) break; - int end = text.indexOf('}', start); - if (end < 0) break; - String name = text.substring(start + 2, end); - String value = variables == null ? null : variables.get(name); - out.append(text, from, start).append(value == null ? "" : value); - from = end + 1; - } - return out.append(text.substring(from)).toString(); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/sound/WaveFile.java b/ts3-client/core/src/main/java/com/ts3client/sound/WaveFile.java deleted file mode 100644 index 48cfee8..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/sound/WaveFile.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.ts3client.sound; - -import com.ts3client.audio.VoiceFormat; - -import java.io.File; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.file.Files; - -/** - * Reads RIFF wave files into mono float samples. Sound packs ship 16-bit PCM, but any - * integer depth up to 32 bits and 32-bit float are accepted too, in plain or - * {@code WAVE_FORMAT_EXTENSIBLE} headers. - */ -final class WaveFile { - - private static final int FORMAT_PCM = 1; - private static final int FORMAT_FLOAT = 3; - private static final int FORMAT_EXTENSIBLE = 0xFFFE; - - /** Decoded audio: mono samples in [-1, 1] at {@code sampleRate}. */ - record Audio(float[] samples, int sampleRate) { - - /** The samples at the 48 kHz everything plays at, linearly interpolated. */ - float[] at48k() { - int toRate = VoiceFormat.SAMPLE_RATE; - if (sampleRate <= 0 || sampleRate == toRate || samples.length == 0) return samples; - double ratio = toRate / (double) sampleRate; - float[] out = new float[(int) (samples.length * ratio)]; - for (int i = 0; i < out.length; i++) { - double position = i / ratio; - int index = (int) position; - double fraction = position - index; - float a = samples[Math.min(index, samples.length - 1)]; - float b = samples[Math.min(index + 1, samples.length - 1)]; - out[i] = (float) (a + (b - a) * fraction); - } - return out; - } - } - - private WaveFile() { - } - - static Audio readMono(File file) throws IOException { - ByteBuffer in = ByteBuffer.wrap(Files.readAllBytes(file.toPath())).order(ByteOrder.LITTLE_ENDIAN); - if (in.remaining() < 12 || in.getInt() != fourCc("RIFF")) throw new IOException("not a RIFF file"); - in.getInt(); // RIFF size - if (in.getInt() != fourCc("WAVE")) throw new IOException("not a wave file"); - - int format = -1, channels = 0, sampleRate = 0, bits = 0; - while (in.remaining() >= 8) { - int id = in.getInt(); - int size = in.getInt(); - if (size < 0 || size > in.remaining()) size = in.remaining(); // truncated files still play - // Android < API 34 lacks ByteBuffer.slice(int, int); original: - // ByteBuffer chunk = in.slice(in.position(), size).order(ByteOrder.LITTLE_ENDIAN); - ByteBuffer chunk = in.duplicate(); - chunk.limit(chunk.position() + size); - chunk = chunk.slice().order(ByteOrder.LITTLE_ENDIAN); - if (id == fourCc("fmt ") && size >= 16) { - format = chunk.getShort() & 0xFFFF; - channels = chunk.getShort() & 0xFFFF; - sampleRate = chunk.getInt(); - chunk.getInt(); // byte rate - chunk.getShort(); // block align - bits = chunk.getShort() & 0xFFFF; - if (format == FORMAT_EXTENSIBLE && size >= 26) { - format = chunk.getShort(24) & 0xFFFF; // the sub-format GUID starts with the tag - } - } else if (id == fourCc("data")) { - if (format < 0) throw new IOException("data before fmt chunk"); - return new Audio(decode(chunk, format, channels, bits), sampleRate); - } - in.position(in.position() + size + (size & 1)); // chunks are word-aligned - } - throw new IOException("no audio data"); - } - - private static float[] decode(ByteBuffer data, int format, int channels, int bits) throws IOException { - int bytes = bits / 8; - boolean supported = (format == FORMAT_PCM && bits % 8 == 0 && bytes >= 1 && bytes <= 4) - || (format == FORMAT_FLOAT && bits == 32); - if (!supported || channels < 1) { - throw new IOException("unsupported wave encoding " + format + "/" + bits + " bit"); - } - int frames = data.remaining() / (bytes * channels); - float[] mono = new float[frames]; - for (int i = 0; i < frames; i++) { - float sum = 0; - for (int c = 0; c < channels; c++) { - sum += format == FORMAT_FLOAT ? data.getFloat() : readInt(data, bytes); - } - mono[i] = sum / channels; - } - return mono; - } - - /** One integer sample scaled to [-1, 1]; 8-bit wave data is unsigned, wider data signed. */ - private static float readInt(ByteBuffer data, int bytes) { - if (bytes == 1) return ((data.get() & 0xFF) - 128) / 128f; - int value = 0; - for (int b = 0; b < bytes; b++) value |= (data.get() & 0xFF) << (8 * b); - int shift = 32 - 8 * bytes; - return (value << shift) / 2147483648f; // sign-extend via the top bits - } - - private static int fourCc(String id) { - return id.charAt(0) | id.charAt(1) << 8 | id.charAt(2) << 16 | id.charAt(3) << 24; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/teamspeak/SqliteReader.java b/ts3-client/core/src/main/java/com/ts3client/teamspeak/SqliteReader.java deleted file mode 100644 index 614bbd9..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/teamspeak/SqliteReader.java +++ /dev/null @@ -1,288 +0,0 @@ -package com.ts3client.teamspeak; - -import java.io.IOException; -import java.io.RandomAccessFile; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -/** - * A minimal read-only reader for SQLite 3 database files, enough to dump the rows - * of a table: it walks the table's b-tree and decodes each record, overflow pages - * included. It exists so the TeamSpeak client's {@code settings.db} can be read - * without a JDBC driver and its native library. - * - *

Only the main database file is read. A write-ahead log that has not been - * checkpointed yet is not consulted; TeamSpeak uses a rollback journal, whose - * committed state is in the main file. - */ -final class SqliteReader implements AutoCloseable { - - private static final int HEADER_SIZE = 100; - private static final int INTERIOR_TABLE = 0x05; - private static final int LEAF_TABLE = 0x0d; - - /** A table's column names and rows; values are {@link Long}, {@link Double}, {@link String}, {@code byte[]} or {@code null}. */ - static final class Table { - final List columns; - final List rows; - - Table(List columns, List rows) { - this.columns = columns; - this.rows = rows; - } - - int columnIndex(String name) { - for (int i = 0; i < columns.size(); i++) { - if (columns.get(i).equalsIgnoreCase(name)) return i; - } - return -1; - } - } - - private final RandomAccessFile file; - private final int pageSize; - private final int usableSize; - private final int encoding; - - SqliteReader(java.io.File path) throws IOException { - file = new RandomAccessFile(path, "r"); - byte[] header = new byte[HEADER_SIZE]; - file.readFully(header); - if (!new String(header, 0, 15, StandardCharsets.US_ASCII).equals("SQLite format 3")) { - file.close(); - throw new IOException("Not an SQLite 3 database"); - } - int size = u16(header, 16); - pageSize = size == 1 ? 65536 : size; - usableSize = pageSize - (header[20] & 0xFF); - encoding = (int) u32(header, 56); - } - - @Override - public void close() throws IOException { - file.close(); - } - - /** Reads a whole table, or returns {@code null} when the schema has no such table. */ - Table readTable(String tableName) throws IOException { - Object[] schema = null; - for (Object[] row : rowsOf(1)) { - if (row.length < 5 || !"table".equals(row[0])) continue; - if (String.valueOf(row[1]).equalsIgnoreCase(tableName)) { - schema = row; - break; - } - } - if (schema == null || !(schema[3] instanceof Long)) return null; - List columns = columnNames(String.valueOf(schema[4])); - return new Table(columns, rowsOf(((Long) schema[3]).intValue())); - } - - /** The column names out of a {@code CREATE TABLE} statement, in declaration order. */ - static List columnNames(String sql) { - List names = new ArrayList<>(); - int open = sql.indexOf('('); - int close = sql.lastIndexOf(')'); - if (open < 0 || close <= open) return names; - for (String definition : splitTopLevel(sql.substring(open + 1, close))) { - String[] tokens = definition.trim().split("\\s+"); - if (tokens.length == 0 || tokens[0].isEmpty()) continue; - String first = tokens[0].toUpperCase(Locale.ROOT); - // Table constraints live in the same list as columns. - if (first.equals("PRIMARY") || first.equals("UNIQUE") || first.equals("CHECK") - || first.equals("FOREIGN") || first.equals("CONSTRAINT")) { - continue; - } - names.add(unquote(tokens[0])); - } - return names; - } - - /** Splits on commas outside parentheses, so {@code PRIMARY KEY (a, b)} stays one item. */ - private static List splitTopLevel(String s) { - List parts = new ArrayList<>(); - int depth = 0; - int start = 0; - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - if (c == '(') depth++; - else if (c == ')') depth--; - else if (c == ',' && depth == 0) { - parts.add(s.substring(start, i)); - start = i + 1; - } - } - parts.add(s.substring(start)); - return parts; - } - - private static String unquote(String s) { - if (s.length() >= 2) { - char c = s.charAt(0); - if ((c == '"' || c == '`' || c == '\'' || c == '[') && (s.endsWith(String.valueOf(c)) || c == '[' && s.endsWith("]"))) { - return s.substring(1, s.length() - 1); - } - } - return s; - } - - // ---- b-tree walk ---- - - private List rowsOf(int rootPage) throws IOException { - List rows = new ArrayList<>(); - walk(rootPage, rows, 0); - return rows; - } - - private void walk(int pageNumber, List rows, int depth) throws IOException { - if (depth > 64) throw new IOException("B-tree too deep"); - byte[] page = readPage(pageNumber); - int base = pageNumber == 1 ? HEADER_SIZE : 0; - int type = page[base] & 0xFF; - int cells = u16(page, base + 3); - int headerSize = type == INTERIOR_TABLE ? 12 : 8; - int pointers = base + headerSize; - - if (type == INTERIOR_TABLE) { - for (int i = 0; i < cells; i++) { - int cell = u16(page, pointers + 2 * i); - walk((int) u32(page, cell), rows, depth + 1); - } - walk((int) u32(page, base + 8), rows, depth + 1); - } else if (type == LEAF_TABLE) { - for (int i = 0; i < cells; i++) { - int cell = u16(page, pointers + 2 * i); - rows.add(decodeRecord(leafPayload(page, cell))); - } - } else { - throw new IOException("Unexpected page type " + type); - } - } - - /** The full payload of a table leaf cell, following the overflow chain when it spills. */ - private byte[] leafPayload(byte[] page, int cell) throws IOException { - long[] varint = new long[2]; - int pos = readVarint(page, cell, varint); - int payloadSize = (int) varint[0]; - pos = readVarint(page, pos, varint); // rowid - - int usable = usableSize; - int maxLocal = usable - 35; - int minLocal = (usable - 12) * 32 / 255 - 23; - int local; - if (payloadSize <= maxLocal) { - local = payloadSize; - } else { - int k = minLocal + (payloadSize - minLocal) % (usable - 4); - local = k <= maxLocal ? k : minLocal; - } - - byte[] payload = new byte[payloadSize]; - System.arraycopy(page, pos, payload, 0, local); - int filled = local; - long next = local < payloadSize ? u32(page, pos + local) : 0; - while (filled < payloadSize && next != 0) { - byte[] overflow = readPage((int) next); - int chunk = Math.min(payloadSize - filled, usable - 4); - System.arraycopy(overflow, 4, payload, filled, chunk); - filled += chunk; - next = u32(overflow, 0); - } - if (filled < payloadSize) throw new IOException("Truncated overflow chain"); - return payload; - } - - private Object[] decodeRecord(byte[] payload) throws IOException { - long[] varint = new long[2]; - int pos = readVarint(payload, 0, varint); - int headerEnd = (int) varint[0]; - List types = new ArrayList<>(); - while (pos < headerEnd) { - pos = readVarint(payload, pos, varint); - types.add(varint[0]); - } - Object[] values = new Object[types.size()]; - int data = headerEnd; - for (int i = 0; i < values.length; i++) { - long type = types.get(i); - if (type == 0) { - values[i] = null; - } else if (type >= 1 && type <= 6) { - int width = type == 5 ? 6 : type == 6 ? 8 : (int) type; - values[i] = readInt(payload, data, width); - data += width; - } else if (type == 7) { - values[i] = Double.longBitsToDouble(readInt(payload, data, 8)); - data += 8; - } else if (type == 8 || type == 9) { - values[i] = type - 8; - } else if (type >= 12) { - int length = (int) ((type - (type % 2 == 0 ? 12 : 13)) / 2); - if (type % 2 == 0) { - byte[] blob = new byte[length]; - System.arraycopy(payload, data, blob, 0, length); - values[i] = blob; - } else { - values[i] = decodeText(payload, data, length); - } - data += length; - } else { - throw new IOException("Reserved serial type " + type); - } - } - return values; - } - - private String decodeText(byte[] b, int off, int len) { - switch (encoding) { - case 2: - return new String(b, off, len, StandardCharsets.UTF_16LE); - case 3: - return new String(b, off, len, StandardCharsets.UTF_16BE); - default: - return new String(b, off, len, StandardCharsets.UTF_8); - } - } - - private byte[] readPage(int number) throws IOException { - if (number < 1) throw new IOException("Bad page number " + number); - byte[] page = new byte[pageSize]; - file.seek((long) (number - 1) * pageSize); - file.readFully(page); - return page; - } - - // ---- encoding primitives ---- - - private static int u16(byte[] b, int off) { - return (b[off] & 0xFF) << 8 | (b[off + 1] & 0xFF); - } - - private static long u32(byte[] b, int off) { - return (long) (b[off] & 0xFF) << 24 | (b[off + 1] & 0xFF) << 16 | (b[off + 2] & 0xFF) << 8 | (b[off + 3] & 0xFF); - } - - private static long readInt(byte[] b, int off, int width) { - long v = b[off] & 0xFF; - if ((v & 0x80) != 0) v |= -256L; // sign-extend - for (int i = 1; i < width; i++) v = v << 8 | (b[off + i] & 0xFF); - return v; - } - - /** Reads a big-endian varint into {@code out[0]} and returns the position after it. */ - private static int readVarint(byte[] b, int off, long[] out) { - long v = 0; - for (int i = 0; i < 8; i++) { - int c = b[off + i] & 0xFF; - v = v << 7 | (c & 0x7F); - if ((c & 0x80) == 0) { - out[0] = v; - return off + i + 1; - } - } - out[0] = v << 8 | (b[off + 8] & 0xFF); - return off + 9; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/teamspeak/SyncItem.java b/ts3-client/core/src/main/java/com/ts3client/teamspeak/SyncItem.java deleted file mode 100644 index 854f6af..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/teamspeak/SyncItem.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.ts3client.teamspeak; - -/** - * One entry of the TeamSpeak 3 client's synchronised item store — the data that - * a myTeamSpeak account syncs between installations. Since client 3.1 the - * bookmarks and identities of every installation live there, signed in or not. - * Whisper lists, hotkey profiles and the other item classes are not modelled. - */ -public sealed interface SyncItem { - - /** The item's own id, a UUID string. */ - String uuid(); - - /** UUID of the {@link Folder} the item sits in, or empty at the top level. */ - String parentUuid(); - - /** UUID of the item just above it in its folder, or empty when it is the first. */ - String previousUuid(); - - record Folder(String uuid, String parentUuid, String previousUuid, String name) implements SyncItem { - } - - /** - * @param identity the key in TeamSpeak's obfuscated {@code V} identity form - * @param nickname the nickname used with this identity when a bookmark names none - */ - record Identity(String uuid, String parentUuid, String previousUuid, String identity, String name, - String nickname, String phoneticNickname, boolean isDefault) implements SyncItem { - } - - /** - * @param identityUuid {@link Identity#uuid()} of the identity to connect with (or its {@link Identity#name()} - * in some myTeamSpeak items); empty for the default - * @param defaultChannel channel path to join, "/"-separated; empty for the server default - * @param defaultChannelId the same channel by id, {@code 0} when unknown - */ - record Bookmark(String uuid, String parentUuid, String previousUuid, String name, String address, int port, - String nickname, String phoneticNickname, String identityUuid, - String serverPassword, String defaultChannel, String defaultChannelPassword, - long defaultChannelId, boolean autoconnect) implements SyncItem { - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/teamspeak/SyncItemDecoder.java b/ts3-client/core/src/main/java/com/ts3client/teamspeak/SyncItemDecoder.java deleted file mode 100644 index 207d99b..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/teamspeak/SyncItemDecoder.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.ts3client.teamspeak; - -import com.ts3client.proto.ProtobufReader; - -import java.io.IOException; - -/** - * Decodes a serialised {@code com.teamspeak.sync.proto.Item_Data} message (the - * schema is embedded in the TeamSpeak client binary) into a {@link SyncItem}: - * a row of the local store, or a decrypted myTeamSpeak item, which is the same. - */ -public final class SyncItemDecoder { - - /** Item_Data.parent of a top-level item. */ - private static final String ROOT_PARENT = "ffffffff-ffff-ffff-ffff-ffffffffffff"; - - private static final int ITEM_DELETED = 2; - - private SyncItemDecoder() { - } - - /** - * @return the item, or {@code null} when it is of an unmodelled class or was - * deleted locally and only lingers until the deletion is synced - */ - public static SyncItem decode(byte[] blob) throws IOException { - String uuid = ""; - String parent = ""; - String previous = ""; - boolean deleted = false; - ProtobufReader content = null; - int contentField = 0; - - ProtobufReader r = new ProtobufReader(blob); - while (r.next()) { - switch (r.fieldNumber()) { - case 2 -> uuid = r.readString(); - case 4 -> deleted = r.readVarint() == ITEM_DELETED; - case 7 -> parent = r.readString(); - case 8 -> previous = r.readString(); - case 16, 17, 22 -> { - contentField = r.fieldNumber(); - content = r.readMessage(); - } - default -> r.skip(); - } - } - if (deleted || content == null) return null; - if (parent.equals(ROOT_PARENT)) parent = ""; - return switch (contentField) { - case 16 -> bookmark(uuid, parent, previous, content); - case 17 -> identity(uuid, parent, previous, content); - default -> folder(uuid, parent, previous, content); - }; - } - - private static SyncItem.Bookmark bookmark(String uuid, String parent, String previous, ProtobufReader r) throws IOException { - String name = "", address = "", nickname = "", phonetic = "", identity = ""; - String serverPassword = "", channel = "", channelPassword = ""; - int port = 9987; - long channelId = 0; - boolean autoconnect = false; - while (r.next()) { - switch (r.fieldNumber()) { - case 1 -> name = r.readString(); - case 2 -> address = r.readString(); - case 3 -> port = (int) r.readVarint(); - case 4 -> nickname = r.readString(); - case 5 -> phonetic = r.readString(); - case 6 -> identity = r.readString(); - case 7 -> serverPassword = r.readString(); - case 8 -> channel = r.readString(); - case 9 -> channelPassword = r.readString(); - case 10 -> channelId = r.readVarint(); - case 14 -> autoconnect = r.readBool(); - default -> r.skip(); - } - } - return new SyncItem.Bookmark(uuid, parent, previous, name, address, port, nickname, phonetic, identity, - serverPassword, channel, channelPassword, channelId, autoconnect); - } - - private static SyncItem.Identity identity(String uuid, String parent, String previous, ProtobufReader r) throws IOException { - String identity = "", name = "", nickname = "", phonetic = ""; - boolean isDefault = false; - while (r.next()) { - switch (r.fieldNumber()) { - case 1 -> identity = r.readString(); - case 2 -> name = r.readString(); - case 3 -> nickname = r.readString(); - case 4 -> phonetic = r.readString(); - case 5 -> isDefault = r.readBool(); - default -> r.skip(); - } - } - return new SyncItem.Identity(uuid, parent, previous, identity, name, nickname, phonetic, isDefault); - } - - private static SyncItem.Folder folder(String uuid, String parent, String previous, ProtobufReader r) throws IOException { - String name = ""; - while (r.next()) { - if (r.fieldNumber() == 1) name = r.readString(); - else r.skip(); - } - return new SyncItem.Folder(uuid, parent, previous, name); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/teamspeak/SyncOrder.java b/ts3-client/core/src/main/java/com/ts3client/teamspeak/SyncOrder.java deleted file mode 100644 index 1d0215a..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/teamspeak/SyncOrder.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.ts3client.teamspeak; - -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Puts sync items in the order the TeamSpeak client lists them. The store keeps them in the - * order they were created; each item names the one above it in its folder, so a reorder only - * rewrites those links. - */ -public final class SyncOrder { - - private SyncOrder() { - } - - /** - * The items top to bottom, each folder's contents right after the folder. Items whose - * links lead nowhere, or whose folder is missing, come last in their stored order. - */ - public static List sorted(List items) { - Map> byFolder = new LinkedHashMap<>(); - for (SyncItem item : items) byFolder.computeIfAbsent(item.parentUuid(), k -> new ArrayList<>()).add(item); - - List out = new ArrayList<>(items.size()); - Set placed = new HashSet<>(); - appendFolder("", byFolder, placed, out); - for (List stray : byFolder.values()) { - for (SyncItem item : stray) { - if (!placed.contains(item)) appendFolder(item.parentUuid(), byFolder, placed, out); - } - } - return out; - } - - private static void appendFolder(String folder, Map> byFolder, Set placed, - List out) { - List members = byFolder.getOrDefault(folder, List.of()); - Map> byPrevious = new LinkedHashMap<>(); - for (SyncItem item : members) byPrevious.computeIfAbsent(item.previousUuid(), k -> new ArrayList<>()).add(item); - - List chain = new ArrayList<>(members.size()); - follow(byPrevious.getOrDefault("", List.of()), byPrevious, placed, chain); - // Broken links: the rest start chains of their own. - for (SyncItem item : members) follow(List.of(item), byPrevious, placed, chain); - for (SyncItem item : chain) { - out.add(item); - if (item instanceof SyncItem.Folder) appendFolder(item.uuid(), byFolder, placed, out); - } - } - - /** Appends {@code heads} and, after each, the items below it, depth first. */ - private static void follow(List heads, Map> byPrevious, Set placed, - List chain) { - ArrayDeque stack = new ArrayDeque<>(); - for (int i = heads.size() - 1; i >= 0; i--) stack.push(heads.get(i)); - while (!stack.isEmpty()) { - SyncItem item = stack.pop(); - if (!placed.add(item)) continue; - chain.add(item); - List below = byPrevious.getOrDefault(item.uuid(), List.of()); - for (int i = below.size() - 1; i >= 0; i--) stack.push(below.get(i)); - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/teamspeak/TeamSpeakImporter.java b/ts3-client/core/src/main/java/com/ts3client/teamspeak/TeamSpeakImporter.java deleted file mode 100644 index 0f76749..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/teamspeak/TeamSpeakImporter.java +++ /dev/null @@ -1,227 +0,0 @@ -package com.ts3client.teamspeak; - -import com.ts3client.config.Bookmark; -import com.ts3client.config.Bookmarks; -import com.ts3client.config.IdentityEntry; -import com.ts3client.config.IdentityStore; -import com.ts3client.config.Settings; -import com.github.manevolent.ts3j.identity.LocalIdentity; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Carries the TeamSpeak 3 client's synchronised bookmarks and identities — - * from its local store or a myTeamSpeak account — over into this client's stores. Importing is additive and idempotent: an identity - * already present (same unique ID) or a bookmark already present (same label, - * address and port) is left alone, and bookmarks are wired to the identities - * they referenced in TeamSpeak. - */ -public final class TeamSpeakImporter { - - /** What an import did; {@code known} counts the items that were already there. */ - public record Result(int identitiesAdded, int identitiesKnown, int bookmarksAdded, int bookmarksKnown) { - public int identities() { - return identitiesAdded + identitiesKnown; - } - - public int bookmarks() { - return bookmarksAdded + bookmarksKnown; - } - } - - private final IdentityStore identities; - private final Bookmarks bookmarks; - private final Settings settings; - - public TeamSpeakImporter(IdentityStore identities, Bookmarks bookmarks, Settings settings) { - this.identities = identities; - this.bookmarks = bookmarks; - this.settings = settings; - } - - /** Imports the identities only. */ - public Result importIdentities(File db) throws IOException { - return importItems(TeamSpeakSettingsDb.readSyncItems(db), false, false); - } - - /** Imports the bookmarks, together with the identities they connect with. */ - public Result importBookmarks(File db) throws IOException { - return importItems(TeamSpeakSettingsDb.readSyncItems(db), true, true); - } - - /** Imports every identity and bookmark. */ - public Result importAll(File db) throws IOException { - return importAll(TeamSpeakSettingsDb.readSyncItems(db)); - } - - /** Imports every identity and bookmark among items read elsewhere, such as from a myTeamSpeak account. */ - public Result importAll(List items) throws IOException { - return importItems(items, true, false); - } - - /** - * Imports the chosen items out of {@code all}, together with the identities the chosen - * bookmarks connect with, which only {@code all} may hold. - */ - public Result importSelected(List all, Collection chosen) throws IOException { - Map syncIdentities = identitiesOf(all); - Set selection = new LinkedHashSet<>(chosen); - for (SyncItem item : chosen) { - if (!(item instanceof SyncItem.Bookmark bookmark)) continue; - SyncItem.Identity identity = identityOf(bookmark, syncIdentities); - if (identity != null) selection.add(identity); - } - return importItems(new ArrayList<>(selection), true, false); - } - - /** Whether the item is here already: an identity with the same key, or a bookmark with the same label and address. */ - public boolean isPresent(SyncItem item) { - if (item instanceof SyncItem.Bookmark bookmark) return find(bookmark) != null; - if (!(item instanceof SyncItem.Identity identity)) return false; - try { - return identities.byUniqueId(IdentityStore.parseIdentityString(identity.identity()).getUid().toBase64()) != null; - } catch (IOException malformed) { - return false; - } - } - - /** - * First run — no identity of our own yet — so adopt whatever the TeamSpeak 3 - * client on this machine has, as the contact list does. Quiet on any failure. - * - * @return what was imported, or {@code null} when this was not a first run or there was nothing to import - */ - public Result seedIfFresh() { - if (!identities.isEmpty()) return null; - File db = TeamSpeakSettingsDb.locate(); - if (db == null) return null; - try { - return importAll(db); - } catch (Exception e) { - return null; - } - } - - private Result importItems(List items, boolean withBookmarks, boolean onlyUsedIdentities) - throws IOException { - Map syncIdentities = identitiesOf(items); - List syncBookmarks = new ArrayList<>(); - for (SyncItem item : items) { - if (item instanceof SyncItem.Bookmark bookmark && !bookmark.address().isBlank()) syncBookmarks.add(bookmark); - } - if (onlyUsedIdentities) { - // Only the identities some bookmark connects with come along. - Set referenced = new HashSet<>(); - for (SyncItem.Bookmark bookmark : syncBookmarks) { - SyncItem.Identity identity = identityOf(bookmark, syncIdentities); - if (identity != null) referenced.add(identity); - } - syncIdentities.values().retainAll(referenced); - } - - int identitiesAdded = 0, identitiesKnown = 0, bookmarksAdded = 0, bookmarksKnown = 0; - Map imported = new HashMap<>(); - boolean settingsChanged = false; - - for (SyncItem.Identity identity : syncIdentities.values()) { - LocalIdentity key; - try { - key = IdentityStore.parseIdentityString(identity.identity()); - } catch (IOException malformed) { - continue; - } - IdentityEntry entry = identities.byUniqueId(key.getUid().toBase64()); - if (entry != null) { - identitiesKnown++; - } else { - entry = identities.add(nameOf(identity), key, identity.nickname(), identity.phoneticNickname()); - identitiesAdded++; - } - imported.put(identity.uuid(), entry); - if (!identity.isDefault()) continue; - // No default of our own yet: TeamSpeak's default identity and nickname become ours. - if (identities.byId(settings.defaultIdentityId) == null) { - settings.defaultIdentityId = entry.getId(); - if (!identity.nickname().isBlank()) settings.nickname = identity.nickname(); - settingsChanged = true; - } - } - if (settingsChanged) settings.save(); - if (!withBookmarks) return new Result(identitiesAdded, identitiesKnown, 0, 0); - - for (SyncItem.Bookmark bookmark : syncBookmarks) { - if (find(bookmark) != null) { - bookmarksKnown++; - continue; - } - // A bookmark naming no identity connects with the default one, as it does here. - SyncItem.Identity syncIdentity = identityOf(bookmark, syncIdentities); - IdentityEntry identity = bookmark.identityUuid().isEmpty() || syncIdentity == null - ? null : imported.get(syncIdentity.uuid()); - bookmarks.add(toBookmark(bookmark, identity)); - bookmarksAdded++; - } - if (bookmarksAdded > 0) bookmarks.save(); - return new Result(identitiesAdded, identitiesKnown, bookmarksAdded, bookmarksKnown); - } - - private Bookmark toBookmark(SyncItem.Bookmark sync, IdentityEntry identity) { - // Without a nickname of its own, the bookmark takes the identity's as it connects. - Bookmark b = new Bookmark(sync.name(), sync.address(), sync.port(), sync.nickname(), sync.serverPassword()); - b.identityId = identity == null ? "" : identity.getId(); - b.channel = sync.defaultChannel(); - if (b.channel.isBlank() && sync.defaultChannelId() != 0) b.channel = "/" + sync.defaultChannelId(); - b.channelPassword = sync.defaultChannelPassword(); - b.connectOnStartup = sync.autoconnect(); - return b; - } - - private static Map identitiesOf(List items) { - Map identities = new LinkedHashMap<>(); - for (SyncItem item : items) { - if (item instanceof SyncItem.Identity identity) identities.put(identity.uuid(), identity); - } - return identities; - } - - /** - * The identity a bookmark connects with. Bookmarks normally name it by item UUID, - * but some — seen in a myTeamSpeak account — name it by its display name instead. - */ - private static SyncItem.Identity identityOf(SyncItem.Bookmark bookmark, Map identities) { - String ref = bookmark.identityUuid(); - for (SyncItem.Identity identity : identities.values()) { - if (ref.isEmpty() ? identity.isDefault() : identity.uuid().equals(ref)) return identity; - } - for (SyncItem.Identity identity : identities.values()) { - if (identity.name().equals(ref)) return identity; - } - return null; - } - - private Bookmark find(SyncItem.Bookmark sync) { - for (Bookmark b : bookmarks.all()) { - if (b.port == sync.port() - && sync.address().equalsIgnoreCase(b.address == null ? "" : b.address) - && sync.name().equals(b.label == null ? "" : b.label)) { - return b; - } - } - return null; - } - - private static String nameOf(SyncItem.Identity identity) { - if (!identity.name().isBlank()) return identity.name(); - return identity.nickname().isBlank() ? "TeamSpeak 3 identity" : identity.nickname(); - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/teamspeak/TeamSpeakSettingsDb.java b/ts3-client/core/src/main/java/com/ts3client/teamspeak/TeamSpeakSettingsDb.java deleted file mode 100644 index 23a6790..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/teamspeak/TeamSpeakSettingsDb.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.ts3client.teamspeak; - -import com.ts3client.contacts.Contact; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * Reads an installed TeamSpeak 3 client's {@code settings.db}: the {@code Contacts} - * table holds one record per contact in the format {@link Contact#parseRecord} - * understands, and {@code ProtobufItems} holds the myTeamSpeak-synchronised - * store — bookmarks, identities and their folders — as {@link SyncItem}s. - */ -public final class TeamSpeakSettingsDb { - - /** Overrides where the TeamSpeak client keeps its configuration. */ - private static final String CONFIG_DIR_PROPERTY = "ts3.config.dir"; - - private TeamSpeakSettingsDb() { - } - - /** The TeamSpeak client's settings database on this machine, or {@code null} when there is none. */ - public static File locate() { - String configured = System.getProperty(CONFIG_DIR_PROPERTY); - List candidates = new ArrayList<>(); - if (configured != null && !configured.isBlank()) candidates.add(new File(configured.trim())); - - String home = System.getProperty("user.home", "."); - candidates.add(new File(home, ".ts3client")); - String appData = System.getenv("APPDATA"); - if (appData != null) candidates.add(new File(appData, "TS3Client")); - candidates.add(new File(home, "Library/Application Support/TeamSpeak 3")); - - for (File dir : candidates) { - File db = new File(dir, "settings.db"); - if (db.isFile()) return db; - } - return null; - } - - /** The contacts of the local TeamSpeak client, or an empty list when it has none or cannot be read. */ - public static List readContacts() { - File db = locate(); - if (db == null) return List.of(); - try { - return readContacts(db); - } catch (Exception e) { - return List.of(); - } - } - - /** @throws IOException when the file is not a readable SQLite database */ - public static List readContacts(File db) throws IOException { - List contacts = new ArrayList<>(); - for (Object value : columnValues(db, "Contacts")) { - if (!(value instanceof String record)) continue; - Contact c = Contact.parseRecord(record); - if (c != null) contacts.add(c); - } - return contacts; - } - - /** - * The synchronised items in the order the client lists them. Rows that are not items — the - * table's checksum, unmodelled classes, pending deletions — are left out. - * - * @throws IOException when the file is not a readable SQLite database - */ - public static List readSyncItems(File db) throws IOException { - List items = new ArrayList<>(); - for (Object value : columnValues(db, "ProtobufItems")) { - if (!(value instanceof byte[] blob)) continue; - SyncItem item; - try { - item = SyncItemDecoder.decode(blob); - } catch (IOException malformed) { - continue; - } - if (item != null) items.add(item); - } - return SyncOrder.sorted(items); - } - - /** The {@code value} column of a key/value table, in row order; empty when the table is absent. */ - private static List columnValues(File db, String tableName) throws IOException { - List values = new ArrayList<>(); - try (SqliteReader reader = new SqliteReader(db)) { - SqliteReader.Table table = reader.readTable(tableName); - if (table == null) return values; - int column = table.columnIndex("value"); - if (column < 0) return values; - for (Object[] row : table.rows) { - if (column < row.length) values.add(row[column]); - } - } - return values; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/text/BBCode.java b/ts3-client/core/src/main/java/com/ts3client/text/BBCode.java deleted file mode 100644 index 7ce7843..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/text/BBCode.java +++ /dev/null @@ -1,303 +0,0 @@ -package com.ts3client.text; - -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Renderer for the small BBCode dialect TeamSpeak uses in chat messages and - * channel/client descriptions. Produces an HTML fragment restricted to the tags - * Swing's HTML 3.2 renderer understands; anything unrecognised is passed - * through as literal text, and all input is escaped, so server-supplied text - * can never inject markup. - */ -public final class BBCode { - - /** {@code [url]http://x[/url]} is rewritten to the {@code [url=…]} form before parsing. */ - private static final Pattern BARE_URL_TAG = - Pattern.compile("\\[url]([^\\[\\]]+)\\[/url]", Pattern.CASE_INSENSITIVE); - private static final Pattern BARE_IMG_TAG = - Pattern.compile("\\[img]([^\\[\\]]+)\\[/img]", Pattern.CASE_INSENSITIVE); - /** A picture's address: only the web, so a description cannot point the client anywhere else. */ - private static final Pattern IMAGE_URL = Pattern.compile("(?i)https?://[^\\s\"'<>]+"); - private static final int MAX_ADDRESS = 48; - private static final Pattern IMG_CLOSE = Pattern.compile("(?i)\\[/img]"); - private static final Pattern PLAIN_URL = - Pattern.compile("(?i)\\b(?:https?://|www\\.)[^\\s<>\"']+"); - private static final Pattern COLOR = Pattern.compile("#[0-9a-fA-F]{3,6}|[a-zA-Z]{3,20}"); - /** Web links plus TeamSpeak's own {@code client://} / {@code channel://} / {@code ts3server://} schemes. */ - private static final Pattern SAFE_URL = - Pattern.compile("(?i)(https?|ftp|client|channel|ts3server|ts3file|offline)://[^\\s\"'<>]*"); - /** TeamSpeak's own protocols, which are rendered without an underline. */ - private static final Pattern TS_PROTOCOL = - Pattern.compile("(?i)^(client|channel|ts3server|ts3file|offline)://"); - private static final Pattern CLIENT_PROTOCOL = Pattern.compile("(?i)^client://"); - - /** CSS class on {@code client://} links, styled like a message author's name. */ - public static final String IDENTITY_LINK_CLASS = "identity"; - /** CSS class on links using TeamSpeak's other protocols (channel, ts3server, …). */ - public static final String TS_LINK_CLASS = "tslink"; - /** CSS class on links that leave the client, so they are visibly not an identity. */ - public static final String EXTERNAL_LINK_CLASS = "extlink"; - - /** A single {@code [url=href]label[/url]} pair, the only markup the log carries. */ - private static final Pattern URL_LINK = - Pattern.compile("(?i)\\[url=([^\\]]+)](.*?)\\[/url]"); - - private BBCode() { - } - - /** Converts BBCode to an HTML fragment (no surrounding {@code } element), pictures as links. */ - public static String toHtml(String input) { - return toHtml(input, false); - } - - /** - * @param images whether {@code [img]} becomes an {@code }, as TeamSpeak shows it in - * descriptions, rather than a link to the picture, as in chat - */ - public static String toHtml(String input, boolean images) { - if (input == null || input.isEmpty()) return ""; - String src = BARE_URL_TAG.matcher(input).replaceAll("[url=$1]$1[/url]"); - if (!images) src = BARE_IMG_TAG.matcher(src).replaceAll("[url=$1]$1[/url]"); - - StringBuilder out = new StringBuilder(); - Deque open = new ArrayDeque<>(); - int i = 0; - while (i < src.length()) { - int lb = src.indexOf('[', i); - if (lb < 0) { - text(out, src.substring(i), open); - break; - } - text(out, src.substring(i, lb), open); - int rb = src.indexOf(']', lb); - if (rb < 0) { - text(out, src.substring(lb), open); - break; - } - if (images && src.substring(lb + 1, rb).equalsIgnoreCase("img")) { - int end = image(out, src, rb + 1); - if (end > 0) { - i = end; - continue; - } - } - if (!emitTag(out, src.substring(lb + 1, rb), open)) { - text(out, src.substring(lb, rb + 1), open); - } - i = rb + 1; - } - while (!open.isEmpty()) out.append(open.pop().close); - return out.toString(); - } - - /** The text BBCode reads as, markup dropped, for places that show no formatting. */ - public static String toPlain(String input) { - return HtmlText.plain(toHtml(input)); - } - - /** - * Renders text carrying {@code [url=…]…[/url]} links and nothing else: everything - * outside those tags stays literal. The server log is written this way, so that a - * name happening to contain bracket markup is shown as it is rather than rendered. - */ - public static String linksToHtml(String input) { - if (input == null || input.isEmpty()) return ""; - StringBuilder out = new StringBuilder(); - Matcher m = URL_LINK.matcher(input); - int last = 0; - while (m.find()) { - out.append(escape(input.substring(last, m.start()))); - String href = m.group(1); - if (SAFE_URL.matcher(href).matches()) { - out.append(link(href)).append(escape(m.group(2))).append(linkClose(href)); - } else { - out.append(escape(m.group())); - } - last = m.end(); - } - return out.append(escape(input.substring(last))).toString(); - } - - /** A long web address as its host and file name, for a link's label where room is short. */ - public static String shortAddress(String url) { - if (url.length() <= MAX_ADDRESS) return url; - int host = url.indexOf("://"); - int path = host < 0 ? -1 : url.indexOf('/', host + 3); - int file = url.lastIndexOf('/'); - if (path < 0 || file <= path) return url; - return url.substring(host + 3, path) + "/…" + url.substring(file); - } - - /** Escapes plain text for HTML without interpreting any BBCode. */ - public static String escape(String s) { - if (s == null) return ""; - return s.replace("&", "&").replace("<", "<").replace(">", ">") - .replace("\"", """); - } - - /** - * Writes the picture whose address starts at {@code from}, up to its {@code [/img]}. - * - * @return where the text goes on after it, or -1 when there is no web address to show - */ - private static int image(StringBuilder out, String src, int from) { - Matcher close = IMG_CLOSE.matcher(src); - if (!close.find(from)) return -1; - String url = src.substring(from, close.start()).trim(); - if (!IMAGE_URL.matcher(url).matches()) return -1; - out.append(""); - return close.end(); - } - - /** True once the tag was recognised and written; false to render it literally. */ - private static boolean emitTag(StringBuilder out, String tag, Deque open) { - if (tag.isEmpty()) return false; - String lower = tag.toLowerCase(); - - if (lower.charAt(0) == '/') { - return closeTag(out, lower.substring(1), open); - } - if (lower.equals("*")) { - if (!contains(open, "list")) return false; - if (peekIs(open, "*")) out.append(open.pop().close); - push(out, open, "*", "
  • ", "
  • "); - return true; - } - - int eq = tag.indexOf('='); - String name = (eq < 0 ? lower : lower.substring(0, eq)).trim(); - String value = eq < 0 ? "" : tag.substring(eq + 1).trim(); - switch (name) { - case "b": - return push(out, open, name, "", ""); - case "i": - return push(out, open, name, "", ""); - case "u": - return push(out, open, name, "", ""); - case "s": - return push(out, open, name, "", ""); - case "hr": - // Stands alone; a closing tag some write after it is dropped, see closeTag. - out.append("
    "); - return true; - case "left": - case "center": - case "right": - case "justify": - return push(out, open, name, "
    ", "
    "); - case "list": - if (value.equals("1")) return push(out, open, name, "
      ", "
    "); - if (value.equalsIgnoreCase("a")) return push(out, open, name, "
      ", "
    "); - return push(out, open, name, "
      ", "
    "); - case "table": - return push(out, open, name, "", "
    "); - case "tr": - if (!contains(open, "table")) return false; - return push(out, open, name, "", ""); - case "td": - case "th": - if (!contains(open, "tr")) return false; - return push(out, open, name, "<" + name + ">", ""); - case "color": { - if (!COLOR.matcher(value).matches()) return false; - return push(out, open, name, "", ""); - } - case "size": { - int px = parseSize(value); - if (px < 0) return false; - return push(out, open, name, "", ""); - } - case "url": { - if (!SAFE_URL.matcher(value).matches()) return false; - return push(out, open, name, link(value), linkClose(value)); - } - - default: - return false; - } - } - - private static boolean closeTag(StringBuilder out, String name, Deque open) { - if (name.equals("hr")) return true; - if (!contains(open, name)) return false; - // Close anything left dangling inside, then the tag itself. - while (!open.isEmpty()) { - Open o = open.pop(); - out.append(o.close); - if (o.name.equals(name)) break; - } - return true; - } - - private static String link(String href) { - return ""; - } - - private static String linkClose(String href) { - return ""; - } - - /** The CSS class a link gets, by protocol. */ - public static String linkClass(String href) { - if (CLIENT_PROTOCOL.matcher(href).find()) return IDENTITY_LINK_CLASS; - return TS_PROTOCOL.matcher(href).find() ? TS_LINK_CLASS : EXTERNAL_LINK_CLASS; - } - - private static boolean push(StringBuilder out, Deque open, String name, - String openHtml, String closeHtml) { - out.append(openHtml); - open.push(new Open(name, closeHtml)); - return true; - } - - private static boolean contains(Deque open, String name) { - for (Open o : open) { - if (o.name.equals(name)) return true; - } - return false; - } - - private static boolean peekIs(Deque open, String name) { - return !open.isEmpty() && open.peek().name.equals(name); - } - - private static int parseSize(String value) { - try { - return Math.max(8, Math.min(28, Integer.parseInt(value.trim()))); - } catch (NumberFormatException e) { - return -1; - } - } - - /** Escapes a text run, turning newlines into breaks and linkifying bare URLs. */ - private static void text(StringBuilder out, String raw, Deque open) { - if (raw.isEmpty()) return; - if (contains(open, "url")) { // don't nest links inside a link label - out.append(escape(raw).replace("\n", "
    ")); - return; - } - Matcher m = PLAIN_URL.matcher(raw); - int last = 0; - while (m.find()) { - out.append(escape(raw.substring(last, m.start())).replace("\n", "
    ")); - String url = m.group(); - String href = url.regionMatches(true, 0, "www.", 0, 4) ? "http://" + url : url; - out.append(link(href)).append(escape(url)).append(linkClose(href)); - last = m.end(); - } - out.append(escape(raw.substring(last)).replace("\n", "
    ")); - } - - private static final class Open { - final String name; - final String close; - - Open(String name, String close) { - this.name = name; - this.close = close; - } - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/text/ChatHtml.java b/ts3-client/core/src/main/java/com/ts3client/text/ChatHtml.java deleted file mode 100644 index 0eece5a..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/text/ChatHtml.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.ts3client.text; - -import com.ts3client.myts.ChatAttachment; -import com.ts3client.myts.ChatAttachments; - -import java.time.LocalTime; -import java.time.format.DateTimeFormatter; -import java.util.Locale; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Builds the entries a chat shows, one {@code
    } of HTML each, the form TeamSpeak's own - * chat logs are in — so live lines and lines loaded from a log history look alike. The - * {@code class} attributes name how a frontend may style them. - */ -public final class ChatHtml { - - /** Timestamps and the chat's own notices. */ - public static final String MUTED_CLASS = "muted"; - /** A server event: someone joining, leaving, moving, a channel being edited, … */ - public static final String EVENT_CLASS = "event"; - /** A sender that cannot be linked to. */ - public static final String NAME_CLASS = "name"; - - /** A file shared in chat; its link's address is a {@link ChatAttachment#href}. */ - public static final String ATTACHMENT_CLASS = "attachment"; - - private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("HH:mm:ss"); - /** The text of a message in TeamSpeak's HTML log. */ - private static final Pattern LOG_TEXT = Pattern.compile("()(.*?)()", - Pattern.DOTALL); - - private ChatHtml() { - } - - /** - * A chat message; the sender becomes a {@code client://} link when their id is known. - * - * @param text the message as sent, in BBCode - */ - public static String message(int fromId, String fromUniqueId, String from, String text) { - return message(fromId, fromUniqueId, from, text, ""); - } - - /** - * A chat message, showing a file shared in it as the file. - * - * @param room the unique identifier of the server the chat is on, where shared files lie - */ - public static String message(int fromId, String fromUniqueId, String from, String text, String room) { - String name = BBCode.escape(from); - String sender = fromId > 0 - ? "" + name + "" - : span(NAME_CLASS, name); - ChatAttachment attachment = ChatAttachment.parse(text); - String body = attachment != null ? attachment(attachment, room) : BBCode.toHtml(text); - return div(span(MUTED_CLASS, stamp()) + sender + ": " + body); - } - - /** - * A shared file: a picture shown as one, anything else as a link with its size. Without - * the room to fetch it from, only its name. - */ - public static String attachment(ChatAttachment attachment, String room) { - String name = BBCode.escape(attachment.fileName().isBlank() ? "file" : attachment.fileName()); - String caption = attachment.caption().isEmpty() ? "" : "
    " + BBCode.escape(attachment.caption()); - if (room == null || room.isBlank()) return span(ATTACHMENT_CLASS, name) + caption; - String href = BBCode.escape(attachment.href(room)); - String open = ""; - if (attachment.isImage() && attachment.fileSize() <= ChatAttachments.MAX_PREVIEW_BYTES) { - return "
    " + open + "
    " + caption; - } - String size = attachment.fileSize() >= 0 ? " " + span(MUTED_CLASS, "(" + size(attachment.fileSize()) + ")") : ""; - return open + name + "" + size + caption; - } - - /** A message as plain text, e.g. for a notification: a shared file as its name. */ - public static String plainMessage(String text) { - ChatAttachment attachment = ChatAttachment.parse(text); - if (attachment == null) return BBCode.toPlain(text); - return attachment.caption().isEmpty() ? attachment.fileName() : attachment.caption(); - } - - /** One of the chat's own notices: connection progress, errors, pokes. */ - public static String system(String text) { - return div(span(MUTED_CLASS, stamp() + BBCode.escape(text))); - } - - /** - * A server event. It names clients and channels with TeamSpeak's own links, which stay - * links; everything else in it is literal text. - */ - public static String serverLog(String text) { - return div(span(EVENT_CLASS, stamp() + BBCode.linksToHtml(text))); - } - - /** - * Brings an entry of TeamSpeak's HTML log into the form of the others: one {@code
    }, - * without the images that log refers to by the native client's own paths. - * - * @return the entry, or empty for one that shows nothing - */ - public static String logEntry(String html) { - return logEntry(html, ""); - } - - /** - * {@link #logEntry(String)}, showing a file shared in the message as the file. - * - * @param room the unique identifier of the server the log is of - */ - public static String logEntry(String html, String room) { - if (html == null || html.isBlank()) return ""; - String normalized = html - .replaceAll("(?i)]*>", "") - .replaceFirst("(?i)^\\s*\\s*$", "
    "); - normalized = withAttachment(normalized, room); - return normalized.startsWith("" + html + ""; - } - - private static String div(String html) { - return "
    " + html + "
    "; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/text/HtmlText.java b/ts3-client/core/src/main/java/com/ts3client/text/HtmlText.java deleted file mode 100644 index 1b4b059..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/text/HtmlText.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.ts3client.text; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** The readable text of an HTML fragment such as a chat log entry, for searching it. */ -public final class HtmlText { - - private static final Pattern BREAK = Pattern.compile("(?i)|"); - private static final Pattern TAG = Pattern.compile("<[^>]*>"); - private static final Pattern ENTITY = Pattern.compile("&(#[0-9]+|#[xX][0-9a-fA-F]+|[a-zA-Z]+);"); - - private HtmlText() { - } - - public static String plain(String html) { - if (html == null || html.isEmpty()) return ""; - String text = TAG.matcher(BREAK.matcher(html).replaceAll("\n")).replaceAll(""); - return text.indexOf('&') < 0 ? text : unescape(text); - } - - private static String unescape(String s) { - Matcher m = ENTITY.matcher(s); - // Android < API 34 lacks Matcher.appendReplacement/appendTail(StringBuilder); original: - // StringBuilder out = new StringBuilder(s.length()); - StringBuffer out = new StringBuffer(s.length()); - while (m.find()) { - String decoded = decode(m.group(1)); - m.appendReplacement(out, Matcher.quoteReplacement(decoded == null ? m.group() : decoded)); - } - m.appendTail(out); - return out.toString(); - } - - private static String decode(String entity) { - if (entity.charAt(0) == '#') { - try { - int cp = entity.length() > 1 && (entity.charAt(1) == 'x' || entity.charAt(1) == 'X') - ? Integer.parseInt(entity.substring(2), 16) - : Integer.parseInt(entity.substring(1)); - return Character.isValidCodePoint(cp) ? new String(Character.toChars(cp)) : null; - } catch (NumberFormatException e) { - return null; - } - } - return switch (entity) { - case "amp" -> "&"; - case "lt" -> "<"; - case "gt" -> ">"; - case "quot" -> "\""; - case "apos" -> "'"; - case "nbsp" -> " "; - default -> null; - }; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/text/Json.java b/ts3-client/core/src/main/java/com/ts3client/text/Json.java deleted file mode 100644 index d0d6a4a..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/text/Json.java +++ /dev/null @@ -1,167 +0,0 @@ -package com.ts3client.text; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * Just enough JSON for the small objects other clients put into chat messages: values - * come back as {@link String}, {@link Double}, {@link Boolean}, {@code null}, - * {@link List} and {@link Map}. - */ -public final class Json { - - private final String src; - private int pos; - - private Json(String src) { - this.src = src; - } - - /** @return the object {@code text} holds, or {@code null} when it is not a JSON object */ - public static Map parseObject(String text) { - if (text == null) return null; - try { - Json json = new Json(text); - json.skipSpace(); - if (json.peek() != '{') return null; - @SuppressWarnings("unchecked") - Map object = (Map) json.value(); - json.skipSpace(); - return json.pos == text.length() ? object : null; - } catch (IllegalArgumentException | IndexOutOfBoundsException malformed) { - return null; - } - } - - /** {@code s} as a JSON string literal. */ - public static String quote(String s) { - StringBuilder out = new StringBuilder(s.length() + 2).append('"'); - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - switch (c) { - case '"' -> out.append("\\\""); - case '\\' -> out.append("\\\\"); - case '\n' -> out.append("\\n"); - case '\r' -> out.append("\\r"); - case '\t' -> out.append("\\t"); - default -> { - if (c < 0x20) out.append(String.format("\\u%04x", (int) c)); - else out.append(c); - } - } - } - return out.append('"').toString(); - } - - private Object value() { - skipSpace(); - char c = peek(); - return switch (c) { - case '{' -> object(); - case '[' -> array(); - case '"' -> string(); - case 't' -> literal("true", Boolean.TRUE); - case 'f' -> literal("false", Boolean.FALSE); - case 'n' -> literal("null", null); - default -> number(); - }; - } - - private Map object() { - Map object = new LinkedHashMap<>(); - pos++; - skipSpace(); - if (peek() == '}') { - pos++; - return object; - } - while (true) { - skipSpace(); - String key = string(); - skipSpace(); - expect(':'); - object.put(key, value()); - skipSpace(); - if (peek() == ',') { - pos++; - continue; - } - expect('}'); - return object; - } - } - - private List array() { - List array = new ArrayList<>(); - pos++; - skipSpace(); - if (peek() == ']') { - pos++; - return array; - } - while (true) { - array.add(value()); - skipSpace(); - if (peek() == ',') { - pos++; - continue; - } - expect(']'); - return array; - } - } - - private String string() { - expect('"'); - StringBuilder out = new StringBuilder(); - while (true) { - char c = src.charAt(pos++); - if (c == '"') return out.toString(); - if (c != '\\') { - out.append(c); - continue; - } - char e = src.charAt(pos++); - switch (e) { - case 'b' -> out.append('\b'); - case 'f' -> out.append('\f'); - case 'n' -> out.append('\n'); - case 'r' -> out.append('\r'); - case 't' -> out.append('\t'); - case 'u' -> { - out.append((char) Integer.parseInt(src.substring(pos, pos + 4), 16)); - pos += 4; - } - default -> out.append(e); - } - } - } - - private Double number() { - int start = pos; - while (pos < src.length() && "+-0123456789.eE".indexOf(src.charAt(pos)) >= 0) pos++; - if (start == pos) throw new IllegalArgumentException("Unexpected " + peek()); - return Double.valueOf(src.substring(start, pos)); - } - - private Object literal(String word, Object value) { - if (!src.startsWith(word, pos)) throw new IllegalArgumentException("Expected " + word); - pos += word.length(); - return value; - } - - private void expect(char c) { - if (peek() != c) throw new IllegalArgumentException("Expected " + c); - pos++; - } - - private char peek() { - return src.charAt(pos); - } - - private void skipSpace() { - while (pos < src.length() && Character.isWhitespace(src.charAt(pos))) pos++; - } -} diff --git a/ts3-client/core/src/main/java/com/ts3client/text/TextQuery.java b/ts3-client/core/src/main/java/com/ts3client/text/TextQuery.java deleted file mode 100644 index fad5bcd..0000000 --- a/ts3-client/core/src/main/java/com/ts3client/text/TextQuery.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.ts3client.text; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.regex.PatternSyntaxException; - -/** - * What a find bar is looking for: the typed text and how to match it. Immutable, so a - * query can be handed to a background search while the user keeps typing. - */ -public final class TextQuery { - - public static final TextQuery EMPTY = new TextQuery("", false, false, false); - - public final String text; - public final boolean matchCase; - public final boolean wholeWord; - public final boolean regex; - /** {@code null} when the query is empty or not a valid regular expression. */ - private final Pattern pattern; - private final String error; - - public TextQuery(String text, boolean matchCase, boolean wholeWord, boolean regex) { - this.text = text == null ? "" : text; - this.matchCase = matchCase; - this.wholeWord = wholeWord; - this.regex = regex; - Pattern p = null; - String err = null; - if (!this.text.isEmpty()) { - try { - p = compile(); - } catch (PatternSyntaxException e) { - err = e.getDescription(); - } - } - this.pattern = p; - this.error = err; - } - - private Pattern compile() { - String body = regex ? text : Pattern.quote(text); - if (wholeWord) body = "(?/~} and {@code channel:///}. - */ -public final class TsLink { - - public static final String CLIENT_SCHEME = "client://"; - public static final String CHANNEL_SCHEME = "channel://"; - /** Opens the offline message inbox, as the "unread offline messages" log line does. */ - public static final String OFFLINE_MESSAGES_HREF = "offline://"; - - /** A parsed {@code client://} or {@code channel://} link. */ - public static final class Ref { - public final boolean client; - public final int id; - /** Client unique id, or {@code ""} for channel links / when absent. */ - public final String uniqueId; - /** Nickname or channel name, or {@code ""} when absent. */ - public final String name; - - Ref(boolean client, int id, String uniqueId, String name) { - this.client = client; - this.id = id; - this.uniqueId = uniqueId; - this.name = name; - } - } - - private TsLink() { - } - - /** Parses a TS link, or returns {@code null} if it is not one. */ - public static Ref parse(String href) { - if (href == null) return null; - boolean client = startsWithIgnoreCase(href, CLIENT_SCHEME); - if (!client && !startsWithIgnoreCase(href, CHANNEL_SCHEME)) return null; - - String rest = href.substring((client ? CLIENT_SCHEME : CHANNEL_SCHEME).length()); - int slash = rest.indexOf('/'); - String idPart = slash < 0 ? rest : rest.substring(0, slash); - String tail = slash < 0 ? "" : rest.substring(slash + 1); - - int id; - try { - id = Integer.parseInt(idPart.trim()); - } catch (NumberFormatException e) { - return null; - } - - String uid = ""; - String name = tail; - if (client) { - int tilde = tail.indexOf('~'); - if (tilde >= 0) { - uid = tail.substring(0, tilde); - name = tail.substring(tilde + 1); - } else { - uid = tail; - name = ""; - } - } - return new Ref(client, id, decode(uid), decode(name)); - } - - public static boolean isOfflineMessages(String href) { - return href != null && startsWithIgnoreCase(href, OFFLINE_MESSAGES_HREF); - } - - public static String offlineMessagesBBCode(String label) { - return "[URL=" + OFFLINE_MESSAGES_HREF + "]" + label + "[/URL]"; - } - - public static String clientHref(int clientId, String uniqueId, String nickname) { - return CLIENT_SCHEME + clientId + "/" + encode(uniqueId) + "~" + encode(nickname); - } - - public static String channelHref(int channelId, String name) { - return CHANNEL_SCHEME + channelId + "/" + encode(name); - } - - /** The BBCode TeamSpeak inserts when a client is dragged into the text box. */ - public static String clientBBCode(int clientId, String uniqueId, String nickname) { - return "[URL=" + clientHref(clientId, uniqueId, nickname) + "]" + nickname + "[/URL]"; - } - - /** The BBCode TeamSpeak inserts when a channel is dragged into the text box. */ - public static String channelBBCode(int channelId, String name) { - return "[URL=" + channelHref(channelId, name) + "]" + name + "[/URL]"; - } - - private static boolean startsWithIgnoreCase(String s, String prefix) { - return s.regionMatches(true, 0, prefix, 0, prefix.length()); - } - - private static String encode(String s) { - if (s == null) return ""; - try { - // TS3 leaves the base64 padding of unique ids unescaped, so match that. - return URLEncoder.encode(s, "UTF-8").replace("+", "%20").replace("%3D", "="); - } catch (UnsupportedEncodingException e) { - return s; - } - } - - private static String decode(String s) { - if (s == null || s.isEmpty()) return ""; - try { - return URLDecoder.decode(s, "UTF-8"); - } catch (UnsupportedEncodingException | IllegalArgumentException e) { - return s; - } - } -} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioBackend.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioBackend.java new file mode 100644 index 0000000..f76624f --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioBackend.java @@ -0,0 +1,37 @@ +package eu.lixko.ts3j.client.audio; + +import eu.lixko.ts3j.client.audio.opus.OpusCodec; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.sound.SoundPlayer; +import eu.lixko.ts3j.client.sound.PackSoundPlayer; + +/** + * A platform's audio stack: its devices and its libopus. Injected into the connection + * layer so the core stays independent of any concrete audio stack; the voice pipelines + * and the sound player on top are the same everywhere. + */ +public interface AudioBackend { + + AudioIo io(); + + OpusCodec opus(); + + /** How incoming voice reaches this platform's devices. */ + StreamingVoiceOutput.Lines outputLines(); + + default VoiceInput createInput(Settings settings) { + return new CaptureVoiceInput(settings, io(), opus()); + } + + default VoiceOutput createOutput(Settings settings) { + return new StreamingVoiceOutput(io(), opus(), settings.outputDevice, outputLines()); + } + + /** Player for notification sounds (sound packs); shared by all connections. */ + default SoundPlayer createSoundPlayer(Settings settings) { + return new PackSoundPlayer(io(), opus(), settings.outputDevice); + } + + /** Human-readable codec/backend description, e.g. for an "about" line. */ + String description(); +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioCapture.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioCapture.java new file mode 100644 index 0000000..d297278 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioCapture.java @@ -0,0 +1,26 @@ +package eu.lixko.ts3j.client.audio; + +/** + * An open microphone line, delivering 16-bit little-endian PCM at + * {@link VoiceFormat#SAMPLE_RATE}. + * + *

    Modelled on Java Sound's {@code TargetDataLine} so the capture pipeline does + * not care which platform audio API delivers it. + */ +public interface AudioCapture extends AutoCloseable { + + /** Channel count actually negotiated with the device. */ + int channels(); + + /** Begins capturing; audio read before this call is not delivered. */ + void start(); + + /** + * Blocks until {@code length} bytes are captured. Returns fewer bytes only when the + * line is closing or the calling thread was interrupted. + */ + int read(byte[] buffer, int offset, int length); + + @Override + void close(); +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioDevice.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioDevice.java new file mode 100644 index 0000000..6b2fa0b --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioDevice.java @@ -0,0 +1,13 @@ +package eu.lixko.ts3j.client.audio; + +/** A selectable audio device. {@code id} is what gets persisted in the settings. */ +public record AudioDevice(String id, String label) { + + /** The implicit entry that lets the platform choose. */ + public static final AudioDevice DEFAULT = new AudioDevice("", "(System default)"); + + @Override + public String toString() { + return label; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioFrameListener.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioFrameListener.java new file mode 100644 index 0000000..386d4e2 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioFrameListener.java @@ -0,0 +1,17 @@ +package eu.lixko.ts3j.client.audio; + +/** Receives frames of PCM audio as they pass through the capture or playback chain. */ +@FunctionalInterface +public interface AudioFrameListener { + + /** + * Called with one frame of interleaved samples in [-1, 1]. + * + *

    The array is reused between calls, so copy anything you need to keep. Called from + * the audio thread: do not block. + * + * @param interleaved samples, {@code channels} per sample position + * @param channels number of interleaved channels + */ + void onFrame(float[] interleaved, int channels); +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioIo.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioIo.java new file mode 100644 index 0000000..b950df5 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioIo.java @@ -0,0 +1,23 @@ +package eu.lixko.ts3j.client.audio; + +import java.util.List; + +/** The platform's audio devices: what can be picked, and opening lines on them. */ +public interface AudioIo { + + /** Devices that can provide microphone lines, {@link AudioDevice#DEFAULT} first. */ + List inputDevices(); + + /** Devices that can provide speaker lines, {@link AudioDevice#DEFAULT} first. */ + List outputDevices(); + + /** + * Opens a capture line at {@link VoiceFormat#SAMPLE_RATE}, preferring + * {@code preferredChannels} but falling back to what the device takes; inspect + * {@link AudioCapture#channels()} for the result. An empty id means the default device. + */ + AudioCapture openCapture(String deviceId, int preferredChannels) throws Exception; + + /** Opens a playback line; see {@link #openCapture} for the channel negotiation. */ + AudioPlayback openPlayback(String deviceId, int preferredChannels) throws Exception; +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioPlayback.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioPlayback.java new file mode 100644 index 0000000..3e65192 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioPlayback.java @@ -0,0 +1,31 @@ +package eu.lixko.ts3j.client.audio; + +/** + * An open speaker line, accepting 16-bit little-endian PCM at + * {@link VoiceFormat#SAMPLE_RATE}. + * + *

    Modelled on Java Sound's {@code SourceDataLine} so the playback pipeline does + * not care which platform audio API plays it. + */ +public interface AudioPlayback extends AutoCloseable { + + /** Channel count actually negotiated with the device. */ + int channels(); + + /** Begins playing whatever is written from now on. */ + void start(); + + /** + * Blocks until the audio has been queued for playback. + * + * @throws IllegalStateException once the line is gone for good (its device went away, + * say), so the caller can open another + */ + void write(byte[] buffer, int offset, int length); + + /** Blocks until everything already written has been played out. */ + void drain(); + + @Override + void close(); +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/CaptureVoiceInput.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/CaptureVoiceInput.java new file mode 100644 index 0000000..8841fdc --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/CaptureVoiceInput.java @@ -0,0 +1,592 @@ +package eu.lixko.ts3j.client.audio; + +import com.github.manevolent.ts3j.enums.CodecType; +import eu.lixko.ts3j.client.audio.opus.OpusCodec; +import eu.lixko.ts3j.client.audio.opus.OpusEncoder; +import eu.lixko.ts3j.client.audio.processing.AudioProcessor; +import eu.lixko.ts3j.client.audio.processing.ns.SuppressionLevel; +import eu.lixko.ts3j.client.audio.vad.RnnSpeechDetector; +import eu.lixko.ts3j.client.config.Settings; + +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; + +/** + * The {@link VoiceInput} every platform shares: captures the microphone, applies voice-activation + * or push-to-talk gating, and Opus-encodes 20 ms frames. + * + *

    The capture line comes from the platform's {@link AudioIo}; it is opened in stereo + * when the device offers it. Voice + * ({@code OPUS_VOICE}) is transmitted mono, from the downmix, so the pre-processing + * chain and VAD see a single channel; the music codec ({@code OPUS_MUSIC}) transmits + * the stereo capture as-is. + * + *

    A dedicated capture thread fills a small packet queue while ts3j polls + * {@link #isReady()} / {@link #provide()} on its own timer, decoupling capture from + * network sending. When the gate closes and the queue drains {@link #isReady()} + * returns {@code false}, prompting ts3j to emit the terminating empty voice packet. + */ +public final class CaptureVoiceInput implements VoiceInput { + + /** + * How long the gate stays open after the last active frame. TS3 counts 64 of its + * 10 ms preprocessor frames before closing, so the tail of a word is never clipped. + */ + private static final int HANGOVER_MS = 640; + + /** + * Audio replayed when the gate opens, so a word's onset is not swallowed by the frame + * that detected it. TS3 keeps up to three 10 ms buffers ({@code vad_extrabuffersize} + * defaults to 2, plus one). + */ + private static final int PREROLL_MS = 30; + + private static final int HANGOVER_FRAMES = + Math.max(1, HANGOVER_MS * VoiceFormat.SAMPLE_RATE / 1000 / VoiceFormat.FRAME_SIZE); + private static final int PREROLL_FRAMES = + Math.max(1, PREROLL_MS * VoiceFormat.SAMPLE_RATE / 1000 / VoiceFormat.FRAME_SIZE); + /** How long stop() waits for the capture loop to finish its frame. */ + private static final long STOP_TIMEOUT_MS = 500; + + private final ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue<>(); + private final AtomicBoolean muted = new AtomicBoolean(false); + private final AtomicBoolean localMuted = new AtomicBoolean(false); + private final AtomicBoolean transmitting = new AtomicBoolean(false); + private final AtomicBoolean pttDown = new AtomicBoolean(false); + private final AtomicBoolean forceDown = new AtomicBoolean(false); + private final AtomicBoolean running = new AtomicBoolean(false); + + private volatile Settings.InputMode mode; + private volatile Settings.VadMode vadMode; + private volatile double thresholdDb; + private volatile double speechThreshold; + private volatile boolean vadOverPtt; + private volatile double inputGain; + private volatile CodecType codec = CodecType.OPUS_VOICE; + private volatile int redundancyDelay; + private volatile int redundancyCopies; + + private final SpeechProbabilityDetector speechDetector = + new RnnSpeechDetector(VoiceFormat.SAMPLE_RATE); + private final AudioProcessor processor = new AudioProcessor(); + + private volatile Consumer levelListener; // input level, InputLevel scale + private volatile Consumer talkListener; // local talk-state changes + private volatile Runnable mutedTalkListener; // speech detected while muted + private volatile AudioFrameListener monitorListener; // local monitoring of what is sent + private boolean mutedTalking; + + private final AudioIo io; + private final OpusCodec opus; + private volatile String deviceName; + + private final Object encoderLock = new Object(); + private volatile OpusParameters params; + private OpusParameters appliedParams; + private OpusCodec.Application encoderApplication; + private volatile int encoderChannels = 1; + private volatile int captureChannels = 1; + + private Thread captureThread; + private AudioCapture line; + private OpusEncoder encoder; + + private int hangover; + private boolean lastTransmitting; + + // Ring of recent frames captured while the gate was shut. + private final float[][] preroll = new float[PREROLL_FRAMES][]; + private int prerollTail; + private int prerollCount; + + public CaptureVoiceInput(Settings settings, AudioIo io, OpusCodec opus) { + this.io = io; + this.opus = opus; + this.deviceName = settings.inputDevice; + this.mode = settings.inputMode; + this.vadMode = settings.vadMode; + this.thresholdDb = settings.vadThresholdDb; + this.speechThreshold = settings.speechThreshold; + this.vadOverPtt = settings.vadOverPtt; + this.inputGain = settings.inputVolume; + this.params = OpusParameters.from(settings); + this.codec = codecFor(params); + setRedundancy(settings.redundancyDelay, settings.redundancyCopies); + processor.setNoiseSuppression(settings.denoise); + processor.setSuppressionLevel(SuppressionLevel.fromDenoiserLevel(settings.denoiserLevel)); + processor.setTransientSuppression(settings.typingAttenuation); + processor.setGainControl(settings.agc); + processor.setGainBoost(settings.agcBoostDb); + } + + // ---- live configuration (safe to call from the UI thread) ---- + + @Override + public synchronized void setInputDevice(String deviceId) { + String device = deviceId == null ? "" : deviceId; + if (device.equals(deviceName)) return; + deviceName = device; + if (running.get()) { + stop(); + start(); + } + } + + public void setMode(Settings.InputMode mode) { + this.mode = mode; + } + + public void setVadMode(Settings.VadMode mode) { + this.vadMode = mode; + speechDetector.reset(); + } + + public void setThresholdDb(double db) { + this.thresholdDb = db; + } + + public void setSpeechThreshold(double threshold) { + this.speechThreshold = threshold; + } + + public void setVadOverPtt(boolean enabled) { + this.vadOverPtt = enabled; + } + + public void setInputGain(double gain) { + this.inputGain = gain; + } + + public void setNoiseSuppression(boolean enabled) { + processor.setNoiseSuppression(enabled); + } + + public void setDenoiserLevel(int level) { + processor.setSuppressionLevel(SuppressionLevel.fromDenoiserLevel(level)); + } + + public void setTypingAttenuation(boolean enabled) { + processor.setTransientSuppression(enabled); + } + + public void setAgc(boolean enabled) { + processor.setGainControl(enabled); + } + + public void setAgcBoost(int db) { + processor.setGainBoost(db); + } + + @Override + public void keyPressed() { + processor.keyPressed(); + } + + /** + * Stages new encoder settings; the capture thread picks them up on the next frame + * (or {@link #start()} applies them directly when idle). + */ + public void setOpusParameters(OpusParameters p) { + this.params = p; + synchronized (encoderLock) { + // While capturing, the codec flag flips together with the encoder swap so + // no packet is ever tagged with a codec it wasn't encoded for. + if (encoder == null) this.codec = codecFor(p); + } + } + + @Override + public void setRedundancy(int delayMillis, int copies) { + this.redundancyDelay = Math.max(0, delayMillis); + this.redundancyCopies = Math.max(1, Math.min(Settings.MAX_REDUNDANCY_COPIES, copies)); + } + + private static OpusCodec.Application applicationFor(OpusParameters p) { + return p.music ? OpusCodec.Application.AUDIO : OpusCodec.Application.VOIP; + } + + private static CodecType codecFor(OpusParameters p) { + return p.music ? CodecType.OPUS_MUSIC : CodecType.OPUS_VOICE; + } + + /** + * Channels to transmit: TeamSpeak's {@code OPUS_MUSIC} stream is stereo, + * {@code OPUS_VOICE} is mono. A mono-only capture device caps this at one. + */ + private int channelsFor(OpusParameters p) { + return (p.music && captureChannels >= 2) ? 2 : 1; + } + + /** Creates or reconfigures the encoder to match {@code p}. Call under {@link #encoderLock}. */ + private void applyParams(OpusParameters p) { + OpusCodec.Application application = applicationFor(p); + int channels = channelsFor(p); + // Application (VOIP vs AUDIO) and channel count are fixed at creation, so + // switching voice<->music means building a new encoder. + if (encoder == null || application != encoderApplication || channels != encoderChannels) { + OpusEncoder replacement = opus.createEncoder( + VoiceFormat.SAMPLE_RATE, VoiceFormat.FRAME_SIZE, channels, application); + configureEncoder(replacement, p); + OpusEncoder previous = encoder; + encoder = replacement; + encoderApplication = application; + encoderChannels = channels; + if (previous != null) previous.close(); + } else { + configureEncoder(encoder, p); + } + codec = codecFor(p); + appliedParams = p; + } + + private static void configureEncoder(OpusEncoder enc, OpusParameters p) { + enc.setBitrate(p.bitrate); + enc.setComplexity(p.complexity); + enc.setVbr(p.vbr); + enc.setInbandFec(p.fec); + enc.setExpectedPacketLoss(p.expectedPacketLoss); + enc.setSignal(p.music ? OpusEncoder.Signal.MUSIC : OpusEncoder.Signal.VOICE); + } + + public void setLevelListener(Consumer l) { + this.levelListener = l; + } + + public void setTalkListener(Consumer l) { + this.talkListener = l; + } + + @Override + public void setMonitorListener(AudioFrameListener l) { + this.monitorListener = l; + } + + @Override + public void setMutedTalkListener(Runnable l) { + this.mutedTalkListener = l; + } + + public void setPushToTalk(boolean down) { + this.pttDown.set(down); + } + + @Override + public void setForceTransmit(boolean down) { + this.forceDown.set(down); + } + + public void setMuted(boolean m) { + this.muted.set(m); + } + + @Override + public void setLocalMuted(boolean m) { + this.localMuted.set(m); + } + + @Override + public boolean isLocalMuted() { + return localMuted.get(); + } + + // ---- lifecycle ---- + + public synchronized void start() { + if (running.get()) return; + try { + line = io.openCapture(deviceName, VoiceFormat.MAX_CHANNELS); + captureChannels = line.channels(); + synchronized (encoderLock) { + applyParams(params); + } + } catch (Throwable t) { + cleanup(); + throw new RuntimeException("Could not start microphone: " + t.getMessage(), t); + } + speechDetector.reset(); + processor.reset(); + running.set(true); + captureThread = new Thread(this::captureLoop, "ts3j-mic-capture"); + captureThread.setDaemon(true); + // Falling behind overruns the device's buffer, losing audio. + captureThread.setPriority(Thread.MAX_PRIORITY); + captureThread.start(); + } + + public synchronized void stop() { + running.set(false); + Thread capture = captureThread; + captureThread = null; + if (line != null) { + line.close(); // wakes the capture loop's blocking read + line = null; + } + if (capture != null) { + // Let the loop finish its frame, so it cannot reopen the gate or overlap a restart. + capture.interrupt(); + try { + capture.join(STOP_TIMEOUT_MS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + cleanup(); + queue.clear(); + setTransmitting(false); + } + + private void cleanup() { + if (line != null) { + line.close(); + line = null; + } + synchronized (encoderLock) { + if (encoder != null) { + try { + encoder.close(); + } catch (Exception ignored) { + } + encoder = null; + encoderApplication = null; + appliedParams = null; + } + } + } + + private void captureLoop() { + final int frameSamples = VoiceFormat.FRAME_SIZE; + final int channels = captureChannels; + final byte[] buf = new byte[frameSamples * 2 * channels]; + final float[] pcm = new float[frameSamples * channels]; // interleaved capture + // Analysis (level, VAD) always runs on a mono downmix; with a mono device that + // is the capture buffer itself, so nothing is copied. + final float[] mono = (channels == 1) ? pcm : new float[frameSamples]; + + // Held locally so a concurrent stop() closing the line cannot null it mid-loop. + final AudioCapture capture = line; + capture.start(); + + while (running.get()) { + // A short read only happens once the line is closing, or on interruption. + if (capture.read(buf, 0, buf.length) < buf.length) break; + + // 16-bit LE -> float, with input gain + for (int i = 0; i < pcm.length; i++) { + int lo = buf[2 * i] & 0xFF; + int hi = buf[2 * i + 1]; + short s = (short) ((hi << 8) | lo); + float f = (float) (s / 32768.0 * inputGain); + if (f > 1f) f = 1f; + else if (f < -1f) f = -1f; + pcm[i] = f; + } + if (channels > 1) { + for (int i = 0; i < frameSamples; i++) { + float sum = 0; + for (int c = 0; c < channels; c++) sum += pcm[i * channels + c]; + mono[i] = sum / channels; + } + } + + byte[] packet = null; + synchronized (encoderLock) { + OpusParameters p = params; + if (p != appliedParams && encoder != null) applyParams(p); + boolean stereo = encoderChannels == 2; + + // As in TS3, the speech detector judges the raw microphone signal, while + // the level meter and volume gate see the processed one. + double probability = usesSpeechDetector() + ? speechDetector.process(mono, frameSamples) : 0.0; + + // Processing is a voice-chain stage on the mono path. A stereo (music) + // stream bypasses it and is transmitted as captured. + if (!stereo) processor.process(mono, frameSamples); + + double db = InputLevel.toDb(mono, frameSamples); + Consumer ll = levelListener; + if (ll != null) ll.accept(db); + + boolean wasOpen = transmitting.get(); + boolean open = decideGate(db, probability); + setTransmitting(open); + + if (open && !muted.get() && encoder != null) { + try { + // On the opening edge, send the buffered lead-in first so the + // word's onset isn't lost to the frame that detected it. + if (!wasOpen) { + flushPreroll(stereo); + } + float[] sent = stereo ? pcm : mono; + packet = encoder.encode(sent); + monitor(sent, stereo ? encoderChannels : 1); + } catch (Exception ignored) { + } + } + if (!open) { + rememberForPreroll(stereo ? pcm : mono); + } + } + + if (packet != null && packet.length > 0) { + offer(packet); + } + } + } + + private void offer(byte[] packet) { + queue.offer(packet); + // Guard against unbounded growth if the network stalls. + while (queue.size() > 10) queue.poll(); + } + + /** Keeps the most recent frames while the gate is shut, for {@link #flushPreroll}. */ + private void rememberForPreroll(float[] frame) { + float[] slot = preroll[prerollTail]; + if (slot == null || slot.length != frame.length) { + slot = new float[frame.length]; + preroll[prerollTail] = slot; + } + System.arraycopy(frame, 0, slot, 0, frame.length); + prerollTail = (prerollTail + 1) % PREROLL_FRAMES; + if (prerollCount < PREROLL_FRAMES) prerollCount++; + } + + /** Encodes and queues the buffered lead-in, oldest first. Call under {@link #encoderLock}. */ + private void flushPreroll(boolean stereo) { + int expected = stereo ? VoiceFormat.FRAME_SIZE * encoderChannels : VoiceFormat.FRAME_SIZE; + for (int i = 0; i < prerollCount; i++) { + int idx = (prerollTail - prerollCount + i + PREROLL_FRAMES) % PREROLL_FRAMES; + float[] frame = preroll[idx]; + // A channel-count change between capture and flush invalidates the buffer. + if (frame == null || frame.length != expected) continue; + try { + byte[] p = encoder.encode(frame); + if (p != null && p.length > 0) offer(p); + monitor(frame, stereo ? encoderChannels : 1); + } catch (Exception ignored) { + } + } + prerollCount = 0; + } + + /** Whether the gate may consult the speech detector, so it must follow the signal. */ + private boolean usesSpeechDetector() { + if (vadMode == Settings.VadMode.VOLUME_GATE) return false; + Settings.InputMode m = mode; + return m == Settings.InputMode.VOICE_ACTIVATION || (m == Settings.InputMode.PUSH_TO_TALK && vadOverPtt); + } + + private boolean decideGate(double db, double probability) { + if (muted.get() || localMuted.get()) { + hangover = 0; + detectMutedSpeech(db); + return false; + } + mutedTalking = false; + if (forceDown.get()) return true; + switch (mode) { + case CONTINUOUS: + return true; + case PUSH_TO_TALK: + if (pttDown.get()) return true; + return vadOverPtt && voiceActivated(db, probability); + case VOICE_ACTIVATION: + default: + return voiceActivated(db, probability); + } + } + + /** + * Applies the selected VAD mode with a hangover so trailing syllables aren't clipped. + * + *

    The modes match the TS3 client's: the volume gate alone, the speech detector + * alone, or both together. Volume Gate skips the detector entirely, as TS3 does. + */ + private boolean voiceActivated(double db, double probability) { + boolean detected = switch (vadMode) { + case VOLUME_GATE -> db >= thresholdDb; + case AUTOMATIC -> probability >= speechThreshold; + case HYBRID -> db >= thresholdDb && probability >= speechThreshold; + }; + if (detected) { + hangover = HANGOVER_FRAMES; + return true; + } + if (hangover > 0) { + hangover--; + return true; + } + return false; + } + + /** + * Reports the start of a talk burst that the mute is swallowing. The volume gate + * alone decides here: the speech detector's state is kept for real transmission. + */ + private void detectMutedSpeech(double db) { + boolean talking = db >= thresholdDb; + if (talking && !mutedTalking) { + Runnable listener = mutedTalkListener; + if (listener != null) listener.run(); + } + mutedTalking = talking; + } + + /** Hands a transmitted frame to the monitor, if one is attached. */ + private void monitor(float[] frame, int channels) { + AudioFrameListener l = monitorListener; + if (l != null) l.onFrame(frame, channels); + } + + private void setTransmitting(boolean t) { + transmitting.set(t); + if (t != lastTransmitting) { + lastTransmitting = t; + Consumer tl = talkListener; + if (tl != null) tl.accept(t); + } + } + + // ---- ts3j Microphone contract ---- + + @Override + public boolean isMuted() { + return muted.get(); + } + + @Override + public boolean isReady() { + // Keep the ts3j sender "active" while we're transmitting or still have + // buffered packets. When both are false ts3j sends the terminating packet. + return transmitting.get() || !queue.isEmpty(); + } + + @Override + public boolean isLiveCapture() { + return true; + } + + @Override + public CodecType getCodec() { + return codec; + } + + @Override + public int getRedundancyDelay() { + return redundancyDelay; + } + + @Override + public int getRedundancyCopies() { + return redundancyCopies; + } + + @Override + public byte[] provide() { + byte[] p = queue.poll(); + return p != null ? p : new byte[0]; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/Fft.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/Fft.java new file mode 100644 index 0000000..dda7593 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/Fft.java @@ -0,0 +1,68 @@ +package eu.lixko.ts3j.client.audio; + +/** + * In-place iterative radix-2 Cooley–Tukey FFT shared by the voice DSP stages. + * All arrays must have a power-of-two length. Pure math, no platform dependencies. + */ +public final class Fft { + + private Fft() { + } + + /** Forward transform (unnormalised). */ + public static void forward(double[] re, double[] im) { + transform(re, im, false); + } + + /** Inverse transform, normalised by {@code 1/n} so it inverts {@link #forward}. */ + public static void inverse(double[] re, double[] im) { + transform(re, im, true); + int n = re.length; + double scale = 1.0 / n; + for (int i = 0; i < n; i++) { + re[i] *= scale; + im[i] *= scale; + } + } + + private static void transform(double[] re, double[] im, boolean inverse) { + int n = re.length; + for (int i = 1, j = 0; i < n; i++) { + int bit = n >> 1; + for (; (j & bit) != 0; bit >>= 1) { + j ^= bit; + } + j ^= bit; + if (i < j) { + double tr = re[i]; + re[i] = re[j]; + re[j] = tr; + double ti = im[i]; + im[i] = im[j]; + im[j] = ti; + } + } + double sign = inverse ? 2 * Math.PI : -2 * Math.PI; + for (int len = 2; len <= n; len <<= 1) { + double ang = sign / len; + double wr = Math.cos(ang); + double wi = Math.sin(ang); + for (int i = 0; i < n; i += len) { + double curR = 1, curI = 0; + for (int k = 0; k < len / 2; k++) { + int a = i + k; + int b = i + k + len / 2; + double vr = re[b] * curR - im[b] * curI; + double vi = re[b] * curI + im[b] * curR; + re[b] = re[a] - vr; + im[b] = im[a] - vi; + re[a] += vr; + im[a] += vi; + double nr = curR * wr - curI * wi; + curI = curR * wi + curI * wr; + curR = nr; + } + } + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/InputLevel.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/InputLevel.java new file mode 100644 index 0000000..015a21c --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/InputLevel.java @@ -0,0 +1,58 @@ +package eu.lixko.ts3j.client.audio; + +/** + * Capture level on the scale the TeamSpeak 3 client puts on its voice-activation slider. + * + *

    TS3 stores {@code voiceactivation_level} in decibels but compares powers: its setter + * converts the slider value with {@code 10^(dB/10) * 0.0095} and its getter reports a + * measured power back with {@code 10*log10(power / 0.0095)}. The same reference constant is + * used here so a threshold of −40 means the same thing it does in TeamSpeak. + * + *

    The resulting scale runs from {@link #MIN_DB} to {@link #MAX_DB}, with 0 dB + * corresponding to roughly −20 dBFS and the default −40 to about + * −60 dBFS. + */ +public final class InputLevel { + + /** + * Mean-square level that reads as 0 dB, taken from the client's own dB conversion. + */ + private static final double REFERENCE_POWER = 0.0095; + + /** Lower end of the slider range. */ + public static final double MIN_DB = -50.0; + + /** Upper end of the slider range. */ + public static final double MAX_DB = 50.0; + + /** Reported when the frame is digital silence. */ + public static final double SILENCE_DB = MIN_DB; + + private InputLevel() { + } + + /** Level of {@code length} mono samples in [-1, 1], in dB on the scale above. */ + public static double toDb(float[] frame, int length) { + if (length <= 0) { + return SILENCE_DB; + } + double sumSq = 0; + for (int i = 0; i < length; i++) { + sumSq += (double) frame[i] * frame[i]; + } + return powerToDb(sumSq / length); + } + + /** Converts a mean-square power to the slider's dB scale. */ + public static double powerToDb(double power) { + if (power <= 0) { + return SILENCE_DB; + } + return Math.max(SILENCE_DB, 10.0 * Math.log10(power / REFERENCE_POWER)); + } + + /** Inverse of {@link #powerToDb}, matching the client's threshold conversion. */ + public static double dbToPower(double db) { + return Math.pow(10.0, db / 10.0) * REFERENCE_POWER; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/JitterBuffer.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/JitterBuffer.java new file mode 100644 index 0000000..de577e0 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/JitterBuffer.java @@ -0,0 +1,595 @@ +package eu.lixko.ts3j.client.audio; + +/** + * Adaptive jitter buffer for incoming voice packets. + * + *

    This is a port of the jitter buffer TeamSpeak itself uses: the official client links + * libspeex's {@code libspeex/jitter.c} verbatim (its diagnostics are still in the shipped + * binary) and drives it through the wrapper described in {@link #forTeamSpeakVoice}. The + * algorithm is what makes a voice stream survive a bad network: packets are reordered by + * timestamp, losses are reported so the codec can conceal them, and — most importantly — + * the playback delay continuously re-tunes itself to the measured jitter instead of being + * a fixed guess. + * + *

    How the delay adapts

    + * Every packet's arrival is recorded as a timing: how early (positive) or late + * (negative) it was relative to the moment it was needed. Timings are kept in three + * rotating sub-windows, each holding only the {@value #MAX_TIMINGS} latest arrivals + * it saw, which makes the set a cheap running estimate of the distribution's late tail. + * {@link #computeOptimalDelay()} then walks the {@value #TOP_DELAY} latest timings and picks + * the delay minimising {@code delay + lateCost * (packets that would then be late)}. The + * result is applied a whole {@link #delayStep} at a time, by dropping a frame to shrink the + * delay or inserting a concealed one to grow it, so the correction is inaudible. + * + *

    Timestamp units

    + * Timestamps and spans are in caller-defined ticks; the buffer never converts them to time. + * All comparisons are wrap-safe, so a tick counter may overflow freely. + * + *

    Not thread-safe: every call must be externally serialised. + */ +public final class JitterBuffer { + + /** Outcome of a {@link #get} call. */ + public enum Status { + /** A packet was available; see {@link #payload()}. */ + OK, + /** Nothing available — the caller should conceal {@link #span()} ticks of loss. */ + MISSING, + /** The buffer is growing its delay; the caller should insert {@link #span()} ticks. */ + INSERTION + } + + /** How many packets may be held at once, awaiting playback or reordering. */ + private static final int MAX_PACKETS = 200; + + /** Timings kept per sub-window. Only the latest arrivals are retained. */ + private static final int MAX_TIMINGS = 40; + + /** Rotating sub-windows the timings are spread over. */ + private static final int SUB_WINDOWS = 3; + + /** How many of the latest timings the delay search considers. */ + private static final int TOP_DELAY = 40; + + /** + * The latest arrival timings seen within one sub-window, sorted ascending. + * + *

    Only the {@value #MAX_TIMINGS} latest are kept: an arrival too early to displace + * any of them is counted but not stored, since the delay search only ever looks at the + * late tail. + */ + private static final class TimingWindow { + final int[] timing = new int[MAX_TIMINGS]; + /** Timings actually stored. */ + int filled; + /** Arrivals seen, including those too early to store. */ + int seen; + + void clear() { + filled = 0; + seen = 0; + } + + void add(int value) { + if (filled >= MAX_TIMINGS && value >= timing[filled - 1]) { + seen++; + return; + } + + int pos = 0; + while (pos < filled && value >= timing[pos]) pos++; + + if (pos < filled) { + int moveSize = filled - pos; + if (filled == MAX_TIMINGS) moveSize--; + System.arraycopy(timing, pos, timing, pos + 1, moveSize); + } + timing[pos] = value; + + seen++; + if (filled < MAX_TIMINGS) filled++; + } + } + + private final byte[][] data = new byte[MAX_PACKETS][]; + private final int[] timestamp = new int[MAX_PACKETS]; + private final int[] span = new int[MAX_PACKETS]; + /** Value of {@link #nextStop} when the packet arrived, or 0 if that is unknown. */ + private final int[] arrival = new int[MAX_PACKETS]; + + private final TimingWindow[] windows = new TimingWindow[SUB_WINDOWS]; + /** {@link #windows} in age order, newest first; rotated in place. */ + private final TimingWindow[] byAge = new TimingWindow[SUB_WINDOWS]; + + private final int delayStep; + private final int concealmentSize; + + private int bufferMargin; + private int maxLateRate; + private int lateCost; + private int windowSize; + private int subWindowSize; + + /** Playback position: the timestamp the next {@link #get} wants. */ + private int pointerTimestamp; + /** Timestamp playback will have reached by the time the next packet is needed. */ + private int nextStop; + /** Ticks handed out by the last {@link #get} beyond what was asked for. */ + private int buffered; + /** Ticks of concealment {@link #get} has been told to insert before reading on. */ + private int interpolationRequested; + /** Consecutive {@link #get} calls that found nothing. */ + private int lostCount; + /** True until the first packet arrives and defines the timeline. */ + private boolean resetState; + /** Self-tuned cost of a late packet, used when {@link #lateCost} is 0. */ + private int autoTradeoff; + + // Result of the most recent get(), kept here so the per-frame path allocates nothing. + private byte[] resultPayload; + private int resultTimestamp; + private int resultSpan; + + /** + * @param stepSize granularity of delay changes, and the span of one concealed frame; + * normally the span of a single packet + * @param margin extra delay held on top of the measured optimum + * @param maxLateRate percentage of packets allowed to arrive too late, which also sets + * how long a window the delay is estimated over + * @param lateCost cost of one late packet relative to delay, or 0 to self-tune + */ + public JitterBuffer(int stepSize, int margin, int maxLateRate, int lateCost) { + this.delayStep = stepSize; + this.concealmentSize = stepSize; + this.bufferMargin = margin; + this.lateCost = lateCost; + setMaxLateRate(maxLateRate); + + for (int i = 0; i < SUB_WINDOWS; i++) { + windows[i] = new TimingWindow(); + byAge[i] = windows[i]; + } + reset(); + } + + /** + * A buffer configured the way the official TeamSpeak client configures its own. + * + *

    Recovered from {@code ts3client_linux_amd64} (3.6.x): it calls + * {@code jitter_buffer_init(60)} and then sets margin 60 and max late rate 1, pulling + * one 60-tick frame per {@code jitter_buffer_get}. One tick is therefore a sixtieth of + * a 20 ms voice frame, so the delay moves in whole-frame steps, one frame of slack + * is held on top of the measured optimum, and the target is for no more than 1% of + * packets to arrive late — a deliberately conservative setting that estimates over a + * ~1.3 s window and is the reason TeamSpeak rides out network trouble smoothly. + * + * @param ticksPerFrame ticks spanned by one voice frame; see {@link #TEAMSPEAK_TICKS_PER_FRAME} + */ + public static JitterBuffer forTeamSpeakVoice(int ticksPerFrame) { + return new JitterBuffer(ticksPerFrame, ticksPerFrame, 1, 0); + } + + /** Ticks per voice frame in TeamSpeak's own timebase, i.e. a 20 ms frame in 1/3 ms units. */ + public static final int TEAMSPEAK_TICKS_PER_FRAME = 60; + + /** + * Sets the share of packets allowed to arrive too late, as a percentage. + * + *

    This doubles as the estimator's time constant: a stricter rate needs a + * proportionally longer window to observe that many late packets. + */ + public void setMaxLateRate(int rate) { + this.maxLateRate = Math.max(1, rate); + this.windowSize = 100 * TOP_DELAY / this.maxLateRate; + this.subWindowSize = this.windowSize / SUB_WINDOWS; + } + + /** + * Sets the extra delay held on top of the measured optimum. The timings already recorded + * are re-based onto it, so the delay moves at the next {@link #tick} rather than once the + * estimate has turned over. + */ + public void setMargin(int margin) { + shiftTimings(bufferMargin - margin); + this.bufferMargin = margin; + } + + public int margin() { + return bufferMargin; + } + + /** Ticks currently held ahead of the playback position, i.e. the live buffering depth. */ + public int bufferedSpan() { + int total = 0; + for (int i = 0; i < MAX_PACKETS; i++) { + if (data[i] != null && ge(timestamp[i], pointerTimestamp)) total += span[i]; + } + return total; + } + + /** True when no packet is held and playback has nothing left to drain. */ + public boolean isEmpty() { + for (int i = 0; i < MAX_PACKETS; i++) { + if (data[i] != null) return false; + } + return true; + } + + /** + * Drops every held packet and forgets both the timeline and the network estimate. + * + *

    Reserved for the cases where a speaker's position genuinely stopped meaning + * anything — a new speaker, or a silence long enough that the sequence may have been + * recycled. Notably not something to do between talk bursts: the timeline stays + * valid across a pause because the sender stops numbering while the receiver stops + * playing, and the estimate needs far longer than one burst to be worth anything. + */ + public void reset() { + for (int i = 0; i < MAX_PACKETS; i++) data[i] = null; + pointerTimestamp = 0; + nextStop = 0; + resetState = true; + lostCount = 0; + buffered = 0; + interpolationRequested = 0; + autoTradeoff = 32000; + for (TimingWindow w : windows) w.clear(); + System.arraycopy(windows, 0, byAge, 0, SUB_WINDOWS); + } + + /** + * Offers an arrived packet to the buffer. + * + * @param payload the packet, retained by reference until played or dropped + * @param timestamp the packet's position on the sender's timeline, in ticks + * @param span how many ticks the packet covers + */ + public void put(byte[] payload, int timestamp, int span) { + // Drop anything playback has already moved past. + if (!resetState) { + for (int i = 0; i < MAX_PACKETS; i++) { + if (data[i] != null && le(this.timestamp[i] + this.span[i], pointerTimestamp)) { + data[i] = null; + } + } + } + + // A packet that missed its slot still tells us how far behind the clock we are. + boolean late = !resetState && lt(timestamp, nextStop); + if (late) { + updateTimings(timestamp - nextStop - bufferMargin); + } + + // The consumer has stopped fetching; don't sit on packets it will never take. + if (lostCount > 20) reset(); + + // Ignore packets so late that even concealment has moved past them. + if (!resetState && !ge(timestamp + span + delayStep, pointerTimestamp)) return; + + int slot = -1; + for (int i = 0; i < MAX_PACKETS; i++) { + if (data[i] == null) { + slot = i; + break; + } + } + if (slot < 0) { + // Full: make room by discarding the oldest packet. + slot = 0; + int earliest = this.timestamp[0]; + for (int i = 1; i < MAX_PACKETS; i++) { + if (lt(this.timestamp[i], earliest)) { + earliest = this.timestamp[i]; + slot = i; + } + } + } + + data[slot] = payload; + this.timestamp[slot] = timestamp; + this.span[slot] = span; + this.arrival[slot] = (resetState || late) ? 0 : nextStop; + } + + /** + * Takes the next {@code desiredSpan} ticks of audio. + * + *

    On {@link Status#OK} the packet is in {@link #payload()}. On {@link Status#MISSING} + * or {@link Status#INSERTION} the caller must produce {@link #span()} ticks of + * concealment instead — for Opus that means decoding a null packet. + */ + public Status get(int desiredSpan) { + resultPayload = null; + + // The first packet to arrive defines where the timeline starts. + if (resetState) { + int oldest = 0; + boolean found = false; + for (int i = 0; i < MAX_PACKETS; i++) { + if (data[i] != null && (!found || lt(timestamp[i], oldest))) { + oldest = timestamp[i]; + found = true; + } + } + if (!found) { + resultTimestamp = 0; + resultSpan = interpolationRequested; + return Status.MISSING; + } + resetState = false; + pointerTimestamp = oldest; + nextStop = oldest; + } + + // A delay increase decided during the last tick(): pad before reading on. + if (interpolationRequested != 0) { + resultTimestamp = pointerTimestamp; + resultSpan = interpolationRequested; + pointerTimestamp += interpolationRequested; + interpolationRequested = 0; + buffered = resultSpan - desiredSpan; + return Status.INSERTION; + } + + int found = findPacket(desiredSpan); + if (found >= 0) { + lostCount = 0; + + // An on-time arrival: record how much slack it had. + if (arrival[found] != 0) { + updateTimings(timestamp[found] - arrival[found] - bufferMargin); + } + + resultPayload = data[found]; + resultTimestamp = timestamp[found]; + resultSpan = span[found]; + data[found] = null; + + pointerTimestamp = resultTimestamp + resultSpan; + buffered = resultSpan - desiredSpan; + return Status.OK; + } + + lostCount++; + + int optimal = computeOptimalDelay(); + if (optimal < 0) { + // The measured jitter wants a deeper buffer: insert without advancing playback. + shiftTimings(-optimal); + resultTimestamp = pointerTimestamp; + resultSpan = -optimal; + buffered = resultSpan - desiredSpan; + return Status.INSERTION; + } + + // Ordinary loss: conceal a whole number of frames and move on. + int concealed = roundDown(desiredSpan, concealmentSize); + resultTimestamp = pointerTimestamp; + resultSpan = concealed; + pointerTimestamp += concealed; + buffered = concealed - desiredSpan; + return Status.MISSING; + } + + /** + * The held packet sitting at the playback position, without consuming it. + * + *

    After a {@link Status#MISSING} the position has already stepped past the gap, so + * this is the packet immediately following the lost one — the one carrying the FEC copy + * that can rebuild it. {@code null} when that packet is missing too. + */ + public byte[] nextPayload() { + for (int i = 0; i < MAX_PACKETS; i++) { + if (data[i] != null && timestamp[i] == pointerTimestamp) return data[i]; + } + return null; + } + + /** The timestamp the next {@link #get} will play from. */ + public int position() { + return pointerTimestamp; + } + + /** Whole frames currently held, given a frame spans {@code frameSpan} ticks. */ + public int heldFrames(int frameSpan) { + int held = 0; + for (int i = 0; i < MAX_PACKETS; i++) { + if (data[i] != null) held += Math.max(1, span[i] / frameSpan); + } + return held; + } + + /** The packet returned by the last {@link #get}, or {@code null} if it was not {@link Status#OK}. */ + public byte[] payload() { + return resultPayload; + } + + /** Ticks covered by the last {@link #get}, whether a real packet or concealment. */ + public int span() { + return resultSpan; + } + + /** Timestamp of the last {@link #get}. */ + public int timestamp() { + return resultTimestamp; + } + + /** + * Advances the playback clock by one frame, after the audio from {@link #get} has been + * handed to the output. This is also where the delay is re-tuned. + */ + public void tick() { + updateDelay(); + nextStop = pointerTimestamp - Math.max(0, buffered); + buffered = 0; + } + + /** + * Advances the playback clock by one frame that the caller played from audio it still had + * from an earlier {@link #get}, instead of calling {@link #get} and {@link #tick}. + * + * @param remaining ticks of that audio still left after this frame + */ + public void remainingSpan(int remaining) { + updateDelay(); + nextStop = pointerTimestamp - remaining; + } + + /** Picks the held packet that best covers the chunk starting at the playback position. */ + private int findPacket(int desiredSpan) { + // Exact start, covering the whole chunk. + for (int i = 0; i < MAX_PACKETS; i++) { + if (data[i] != null && timestamp[i] == pointerTimestamp + && ge(timestamp[i] + span[i], pointerTimestamp + desiredSpan)) { + return i; + } + } + // An earlier packet still covering the whole chunk. + for (int i = 0; i < MAX_PACKETS; i++) { + if (data[i] != null && le(timestamp[i], pointerTimestamp) + && ge(timestamp[i] + span[i], pointerTimestamp + desiredSpan)) { + return i; + } + } + // An earlier packet covering part of it. + for (int i = 0; i < MAX_PACKETS; i++) { + if (data[i] != null && le(timestamp[i], pointerTimestamp) + && gt(timestamp[i] + span[i], pointerTimestamp)) { + return i; + } + } + // Anything starting inside the chunk: prefer the earliest, then the longest. + int best = -1; + for (int i = 0; i < MAX_PACKETS; i++) { + if (data[i] == null) continue; + if (!(lt(timestamp[i], pointerTimestamp + desiredSpan) && ge(timestamp[i], pointerTimestamp))) continue; + if (best < 0 || lt(timestamp[i], timestamp[best]) + || (timestamp[i] == timestamp[best] && gt(span[i], span[best]))) { + best = i; + } + } + return best; + } + + /** + * Applies the delay the timings call for, by scheduling an insertion to grow the buffer + * or skipping ahead to shrink it. The timings are shifted by the same amount so the + * next estimate is made relative to the new delay. + */ + private void updateDelay() { + int optimal = computeOptimalDelay(); + if (optimal == 0) return; + + shiftTimings(-optimal); + pointerTimestamp += optimal; + if (optimal < 0) interpolationRequested = -optimal; + // Held packets measure their slack against when they arrived, so move that with the + // timeline too. libspeex does not, which makes a delay jump of several frames count + // twice: every packet already waiting reports the old shortfall again on playout. + for (int i = 0; i < MAX_PACKETS; i++) { + if (data[i] != null && arrival[i] != 0) arrival[i] += optimal; + } + } + + /** + * Finds the delay minimising {@code delay + lateCost * latePackets} over the observed + * timings, quantised to whole {@link #delayStep}s. + * + * @return ticks to shift playback by: negative to buffer more, positive to catch up + */ + private int computeOptimalDelay() { + int totalSeen = 0; + for (TimingWindow w : windows) totalSeen += w.seen; + if (totalSeen == 0) return 0; + + float lateFactor = lateCost != 0 + ? lateCost * 100.0f / totalSeen + : (float) autoTradeoff * windowSize / totalSeen; + + int[] pos = new int[SUB_WINDOWS]; + int optimal = 0; + int bestCost = Integer.MAX_VALUE; + int late = 0; + boolean penaltyTaken = false; + int earliestSeen = 0; + int latestSeen = 0; + + // Walk the timings from latest to earliest, costing each as a candidate delay. + for (int i = 0; i < TOP_DELAY; i++) { + int next = -1; + int timing = Integer.MAX_VALUE; + for (int j = 0; j < SUB_WINDOWS; j++) { + if (pos[j] < windows[j].filled && windows[j].timing[pos[j]] < timing) { + next = j; + timing = windows[j].timing[pos[j]]; + } + } + if (next < 0) break; + + if (i == 0) latestSeen = timing; + earliestSeen = timing; + timing = roundDown(timing, delayStep); + pos[next]++; + + int cost = (int) (-timing + lateFactor * late); + if (cost < bestCost) { + bestCost = cost; + optimal = timing; + } + + late++; + // Hysteresis: charge extra the first time we would start making packets late. + if (timing >= 0 && !penaltyTaken) { + penaltyTaken = true; + late += 4; + } + } + + autoTradeoff = 1 + (earliestSeen - latestSeen) / TOP_DELAY; + + // Too little evidence to justify shrinking the buffer. + if (totalSeen < TOP_DELAY && optimal > 0) return 0; + return optimal; + } + + /** Records one arrival's slack, rotating the sub-windows when the newest fills up. */ + private void updateTimings(int timing) { + timing = Math.max(-32767, Math.min(32767, timing)); + + if (byAge[0].seen >= subWindowSize) { + TimingWindow oldest = byAge[SUB_WINDOWS - 1]; + System.arraycopy(byAge, 0, byAge, 1, SUB_WINDOWS - 1); + byAge[0] = oldest; + oldest.clear(); + } + byAge[0].add(timing); + } + + /** Re-bases every recorded timing after the delay moved. */ + private void shiftTimings(int amount) { + for (TimingWindow w : windows) { + for (int i = 0; i < w.filled; i++) w.timing[i] += amount; + } + } + + private static int roundDown(int value, int step) { + return value < 0 ? (value - step + 1) / step * step : value / step * step; + } + + // Wrap-safe comparisons, so tick counters may overflow. + private static boolean lt(int a, int b) { + return a - b < 0; + } + + private static boolean le(int a, int b) { + return a - b <= 0; + } + + private static boolean gt(int a, int b) { + return a - b > 0; + } + + private static boolean ge(int a, int b) { + return a - b >= 0; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/MixedPlayout.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/MixedPlayout.java new file mode 100644 index 0000000..c69910f --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/MixedPlayout.java @@ -0,0 +1,116 @@ +package eu.lixko.ts3j.client.audio; + +import java.util.Arrays; +import java.util.Collection; +import java.util.function.Supplier; +import java.util.function.ToDoubleFunction; + +/** + * Mixes every speaker onto one playback line, as mobile audio APIs want: a single + * low-latency stream. The line's blocking writes pace the mix, so it runs on the device's + * clock; between talk bursts the mixer writes nothing and waits. + */ +final class MixedPlayout implements Playout { + + private static final int FRAME = VoiceFormat.FRAME_SIZE; + + private final AudioIo io; + private final Supplier outputDevice; + private final ToDoubleFunction gain; + private final Collection streams; + + private final Object lock = new Object(); + /** Guarded by {@link #lock}. */ + private boolean running = true; + private Thread mixer; + + MixedPlayout(AudioIo io, Supplier outputDevice, ToDoubleFunction gain, + Collection streams) { + this.io = io; + this.outputDevice = outputDevice; + this.gain = gain; + this.streams = streams; + } + + @Override + public void started(VoiceStream stream) { + synchronized (lock) { + if (!running) return; + if (mixer == null) { + mixer = new Thread(this::mixLoop, "ts3j-voice-mixer"); + mixer.setDaemon(true); + mixer.start(); + } + lock.notifyAll(); + } + } + + @Override + public void removed(VoiceStream stream) { + // The stream has already left the collection the mixer iterates. + } + + @Override + public void shutdown() { + synchronized (lock) { + running = false; + if (mixer != null) mixer.interrupt(); + lock.notifyAll(); + } + } + + private void mixLoop() { + AudioPlayback line = null; + try { + int channels = 0; + float[] mix = null; + float[] scratch = null; + byte[] out = null; + String device = null; + while (awaitSpeech()) { + if (line != null && !device.equals(outputDevice.get())) { + line.close(); + line = null; + } + if (line == null) { + device = outputDevice.get(); + line = io.openPlayback(device, VoiceFormat.MAX_CHANNELS); + line.start(); + channels = line.channels(); + mix = new float[FRAME * channels]; + scratch = new float[VoiceStream.MAX_FRAME * channels]; + out = new byte[mix.length * 2]; + } + Arrays.fill(mix, 0f); + for (VoiceStream stream : streams) { + int frames = stream.pull(scratch, channels, gain.applyAsDouble(stream)); + // TeamSpeak clients send 20 ms packets; anything longer is cut to the frame. + int samples = Math.min(frames, FRAME) * channels; + for (int i = 0; i < samples; i++) mix[i] += scratch[i]; + } + Pcm16.encode(mix, mix.length, out); + line.write(out, 0, out.length); + } + } catch (Exception ignored) { + // No usable line: this mixer ends, and the next talk burst tries again. + } finally { + if (line != null) line.close(); + synchronized (lock) { + mixer = null; + } + } + } + + /** Waits until some stream is playing; false once shut down. */ + private boolean awaitSpeech() throws InterruptedException { + synchronized (lock) { + while (running) { + for (VoiceStream stream : streams) { + if (stream.isPlaying()) return true; + } + lock.wait(); + } + return false; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/OpusParameters.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/OpusParameters.java new file mode 100644 index 0000000..b4264f4 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/OpusParameters.java @@ -0,0 +1,37 @@ +package eu.lixko.ts3j.client.audio; + +import eu.lixko.ts3j.client.config.Settings; + +/** + * Immutable set of Opus encoder settings that a {@link VoiceInput} can apply, + * including while capturing. Frontend-agnostic: carries no native handles. + */ +public final class OpusParameters { + + public static OpusParameters from(Settings s) { + return new OpusParameters(s.bitrate, s.complexity, s.vbr, s.fec, s.packetLoss, s.music); + } + + /** Target bitrate in bits per second. */ + public final int bitrate; + /** Encoder complexity, 0 (fast) .. 10 (best). */ + public final int complexity; + /** Variable bitrate. */ + public final boolean vbr; + /** In-band forward error correction. */ + public final boolean fec; + /** Expected packet loss, 0..100 percent (drives FEC redundancy). */ + public final int expectedPacketLoss; + /** {@code true} to encode as music (OPUS_MUSIC, stereo-friendly); {@code false} for voice. */ + public final boolean music; + + public OpusParameters(int bitrate, int complexity, boolean vbr, boolean fec, + int expectedPacketLoss, boolean music) { + this.bitrate = bitrate; + this.complexity = Math.max(0, Math.min(10, complexity)); + this.vbr = vbr; + this.fec = fec; + this.expectedPacketLoss = Math.max(0, Math.min(100, expectedPacketLoss)); + this.music = music; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/Pcm16.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/Pcm16.java new file mode 100644 index 0000000..e982399 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/Pcm16.java @@ -0,0 +1,20 @@ +package eu.lixko.ts3j.client.audio; + +/** Conversion between float samples in [-1, 1] and 16-bit little-endian PCM. */ +public final class Pcm16 { + + private Pcm16() { + } + + /** Writes {@code count} samples to {@code out}, clipping anything out of range. */ + public static void encode(float[] samples, int count, byte[] out) { + for (int i = 0; i < count; i++) { + float f = samples[i]; + if (f > 1f) f = 1f; + else if (f < -1f) f = -1f; + int s = Math.round(f * 32767f); + out[2 * i] = (byte) (s & 0xFF); + out[2 * i + 1] = (byte) ((s >> 8) & 0xFF); + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/PerSpeakerPlayout.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/PerSpeakerPlayout.java new file mode 100644 index 0000000..da7eff3 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/PerSpeakerPlayout.java @@ -0,0 +1,181 @@ +package eu.lixko.ts3j.client.audio; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; +import java.util.function.ToDoubleFunction; + +/** + * Gives every speaker a playback line and worker thread of its own, so simultaneous + * speakers are mixed by the audio server and one slow decode never blocks another. On a + * PipeWire desktop every speaker then shows up as a separate stream in the mixer. + */ +final class PerSpeakerPlayout implements Playout { + + private static final long FRAME_NANOS = + TimeUnit.SECONDS.toNanos(VoiceFormat.FRAME_SIZE) / VoiceFormat.SAMPLE_RATE; + /** Silence after which a speaker's line and thread are given back; the next burst reopens them. */ + private static final long IDLE_RELEASE_NANOS = TimeUnit.SECONDS.toNanos(30); + + private final class Speaker { + final VoiceStream stream; + final AudioPlayback line; + final int lineChannels; + final ExecutorService worker; + final AtomicBoolean tickQueued = new AtomicBoolean(); + /** Touched only by {@link #worker}. */ + final float[] pcm; + final byte[] out; + /** Guarded by this speaker. */ + ScheduledFuture ticks; + /** Guarded by this speaker; a closed speaker is never ticked again. */ + boolean closed; + + Speaker(VoiceStream stream) throws Exception { + this.stream = stream; + this.line = io.openPlayback(outputDevice.get(), VoiceFormat.MAX_CHANNELS); + this.lineChannels = line.channels(); + this.line.start(); + this.pcm = new float[VoiceStream.MAX_FRAME * lineChannels]; + this.out = new byte[pcm.length * 2]; + this.worker = Executors.newSingleThreadExecutor(r -> { + Thread t = new Thread(r, "ts3j-play-" + stream.clientId); + t.setDaemon(true); + return t; + }); + } + + void close() { + synchronized (this) { + closed = true; + if (ticks != null) ticks.cancel(false); + } + worker.shutdownNow(); + line.close(); + } + } + + private final AudioIo io; + private final Supplier outputDevice; + private final ToDoubleFunction gain; + private final ScheduledExecutorService clock; + private final Map speakers = new ConcurrentHashMap<>(); + + PerSpeakerPlayout(AudioIo io, Supplier outputDevice, ToDoubleFunction gain, + ScheduledExecutorService clock) { + this.io = io; + this.outputDevice = outputDevice; + this.gain = gain; + this.clock = clock; + clock.scheduleWithFixedDelay(this::releaseIdle, 1, 1, TimeUnit.SECONDS); + } + + @Override + public void started(VoiceStream stream) { + while (true) { + Speaker speaker = speakers.get(stream); + if (speaker == null) { + try { + speaker = new Speaker(stream); + } catch (Exception e) { + stream.stop(); // couldn't open a line; drop the burst + return; + } + Speaker existing = speakers.putIfAbsent(stream, speaker); + if (existing != null) { + speaker.close(); + speaker = existing; + } + } + synchronized (speaker) { + if (speaker.closed) { + // Released a moment ago; this burst gets a fresh line. + speakers.remove(stream, speaker); + continue; + } + if (speaker.ticks == null) { + Speaker s = speaker; + speaker.ticks = clock.scheduleAtFixedRate( + () -> queueTick(s), FRAME_NANOS, FRAME_NANOS, TimeUnit.NANOSECONDS); + } + return; + } + } + } + + /** Gives back the line and thread of every speaker that has been silent for a while. */ + private void releaseIdle() { + long now = System.nanoTime(); + for (Speaker speaker : speakers.values()) { + synchronized (speaker) { + if (speaker.ticks != null || now - speaker.stream.lastPacketNanos() < IDLE_RELEASE_NANOS) continue; + speaker.closed = true; + } + speakers.remove(speaker.stream, speaker); + speaker.close(); + } + } + + private void queueTick(Speaker speaker) { + if (!speaker.tickQueued.compareAndSet(false, true)) return; + try { + speaker.worker.submit(() -> { + try { + tick(speaker); + } finally { + speaker.tickQueued.set(false); + } + }); + } catch (RuntimeException e) { + if (speaker.worker.isShutdown()) { + speaker.tickQueued.set(false); + } else { + throw e; + } + } + } + + private void tick(Speaker speaker) { + int frames = speaker.stream.pull(speaker.pcm, speaker.lineChannels, gain.applyAsDouble(speaker.stream)); + if (frames == VoiceStream.IDLE) { + synchronized (speaker) { + // A packet may have started the next burst since the pull; keep ticking then. + if (!speaker.stream.isPlaying() && speaker.ticks != null) { + speaker.ticks.cancel(false); + speaker.ticks = null; + } + } + return; + } + if (frames == 0) return; + int samples = frames * speaker.lineChannels; + Pcm16.encode(speaker.pcm, samples, speaker.out); + try { + speaker.line.write(speaker.out, 0, samples * 2); + } catch (RuntimeException e) { + // The line died (a device went away, say). Drop it rather than keep writing into it: + // the speaker's next packet starts a burst on a fresh one. + speakers.remove(speaker.stream, speaker); + speaker.close(); + speaker.stream.stop(); + } + } + + @Override + public void removed(VoiceStream stream) { + Speaker speaker = speakers.remove(stream); + if (speaker != null) speaker.close(); + } + + @Override + public void shutdown() { + for (Speaker speaker : speakers.values()) speaker.close(); + speakers.clear(); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/Playout.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/Playout.java new file mode 100644 index 0000000..38f155b --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/Playout.java @@ -0,0 +1,13 @@ +package eu.lixko.ts3j.client.audio; + +/** Drives the {@link VoiceStream}s of a {@link StreamingVoiceOutput} out to the speakers. */ +interface Playout { + + /** A stream began a talk burst and must now be pulled every 20 ms. */ + void started(VoiceStream stream); + + /** The stream's client left; it will not be pulled again. */ + void removed(VoiceStream stream); + + void shutdown(); +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/SpeechProbabilityDetector.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/SpeechProbabilityDetector.java new file mode 100644 index 0000000..49f4d68 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/SpeechProbabilityDetector.java @@ -0,0 +1,27 @@ +package eu.lixko.ts3j.client.audio; + +/** + * Estimates how likely it is that a frame of captured audio contains speech. + * + *

    Used by the "Automatic" and "Hybrid" voice-activation modes. Implementations are + * stateful and expect frames in capture order; {@link #reset()} clears that state. + * + *

    Pure DSP with no platform dependencies, so any frontend or backend can reuse it. + */ +public interface SpeechProbabilityDetector { + + /** + * Consumes one frame of mono PCM in [-1, 1] and returns the current speech + * probability in [0, 1]. + * + * @param frame samples in capture order + * @param length number of valid samples in {@code frame} + */ + double process(float[] frame, int length); + + /** Speech probability from the most recent {@link #process} call. */ + double probability(); + + /** Drops all history. Call on a capture discontinuity or a settings change. */ + void reset(); +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/StreamingVoiceOutput.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/StreamingVoiceOutput.java new file mode 100644 index 0000000..8eb7629 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/StreamingVoiceOutput.java @@ -0,0 +1,221 @@ +package eu.lixko.ts3j.client.audio; + +import com.github.manevolent.ts3j.enums.CodecType; +import com.github.manevolent.ts3j.protocol.packet.PacketBody0Voice; +import com.github.manevolent.ts3j.protocol.packet.PacketBody1VoiceWhisper; +import eu.lixko.ts3j.client.audio.opus.OpusCodec; + +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; + +/** + * The {@link VoiceOutput} every platform shares: decodes incoming voice per speaker, each + * through its own jitter buffer, and plays it on the platform's {@link AudioIo}. + */ +public final class StreamingVoiceOutput implements VoiceOutput { + + /** How speakers reach the device. */ + public enum Lines { + /** A line per speaker, mixed by the platform's audio server. */ + PER_SPEAKER, + /** One line all speakers are mixed onto here. */ + SHARED + } + + /** + * A speaker is only meant to stop when the empty voice packet marking the end of a + * talk burst arrives — but that packet is UDP too, and a lost one otherwise leaves + * the talking indicator stuck until the speaker's next burst. Opus frames are 20 ms + * apart while someone is actually talking, so a gap several times that long, with no + * packet of either kind, is unambiguous: force the indicator off rather than trust + * the one packet that could go missing. + */ + private static final long TALK_TIMEOUT_NANOS = TimeUnit.MILLISECONDS.toNanos(400); + + private final OpusCodec opus; + private final Map streams = new ConcurrentHashMap<>(); + private final Set mutedClients = ConcurrentHashMap.newKeySet(); + /** Per-client gain on top of the master volume; absent means 1.0. */ + private final Map clientVolumes = new ConcurrentHashMap<>(); + /** What came in from speakers who have left. */ + private volatile VoiceReceiveStats departed = VoiceReceiveStats.NONE; + + private volatile String outputDevice; + private volatile double masterVolume = 1.0; + /** Extra playback delay, in jitter buffer ticks. */ + private volatile int extraDelayTicks; + private volatile boolean deafened = false; + + /** Notified (clientId, talking) on an audio thread when a speaker starts/stops. */ + private volatile BiConsumer talkListener; + private volatile VoiceTap voiceTap; + + /** Catches talk bursts whose end packet never arrived, and paces per-speaker lines. */ + private final ScheduledExecutorService clock = Executors.newSingleThreadScheduledExecutor(r -> { + Thread t = new Thread(r, "ts3j-talk-watchdog"); + t.setDaemon(true); + return t; + }); + private final Playout playout; + + public StreamingVoiceOutput(AudioIo io, OpusCodec opus, String outputDevice, Lines lines) { + this.opus = opus; + this.outputDevice = outputDevice == null ? "" : outputDevice; + this.playout = switch (lines) { + case PER_SPEAKER -> new PerSpeakerPlayout(io, () -> this.outputDevice, this::gainFor, clock); + case SHARED -> new MixedPlayout(io, () -> this.outputDevice, this::gainFor, streams.values()); + }; + clock.scheduleWithFixedDelay(this::checkTalkTimeouts, 50, 50, TimeUnit.MILLISECONDS); + } + + private void checkTalkTimeouts() { + long now = System.nanoTime(); + for (VoiceStream s : streams.values()) { + if (s.isTalking() && now - s.lastPacketNanos() > TALK_TIMEOUT_NANOS) s.stop(); + } + } + + private double gainFor(VoiceStream stream) { + return masterVolume * clientVolumes.getOrDefault(stream.clientId, 1.0); + } + + private void fireTalk(int clientId, boolean talking) { + BiConsumer l = talkListener; + if (l != null) l.accept(clientId, talking); + } + + @Override + public void setTalkListener(BiConsumer l) { + this.talkListener = l; + } + + @Override + public void setVoiceTap(VoiceTap tap) { + this.voiceTap = tap; + for (VoiceStream s : streams.values()) s.setTap(tap); + } + + @Override + public void setMasterVolume(double v) { + this.masterVolume = Math.max(0, Math.min(2.0, v)); + } + + @Override + public void setDeafened(boolean d) { + this.deafened = d; + if (d) { + // Stop everyone talking immediately. + for (VoiceStream s : streams.values()) s.stop(); + } + } + + @Override + public boolean isDeafened() { + return deafened; + } + + @Override + public void setClientMuted(int clientId, boolean muted) { + if (muted) { + mutedClients.add(clientId); + VoiceStream s = streams.get(clientId); + if (s != null) s.stop(); + } else { + mutedClients.remove(clientId); + } + } + + @Override + public boolean isClientMuted(int clientId) { + return mutedClients.contains(clientId); + } + + @Override + public void setClientVolume(int clientId, double gain) { + if (gain == 1.0) clientVolumes.remove(clientId); + else clientVolumes.put(clientId, Math.max(0, gain)); + } + + @Override + public double getClientVolume(int clientId) { + return clientVolumes.getOrDefault(clientId, 1.0); + } + + @Override + public void setOutputDevice(String device) { + this.outputDevice = device == null ? "" : device; + } + + @Override + public void setReceiveBuffer(int ms) { + int frames = Math.max(0, ms) * (VoiceFormat.SAMPLE_RATE / 1000) / VoiceFormat.FRAME_SIZE; + extraDelayTicks = frames * JitterBuffer.TEAMSPEAK_TICKS_PER_FRAME; + for (VoiceStream s : streams.values()) s.setExtraDelay(extraDelayTicks); + } + + /** Entry point wired into {@code client.setVoiceHandler(...)}. */ + @Override + public void handleVoice(PacketBody0Voice voice) { + route(voice.getClientId(), voice.getPacketId(), voice.getCodecType(), voice.getCodecData()); + } + + /** Entry point wired into {@code client.setWhisperHandler(...)}. */ + @Override + public void handleWhisper(PacketBody1VoiceWhisper whisper) { + route(whisper.getClientId(), whisper.getPacketId(), whisper.getCodecType(), whisper.getCodecData()); + } + + private void route(int clientId, int packetId, CodecType codec, byte[] data) { + if (deafened) return; + if (mutedClients.contains(clientId)) return; + + VoiceStream stream = streams.computeIfAbsent(clientId, id -> { + VoiceStream created = new VoiceStream(id, opus, this::fireTalk); + created.setTap(voiceTap); + created.setExtraDelay(extraDelayTicks); + return created; + }); + if (stream.offer(packetId, codec, data)) playout.started(stream); + } + + /** Forgets a client that left; the server may hand its id to somebody else. */ + @Override + public void removeClient(int clientId) { + VoiceStream s = streams.remove(clientId); + if (s != null) { + synchronized (this) { + departed = departed.plus(s.stats()); + } + playout.removed(s); + s.close(); + } + mutedClients.remove(clientId); + clientVolumes.remove(clientId); + } + + @Override + public VoiceReceiveStats receiveStats(int clientId) { + VoiceStream s = streams.get(clientId); + return s == null ? null : s.stats(); + } + + @Override + public VoiceReceiveStats receiveStats() { + VoiceReceiveStats total = departed; + for (VoiceStream s : streams.values()) total = total.plus(s.stats()); + return total; + } + + @Override + public void shutdown() { + clock.shutdownNow(); + playout.shutdown(); + for (VoiceStream s : streams.values()) s.close(); + streams.clear(); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceFormat.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceFormat.java new file mode 100644 index 0000000..69cf4cc --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceFormat.java @@ -0,0 +1,16 @@ +package eu.lixko.ts3j.client.audio; + +/** + * The PCM format voice is captured, processed and played in. TeamSpeak's Opus codecs run at + * 48 kHz in 20 ms frames, mono for {@code OPUS_VOICE} and stereo for {@code OPUS_MUSIC}. + */ +public final class VoiceFormat { + + public static final int SAMPLE_RATE = 48_000; + /** Samples per channel in one 20 ms frame. */ + public static final int FRAME_SIZE = 960; + public static final int MAX_CHANNELS = 2; + + private VoiceFormat() { + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceInput.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceInput.java new file mode 100644 index 0000000..5d19606 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceInput.java @@ -0,0 +1,110 @@ +package eu.lixko.ts3j.client.audio; + +import com.github.manevolent.ts3j.audio.Microphone; +import eu.lixko.ts3j.client.config.Settings; + +import java.util.function.Consumer; + +/** + * Voice capture source feeding the TS3 socket. Extends ts3j's {@link Microphone} + * (the encoded-packet supplier) with capture lifecycle and voice-gating controls + * so the connection layer can drive it without knowing the platform backend. + */ +public interface VoiceInput extends Microphone { + + void start(); + + void stop(); + + void setMuted(boolean muted); + + /** + * Silences capture the same way {@link #setMuted} does, but locally only: it does + * not touch {@link #isMuted}, so the mute status published to the server (and the + * mute/unmute sound) is unaffected. TS3's "Local Mic Mute". + */ + void setLocalMuted(boolean muted); + + boolean isLocalMuted(); + + /** Moves capture to another device, reopening at once if capturing; empty is the default. */ + void setInputDevice(String deviceId); + + void setMode(Settings.InputMode mode); + + void setVadMode(Settings.VadMode mode); + + /** Volume-gate threshold on {@link InputLevel}'s scale. */ + void setThresholdDb(double db); + + /** Speech-probability threshold (0..1) for Automatic/Hybrid modes. */ + void setSpeechThreshold(double threshold); + + /** Keep voice activation active while in push-to-talk mode. */ + void setVadOverPtt(boolean enabled); + + void setInputGain(double gain); + + /** Enables removal of steady background noise (WebRTC noise suppression). */ + void setNoiseSuppression(boolean enabled); + + /** Noise suppression strength as TS3's {@code denoiser_level}: 0 (6 dB) .. 3 (21 dB). */ + void setDenoiserLevel(int level); + + /** Enables attenuation of keyboard clicks while the user is typing. */ + void setTypingAttenuation(boolean enabled); + + /** Reports a key press anywhere on the system; typing attenuation only acts while typing. */ + void keyPressed(); + + /** Enables automatic gain control (normalise microphone loudness). */ + void setAgc(boolean enabled); + + /** Lets AGC raise the background noise this many dB more to bring up a quiet voice. */ + void setAgcBoost(int db); + + /** Applies Opus encoder parameters, taking effect immediately if capturing. */ + void setOpusParameters(OpusParameters parameters); + + /** Sends every voice packet {@code copies} more times, {@code delayMillis} apart; a delay of 0 sends it once. */ + void setRedundancy(int delayMillis, int copies); + + void setPushToTalk(boolean pressed); + + /** Transmits while held, whatever the input mode or the gate says; a mute still wins. */ + void setForceTransmit(boolean pressed); + + /** Receives the live input level on {@link InputLevel}'s scale, once per captured frame. */ + void setLevelListener(Consumer listener); + + /** Receives local transmit-state transitions (talking / silent). */ + void setTalkListener(Consumer listener); + + /** + * Receives every frame that is actually transmitted, for local monitoring: the audio + * after pre-processing and gating, including the pre-roll replayed when the gate opens. + * Nothing is delivered while the gate is shut or the microphone is muted. + */ + void setMonitorListener(AudioFrameListener listener); + + /** Called when speech is detected while the microphone is muted. */ + void setMutedTalkListener(Runnable listener); + + /** Takes on the voice settings, as they stand now, while capturing. */ + default void apply(Settings settings) { + setInputDevice(settings.inputDevice); + setMode(settings.inputMode); + setVadMode(settings.vadMode); + setThresholdDb(settings.vadThresholdDb); + setSpeechThreshold(settings.speechThreshold); + setVadOverPtt(settings.vadOverPtt); + setInputGain(settings.inputVolume); + setNoiseSuppression(settings.denoise); + setDenoiserLevel(settings.denoiserLevel); + setTypingAttenuation(settings.typingAttenuation); + setAgc(settings.agc); + setAgcBoost(settings.agcBoostDb); + setOpusParameters(OpusParameters.from(settings)); + setRedundancy(settings.redundancyDelay, settings.redundancyCopies); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceOutput.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceOutput.java new file mode 100644 index 0000000..f1f053a --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceOutput.java @@ -0,0 +1,58 @@ +package eu.lixko.ts3j.client.audio; + +import com.github.manevolent.ts3j.protocol.packet.PacketBody0Voice; +import com.github.manevolent.ts3j.protocol.packet.PacketBody1VoiceWhisper; + +import java.util.function.BiConsumer; + +/** + * Playback sink for incoming voice packets. The connection layer registers + * {@link #handleVoice} as the socket's voice handler; the backend decodes and + * renders per speaker. + */ +public interface VoiceOutput { + + void handleVoice(PacketBody0Voice voice); + + /** Handles a whisper (targeted voice) packet; decoded and played like normal voice. */ + void handleWhisper(PacketBody1VoiceWhisper whisper); + + void setMasterVolume(double volume); + + void setDeafened(boolean deafened); + + boolean isDeafened(); + + void setClientMuted(int clientId, boolean muted); + + boolean isClientMuted(int clientId); + + /** Scales one client's voice on top of the master volume; 1.0 is unchanged, the default. */ + void setClientVolume(int clientId, double gain); + + double getClientVolume(int clientId); + + void setOutputDevice(String device); + + /** + * Delays every speaker by {@code ms} more than the network calls for, trading latency for + * fewer dropouts on a bad connection. + */ + void setReceiveBuffer(int ms); + + void removeClient(int clientId); + + void shutdown(); + + /** Receives remote speaker talk-state transitions as (clientId, talking). */ + void setTalkListener(BiConsumer listener); + + /** Receives every speaker's voice as it is played, e.g. for recording; null detaches it. */ + void setVoiceTap(VoiceTap tap); + + /** How one speaker's voice has been coming in, or {@code null} if none came yet. */ + VoiceReceiveStats receiveStats(int clientId); + + /** How everyone's voice has been coming in, those who left included. */ + VoiceReceiveStats receiveStats(); +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceReceiveStats.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceReceiveStats.java new file mode 100644 index 0000000..2c3c5ca --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceReceiveStats.java @@ -0,0 +1,31 @@ +package eu.lixko.ts3j.client.audio; + +/** + * How one speaker's voice, or everyone's together, has been coming in: what arrived, and + * what playback had to do without. + * + * @param received voice packets that arrived, copies included + * @param played frames played from a packet + * @param missed frames whose packet was not there when due + * @param recovered of those, frames rebuilt from the error correction copy in the next packet + * rather than concealed + * @param outOfOrder packets that arrived after a later one + * @param late packets that arrived after their frame was concealed, so were dropped; + * each one is also among {@code missed} + * @param duplicates copies of a packet already received, discarded + */ +public record VoiceReceiveStats(long received, long played, long missed, long recovered, long outOfOrder, long late, + long duplicates) { + + public static final VoiceReceiveStats NONE = new VoiceReceiveStats(0, 0, 0, 0, 0, 0, 0); + + public VoiceReceiveStats plus(VoiceReceiveStats o) { + return new VoiceReceiveStats(received + o.received, played + o.played, missed + o.missed, + recovered + o.recovered, outOfOrder + o.outOfOrder, late + o.late, duplicates + o.duplicates); + } + + /** Frames that were due, whether played or missed. */ + public long due() { + return played + missed; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceStream.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceStream.java new file mode 100644 index 0000000..2fcfb3f --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceStream.java @@ -0,0 +1,489 @@ +package eu.lixko.ts3j.client.audio; + +import com.github.manevolent.ts3j.enums.CodecType; +import eu.lixko.ts3j.client.audio.opus.OpusCodec; +import eu.lixko.ts3j.client.audio.opus.OpusDecoder; + +import java.util.function.BiConsumer; + +/** + * One speaker's incoming voice: packets go into an adaptive {@link JitterBuffer} as they + * arrive, and every {@link #pull} plays out the next 20 ms, concealing what went missing. + * + *

    The buffer is driven the way the official client drives it. A speaker has one timeline, + * {@code unwrap16(packetId) * 60} ticks, which is never re-anchored between talk bursts: the + * sender stops numbering when it stops talking and playback stops at the same point, so the + * next burst lands where the last one left off and the delay the buffer has learned carries + * over. Only a long silence drops the timeline. + * + *

    An empty packet is the talker letting go of the key. It never enters the buffer; its + * position is remembered, the burst ends once playback reaches it, and its slot is played as + * silence rather than concealed, since nothing was lost there. + * + *

    A frame that did go missing is rebuilt from the error correction copy in the packet after + * it, when that one is already held; only otherwise is it concealed. An + * {@linkplain #setExtraDelay extra delay} makes that, and late packets, more likely to be in + * time. + * + *

    The stream keeps no clock of its own: whoever pulls sets the pace, one call per + * 20 ms frame. {@link #offer} and {@link #stop} may be called from any thread; pulls + * must come from one thread at a time. + */ +final class VoiceStream { + + /** Returned by {@link #pull} when no talk burst is playing. */ + static final int IDLE = -1; + + /** Longest Opus frame (120 ms @ 48 kHz) a packet may decode to, per channel. */ + static final int MAX_FRAME = 5760; + + private static final int FRAME = VoiceFormat.FRAME_SIZE; + private static final float[] SILENT_FRAME = new float[FRAME]; + private static final int FRAME_TICKS = JitterBuffer.TEAMSPEAK_TICKS_PER_FRAME; + /** Pulls in a row with nothing held before a burst whose end marker got lost is given up. */ + private static final int EMPTY_PULLS_TO_END = 10; + /** How far back a talker's stop is remembered, as in the official client. */ + private static final int STOP_MARK_WINDOW_TICKS = 3000; + /** Silence after which the timeline and the delay estimate are dropped, as in the official client. */ + private static final long IDLE_RESET_NANOS = 5_000_000_000L; + private static final int EPOCH_UNSET = Integer.MIN_VALUE; + /** How many recent sequence numbers are remembered to recognise a copy; a power of two. */ + private static final int SEEN_WINDOW = 1024; + + /** What a pull plays, decided under the lock and produced outside it. */ + private enum Source { PACKET, RECOVER, CONCEAL, SILENCE, SURPLUS } + + final int clientId; + private final OpusCodec opus; + private final BiConsumer talkListener; + + private final Object lock = new Object(); + // Guarded by lock. + private final JitterBuffer jitter = JitterBuffer.forTeamSpeakVoice(FRAME_TICKS); + private int epoch = EPOCH_UNSET; + private int lastSeq; + private int[] stopMarks = new int[8]; + private int stopMarkCount; + /** Channels of the latest packet: TeamSpeak streams {@code OPUS_MUSIC} in stereo. */ + private int channels = 1; + private boolean playing; + private int emptyPulls; + /** Frames of decoded audio left over from the last packet, still to be played. */ + private int surplusFrames; + /** Frames of concealment still owed to a delay increase. */ + private int concealOwed; + /** Ticks of delay held on top of what the jitter buffer measures it needs. */ + private int extraTicks; + /** Frames of silence still to play before a fresh timeline starts, building up {@link #extraTicks}. */ + private int leadInFrames; + /** Set when the timeline was dropped; the decoder follows on the next pull. */ + private boolean resetDecoder; + /** Recently received sequence numbers, each at {@code seq % SEEN_WINDOW}. */ + private final int[] seen = new int[SEEN_WINDOW]; + private int highestSeq; + private long received; + private long played; + private long missed; + private long recovered; + private long outOfOrder; + private long late; + private long duplicates; + + /** Guards the decoder: a close from another thread may reach it mid-pull. */ + private final Object decoderLock = new Object(); + private final float[] pcm = new float[MAX_FRAME * VoiceFormat.MAX_CHANNELS]; + /** Audio a packet decoded to beyond its first frame; only the pulling thread touches it. */ + private final float[] surplus = new float[MAX_FRAME * VoiceFormat.MAX_CHANNELS]; + private int surplusOffset; + private int surplusChannels; + private OpusDecoder decoder; + private int decoderChannels; + private boolean closed; + /** The played frame in mono and at full volume, for the {@link #tap}. */ + private final float[] tapped = new float[FRAME]; + private volatile VoiceTap tap; + + private volatile boolean talking; + private volatile long lastPacketNanos; + + VoiceStream(int clientId, OpusCodec opus, BiConsumer talkListener) { + this.clientId = clientId; + this.opus = opus; + this.talkListener = talkListener; + forgetSeen(); + } + + void setTap(VoiceTap tap) { + this.tap = tap; + } + + /** + * Holds {@code ticks} more delay than the network calls for, for a better chance that + * late packets and those carrying a lost one's error correction copy arrive in time. + */ + void setExtraDelay(int ticks) { + synchronized (lock) { + extraTicks = Math.max(0, ticks); + jitter.setMargin(FRAME_TICKS + extraTicks); + } + } + + private static int channelsFor(CodecType codec) { + return codec == CodecType.OPUS_MUSIC ? 2 : 1; + } + + /** + * Places an incoming packet on the speaker's timeline; an empty one marks the end of the + * talk burst. + * + * @return true if the packet started a new burst, so playout has to begin + */ + boolean offer(int packetId, CodecType codec, byte[] data) { + long now = System.nanoTime(); + boolean longIdle = lastPacketNanos != 0 && now - lastPacketNanos >= IDLE_RESET_NANOS; + lastPacketNanos = now; + boolean end = data == null || data.length == 0; + boolean started = false; + + synchronized (lock) { + if (longIdle && !playing) { + jitter.reset(); + epoch = EPOCH_UNSET; + stopMarkCount = 0; + resetDecoder = true; + forgetSeen(); + } + boolean fresh = epoch == EPOCH_UNSET; + int seq = unwrap(packetId & 0xFFFF); + int ticks = seq * FRAME_TICKS; + if (end) { + markStop(ticks); + return false; + } + boolean behind = !fresh && ticks - jitter.position() < 0; + count(seq, fresh, behind); + // Playback already went past it, but the buffer still learns how late it ran, as in + // the official client; that is what grows the delay to wait for redundant copies. + if (behind) { + jitter.put(data, ticks, FRAME_TICKS); + return false; + } + + channels = channelsFor(codec); + jitter.put(data, ticks, FRAME_TICKS); + if (!playing) { + playing = true; + started = true; + emptyPulls = 0; + // The buffer would otherwise reach the extra delay by concealing frames mid-speech. + if (fresh) leadInFrames = extraTicks / FRAME_TICKS; + } + } + markTalking(true); + return started; + } + + /** + * Plays out the next frame into {@code out}, interleaved over {@code outChannels} and + * scaled by {@code gain} but not clipped, so it can still be mixed. + * + * @param out room for {@link VoiceFormat#FRAME_SIZE} samples per channel + * @return the samples written per channel, at most one frame; 0 if a packet could not be + * decoded, or {@link #IDLE} once the burst is over + */ + int pull(float[] out, int outChannels, double gain) { + Source source; + byte[] packet = null; + int surplusTake = 0; + int packetChannels; + boolean reset; + synchronized (lock) { + if (!playing) return IDLE; + reset = resetDecoder; + resetDecoder = false; + packetChannels = channels; + + if (leadInFrames > 0) { + leadInFrames--; + source = Source.SILENCE; + } else if (surplusFrames > 0 || concealOwed > 0) { + // Still playing out what the last get() handed over. + if (surplusFrames > 0) { + source = Source.SURPLUS; + surplusTake = Math.min(FRAME, surplusFrames); + surplusFrames -= surplusTake; + } else { + source = Source.CONCEAL; + concealOwed--; + } + jitter.remainingSpan(remainingTicks()); + } else { + boolean empty = jitter.isEmpty(); + emptyPulls = empty ? emptyPulls + 1 : 0; + if (empty && (stoppedAt(jitter.position()) || emptyPulls >= EMPTY_PULLS_TO_END)) { + stopLocked(); + source = null; + } else { + JitterBuffer.Status status = jitter.get(FRAME_TICKS); + switch (status) { + case OK -> { + source = Source.PACKET; + packet = jitter.payload(); + played++; + } + case MISSING -> { + if (isStopMark(jitter.timestamp())) { + source = Source.SILENCE; + } else { + missed++; + packet = jitter.nextPayload(); + if (packet != null) { + source = Source.RECOVER; + recovered++; + } else { + source = Source.CONCEAL; + } + } + } + default -> { + // The buffer grows its delay by inserting this many frames. + source = Source.CONCEAL; + concealOwed = Math.max(1, jitter.span() / FRAME_TICKS) - 1; + } + } + jitter.tick(); + } + } + } + if (source == null) { + markTalking(false); + return IDLE; + } + + int frames; + synchronized (decoderLock) { + if (closed) return 0; + try { + if (reset && decoder != null) decoder.reset(); + frames = produce(source, packet, surplusTake, packetChannels, out, outChannels, gain); + } catch (RuntimeException e) { + return 0; + } + } + return frames; + } + + private int produce(Source source, byte[] packet, int surplusTake, int packetChannels, float[] out, + int outChannels, double gain) { + switch (source) { + case SURPLUS -> { + play(surplus, surplusOffset, surplusTake, surplusChannels, out, outChannels, gain); + surplusOffset += surplusTake; + return surplusTake; + } + case SILENCE -> { + play(SILENT_FRAME, 0, FRAME, 1, out, outChannels, gain); + return FRAME; + } + case CONCEAL -> { + int frames = decoderFor(decoderChannels == 0 ? packetChannels : decoderChannels).conceal(pcm, FRAME); + play(pcm, 0, frames, decoderChannels, out, outChannels, gain); + return frames; + } + case RECOVER -> { + int frames = decoderFor(decoderChannels == 0 ? packetChannels : decoderChannels).recover(packet, pcm, FRAME); + play(pcm, 0, frames, decoderChannels, out, outChannels, gain); + return frames; + } + default -> { + int frames = decoderFor(packetChannels).decode(packet, pcm); + int played = Math.min(frames, FRAME); + play(pcm, 0, played, packetChannels, out, outChannels, gain); + if (frames > played) keepSurplus(played, frames - played, packetChannels); + return played; + } + } + } + + /** Hands a frame to the output and, if attached, the tap. */ + private void play(float[] src, int fromFrame, int frames, int channels, float[] out, int outChannels, + double gain) { + emit(src, fromFrame, frames, channels, out, outChannels, gain); + VoiceTap t = tap; + if (t == null || frames <= 0) return; + int n = Math.min(frames, FRAME); + emit(src, fromFrame, n, channels, tapped, 1, 1.0); + t.onVoice(clientId, tapped, n); + } + + /** Holds back what a packet decoded to beyond one frame, for the following pulls. */ + private void keepSurplus(int from, int frames, int channels) { + System.arraycopy(pcm, from * channels, surplus, 0, frames * channels); + surplusOffset = 0; + surplusChannels = channels; + synchronized (lock) { + if (playing) surplusFrames = frames; + } + } + + /** Ticks of audio already handed out but not yet played; guarded by the lock. */ + private int remainingTicks() { + return (surplusFrames * FRAME_TICKS + FRAME - 1) / FRAME + concealOwed * FRAME_TICKS; + } + + /** + * Matches decoded audio to the output: duplicates mono across stereo and folds a stereo + * (music) stream down onto mono. + */ + private static void emit(float[] src, int fromFrame, int frames, int channels, float[] out, int outChannels, + double gain) { + int base = fromFrame * channels; + for (int i = 0, k = 0; i < frames; i++) { + for (int c = 0; c < outChannels; c++, k++) { + double v; + if (channels == outChannels) { + v = src[base + i * channels + c]; + } else if (channels == 1) { + v = src[base + i]; + } else { + double sum = 0; + for (int s = 0; s < channels; s++) sum += src[base + i * channels + s]; + v = sum / channels; + } + out[k] = (float) (v * gain); + } + } + } + + /** + * Returns a decoder matching the stream's channel count, rebuilding it when a speaker + * switches between the mono {@code OPUS_VOICE} and stereo {@code OPUS_MUSIC} codecs. + */ + private OpusDecoder decoderFor(int channels) { + if (decoder == null || decoderChannels != channels) { + if (decoder != null) decoder.close(); + decoder = opus.createDecoder(VoiceFormat.SAMPLE_RATE, MAX_FRAME, channels); + decoderChannels = channels; + } + return decoder; + } + + /** + * Widens the 16-bit packet id into a continuous sequence. A packet that arrives after the + * counter wrapped, but was sent before it, counts back into the previous epoch. + */ + private int unwrap(int seq) { + if (epoch == EPOCH_UNSET) { + epoch = 0; + lastSeq = seq; + } else { + int delta = (short) (seq - lastSeq); + if (delta > 0) { + if (seq < lastSeq) epoch++; + lastSeq = seq; + } else if (seq > lastSeq) { + epoch--; + } + } + return (epoch << 16) | seq; + } + + /** Files an arrived packet under the counters. Call under the lock. */ + private void count(int seq, boolean fresh, boolean behind) { + received++; + int slot = seq & (SEEN_WINDOW - 1); + if (!fresh && seen[slot] == seq) { + duplicates++; + return; + } + seen[slot] = seq; + if (behind) late++; + if (fresh || seq - highestSeq > 0) highestSeq = seq; + else outOfOrder++; + } + + private void forgetSeen() { + java.util.Arrays.fill(seen, Integer.MIN_VALUE); + } + + /** How this speaker's voice has been coming in since the stream was created. */ + VoiceReceiveStats stats() { + synchronized (lock) { + return new VoiceReceiveStats(received, played, missed, recovered, outOfOrder, late, duplicates); + } + } + + private void markStop(int ticks) { + int position = jitter.position(); + int kept = 0; + for (int i = 0; i < stopMarkCount; i++) { + if (position - stopMarks[i] < STOP_MARK_WINDOW_TICKS) stopMarks[kept++] = stopMarks[i]; + } + stopMarkCount = kept; + if (stopMarkCount == stopMarks.length) stopMarks = java.util.Arrays.copyOf(stopMarks, stopMarkCount * 2); + stopMarks[stopMarkCount++] = ticks; + } + + private boolean isStopMark(int ticks) { + for (int i = 0; i < stopMarkCount; i++) { + if (stopMarks[i] == ticks) return true; + } + return false; + } + + /** Whether the talker let go at or shortly before {@code position}, so the burst is spoken out. */ + private boolean stoppedAt(int position) { + for (int i = 0; i < stopMarkCount; i++) { + int behind = position - stopMarks[i]; + if (behind >= 0 && behind < STOP_MARK_WINDOW_TICKS) return true; + } + return false; + } + + /** Ends the current talk burst, if any; the next packet starts a new one. */ + void stop() { + synchronized (lock) { + stopLocked(); + } + markTalking(false); + } + + private void stopLocked() { + playing = false; + surplusFrames = 0; + concealOwed = 0; + leadInFrames = 0; + emptyPulls = 0; + } + + boolean isPlaying() { + synchronized (lock) { + return playing; + } + } + + boolean isTalking() { + return talking; + } + + long lastPacketNanos() { + return lastPacketNanos; + } + + void close() { + synchronized (lock) { + stopLocked(); + } + synchronized (decoderLock) { + closed = true; + if (decoder != null) decoder.close(); + decoder = null; + } + } + + private void markTalking(boolean talking) { + if (this.talking == talking) return; + this.talking = talking; + talkListener.accept(clientId, talking); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceTap.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceTap.java new file mode 100644 index 0000000..cb451d8 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceTap.java @@ -0,0 +1,15 @@ +package eu.lixko.ts3j.client.audio; + +/** Receives each speaker's voice as it is played, before any volume is applied. */ +@FunctionalInterface +public interface VoiceTap { + + /** + * Called from an audio thread with one played frame; do not block. The array is reused + * between calls. + * + * @param mono samples in [-1, 1] + * @param frames how many samples, at most one 20 ms frame + */ + void onVoice(int clientId, float[] mono, int frames); +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/ogg/OggPageWriter.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/ogg/OggPageWriter.java new file mode 100644 index 0000000..7910922 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/ogg/OggPageWriter.java @@ -0,0 +1,113 @@ +package eu.lixko.ts3j.client.audio.ogg; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; + +/** + * Frames the packets of one logical bitstream into Ogg pages (RFC 3533). Packets too long + * for one page run on into the next; a page is closed once it holds about + * {@link #TARGET_PAGE_BYTES}, or on {@link #flush}. + */ +public final class OggPageWriter { + + private static final int TARGET_PAGE_BYTES = 4096; + private static final int MAX_SEGMENTS = 255; + + private static final int FLAG_CONTINUED = 0x01; + private static final int FLAG_FIRST = 0x02; + private static final int FLAG_LAST = 0x04; + + private final OutputStream out; + private final int serial; + private final byte[] lacing = new byte[MAX_SEGMENTS]; + private final ByteArrayOutputStream data = new ByteArrayOutputStream(); + private int segments; + private int sequence; + /** Whether the open page starts with the rest of a packet from the page before. */ + private boolean continued; + /** Granule position of the last packet completed on the open page, -1 if none. */ + private long granule = -1; + private long lastGranule; + + public OggPageWriter(OutputStream out, int serial) { + this.out = out; + this.serial = serial; + } + + /** @param granule the stream position at the end of this packet */ + public void write(byte[] packet, long granule) throws IOException { + int offset = 0; + while (true) { + if (segments == MAX_SEGMENTS) closePage(0, true); + int take = Math.min(255, packet.length - offset); + lacing[segments++] = (byte) take; + data.write(packet, offset, take); + offset += take; + // A packet ends with a segment shorter than 255 bytes, if need be an empty one. + if (take < 255) break; + } + this.granule = granule; + this.lastGranule = granule; + if (data.size() >= TARGET_PAGE_BYTES) flush(); + } + + /** Closes the open page, so the next packet starts a new one (as the Opus headers need). */ + public void flush() throws IOException { + if (segments > 0) closePage(0, false); + } + + /** Writes out the stream's last page. */ + public void finish() throws IOException { + closePage(FLAG_LAST, false); + out.flush(); + } + + private void closePage(int flags, boolean packetContinues) throws IOException { + if (continued) flags |= FLAG_CONTINUED; + if (sequence == 0) flags |= FLAG_FIRST; + long pageGranule = granule >= 0 ? granule : (flags & FLAG_LAST) != 0 ? lastGranule : -1; + + ByteBuffer header = ByteBuffer.allocate(27 + segments).order(ByteOrder.LITTLE_ENDIAN); + header.put("OggS".getBytes(StandardCharsets.US_ASCII)); + header.put((byte) 0); + header.put((byte) flags); + header.putLong(pageGranule); + header.putInt(serial); + header.putInt(sequence++); + header.putInt(0); // checksum, filled in below + header.put((byte) segments); + header.put(lacing, 0, segments); + + byte[] page = new byte[header.capacity() + data.size()]; + System.arraycopy(header.array(), 0, page, 0, header.capacity()); + System.arraycopy(data.toByteArray(), 0, page, header.capacity(), data.size()); + ByteBuffer.wrap(page).order(ByteOrder.LITTLE_ENDIAN).putInt(22, crc(page)); + out.write(page); + + segments = 0; + data.reset(); + granule = -1; + continued = packetContinues; + } + + /** Ogg's CRC-32: polynomial 0x04c11db7, not reflected, starting from 0. */ + private static int crc(byte[] page) { + int crc = 0; + for (byte b : page) crc = (crc << 8) ^ CRC_TABLE[((crc >>> 24) ^ b) & 0xff]; + return crc; + } + + private static final int[] CRC_TABLE = new int[256]; + + static { + for (int i = 0; i < 256; i++) { + int r = i << 24; + for (int j = 0; j < 8; j++) r = (r & 0x80000000) != 0 ? (r << 1) ^ 0x04c11db7 : r << 1; + CRC_TABLE[i] = r; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/ogg/OpusHeaders.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/ogg/OpusHeaders.java new file mode 100644 index 0000000..483aab8 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/ogg/OpusHeaders.java @@ -0,0 +1,78 @@ +package eu.lixko.ts3j.client.audio.ogg; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.util.List; + +/** The two header packets that open an Ogg Opus stream (RFC 7845, section 5). */ +public final class OpusHeaders { + + /** Channel mapping family 255 caps a stream at this many channels. */ + public static final int MAX_DISCRETE_CHANNELS = 255; + /** + * libopus' encoder delay at 48 kHz for 20 ms frames, which the file tells the decoder + * to drop (the SPI does not expose {@code OPUS_GET_LOOKAHEAD}). + */ + public static final int LIBOPUS_PRE_SKIP = 312; + + private OpusHeaders() { + } + + /** A single mono stream (mapping family 0). */ + public static byte[] mono(int preSkip, int inputRate) { + return head(1, preSkip, inputRate, 0).array(); + } + + /** + * {@code channels} unrelated channels, each its own uncoupled mono stream in channel + * order (mapping family 255): every packet is a multistream packet, see + * {@link SelfDelimitedOpus#join}. + */ + public static byte[] discrete(int channels, int preSkip, int inputRate) { + if (channels < 1 || channels > MAX_DISCRETE_CHANNELS) { + throw new IllegalArgumentException("channels " + channels); + } + ByteBuffer b = head(channels, preSkip, inputRate, 255); + b.put((byte) channels); // streams + b.put((byte) 0); // coupled streams + for (int c = 0; c < channels; c++) b.put((byte) c); + return b.array(); + } + + private static ByteBuffer head(int channels, int preSkip, int inputRate, int family) { + ByteBuffer b = ByteBuffer.allocate(19 + (family == 0 ? 0 : 2 + channels)).order(ByteOrder.LITTLE_ENDIAN); + b.put("OpusHead".getBytes(StandardCharsets.US_ASCII)); + b.put((byte) 1); // version + b.put((byte) channels); + b.putShort((short) preSkip); + b.putInt(inputRate); + b.putShort((short) 0); // output gain + b.put((byte) family); + return b; + } + + /** @param comments {@code NAME=value} user comments */ + public static byte[] tags(String vendor, List comments) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + out.writeBytes("OpusTags".getBytes(StandardCharsets.US_ASCII)); + writeString(out, vendor); + writeInt(out, comments.size()); + for (String comment : comments) writeString(out, comment); + return out.toByteArray(); + } + + private static void writeString(ByteArrayOutputStream out, String s) { + byte[] bytes = s.getBytes(StandardCharsets.UTF_8); + writeInt(out, bytes.length); + out.writeBytes(bytes); + } + + private static void writeInt(ByteArrayOutputStream out, int v) { + out.write(v); + out.write(v >>> 8); + out.write(v >>> 16); + out.write(v >>> 24); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/ogg/SelfDelimitedOpus.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/ogg/SelfDelimitedOpus.java new file mode 100644 index 0000000..f944aa7 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/ogg/SelfDelimitedOpus.java @@ -0,0 +1,104 @@ +package eu.lixko.ts3j.client.audio.ogg; + +import java.io.ByteArrayOutputStream; +import java.util.List; + +/** + * Opus' self-delimiting packet framing (RFC 6716, appendix B), which multistream packets + * use to put several streams' packets back to back. + */ +public final class SelfDelimitedOpus { + + private SelfDelimitedOpus() { + } + + /** + * Joins one packet per stream into a multistream packet: every packet but the last is + * self-delimited, the last is kept as it is. + */ + public static byte[] join(List packets) { + if (packets.size() == 1) return packets.get(0); + int size = 0; + for (byte[] p : packets) size += p.length + 2; + ByteArrayOutputStream out = new ByteArrayOutputStream(size); + for (int i = 0; i < packets.size() - 1; i++) out.writeBytes(selfDelimited(packets.get(i))); + out.writeBytes(packets.get(packets.size() - 1)); + return out.toByteArray(); + } + + /** Re-frames a packet so its length can be told from the packet itself. */ + public static byte[] selfDelimited(byte[] packet) { + if (packet.length == 0) throw new IllegalArgumentException("empty Opus packet"); + int code = packet[0] & 0x03; + // The extra length goes right after the packet's own header: the TOC byte, plus for + // code 1 and 2 nothing more, for code 2 the first frame's length, and for code 3 the + // frame count, padding length and (VBR) all but the last frame's lengths. + int header; + int lastFrame; + switch (code) { + case 0 -> { + header = 1; + lastFrame = packet.length - 1; + } + case 1 -> { + header = 1; + lastFrame = (packet.length - 1) / 2; + } + case 2 -> { + int[] first = readLength(packet, 1); + header = 1 + first[1]; + lastFrame = packet.length - header - first[0]; + } + default -> { + if (packet.length < 2) throw new IllegalArgumentException("truncated Opus packet"); + int count = packet[1] & 0x3f; + boolean vbr = (packet[1] & 0x80) != 0; + boolean padded = (packet[1] & 0x40) != 0; + int pos = 2; + int padding = 0; + if (padded) { + int b; + do { + b = packet[pos++] & 0xff; + padding += b == 255 ? 254 : b; + } while (b == 255); + } + int payload; + if (vbr) { + int framesBefore = 0; + for (int i = 0; i < count - 1; i++) { + int[] length = readLength(packet, pos); + framesBefore += length[0]; + pos += length[1]; + } + payload = packet.length - pos - padding; + lastFrame = payload - framesBefore; + } else { + payload = packet.length - pos - padding; + lastFrame = payload / count; + } + header = pos; + } + } + if (lastFrame < 0) throw new IllegalArgumentException("malformed Opus packet"); + byte[] length = encodeLength(lastFrame); + byte[] out = new byte[packet.length + length.length]; + System.arraycopy(packet, 0, out, 0, header); + System.arraycopy(length, 0, out, header, length.length); + System.arraycopy(packet, header, out, header + length.length, packet.length - header); + return out; + } + + /** @return the frame length at {@code pos} and how many bytes it took */ + private static int[] readLength(byte[] packet, int pos) { + int b = packet[pos] & 0xff; + if (b < 252) return new int[]{b, 1}; + return new int[]{b + 4 * (packet[pos + 1] & 0xff), 2}; + } + + private static byte[] encodeLength(int length) { + if (length < 252) return new byte[]{(byte) length}; + int first = 252 + (length & 3); + return new byte[]{(byte) first, (byte) ((length - first) / 4)}; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/opus/CtlOpusEncoder.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/opus/CtlOpusEncoder.java new file mode 100644 index 0000000..6a88992 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/opus/CtlOpusEncoder.java @@ -0,0 +1,38 @@ +package eu.lixko.ts3j.client.audio.opus; + +/** An {@link OpusEncoder} configured through libopus' own controls; a binding supplies {@link #ctl}. */ +public abstract class CtlOpusEncoder implements OpusEncoder { + + /** Calls {@code opus_encoder_ctl(encoder, request, value)}. */ + protected abstract void ctl(int request, int value); + + @Override + public void setBitrate(int bitsPerSecond) { + ctl(LibOpus.SET_BITRATE_REQUEST, bitsPerSecond); + } + + @Override + public void setComplexity(int complexity) { + ctl(LibOpus.SET_COMPLEXITY_REQUEST, Math.max(0, Math.min(10, complexity))); + } + + @Override + public void setVbr(boolean vbr) { + ctl(LibOpus.SET_VBR_REQUEST, vbr ? 1 : 0); + } + + @Override + public void setInbandFec(boolean fec) { + ctl(LibOpus.SET_INBAND_FEC_REQUEST, fec ? 1 : 0); + } + + @Override + public void setExpectedPacketLoss(int percent) { + ctl(LibOpus.SET_PACKET_LOSS_PERC_REQUEST, Math.max(0, Math.min(100, percent))); + } + + @Override + public void setSignal(Signal signal) { + ctl(LibOpus.SET_SIGNAL_REQUEST, signal == Signal.MUSIC ? LibOpus.SIGNAL_MUSIC : LibOpus.SIGNAL_VOICE); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/opus/LibOpus.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/opus/LibOpus.java new file mode 100644 index 0000000..46610d0 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/opus/LibOpus.java @@ -0,0 +1,26 @@ +package eu.lixko.ts3j.client.audio.opus; + +/** libopus' numeric constants (opus_defines.h), shared by every binding of it. */ +public final class LibOpus { + + public static final int APPLICATION_VOIP = 2048; + public static final int APPLICATION_AUDIO = 2049; + + public static final int SET_BITRATE_REQUEST = 4002; + public static final int SET_VBR_REQUEST = 4006; + public static final int SET_COMPLEXITY_REQUEST = 4010; + public static final int SET_INBAND_FEC_REQUEST = 4012; + public static final int SET_PACKET_LOSS_PERC_REQUEST = 4014; + public static final int SET_SIGNAL_REQUEST = 4024; + public static final int RESET_STATE = 4028; + + public static final int SIGNAL_VOICE = 3001; + public static final int SIGNAL_MUSIC = 3002; + + private LibOpus() { + } + + public static int application(OpusCodec.Application application) { + return application == OpusCodec.Application.AUDIO ? APPLICATION_AUDIO : APPLICATION_VOIP; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/opus/OpusCodec.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/opus/OpusCodec.java new file mode 100644 index 0000000..2afa57e --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/opus/OpusCodec.java @@ -0,0 +1,16 @@ +package eu.lixko.ts3j.client.audio.opus; + +/** Creates Opus encoders and decoders; each platform binds its own libopus. */ +public interface OpusCodec { + + /** Opus' coding mode, fixed when an encoder is created. */ + enum Application { VOIP, AUDIO } + + OpusEncoder createEncoder(int sampleRate, int frameSize, int channels, Application application); + + /** @param maxFrameSize the longest frame, per channel, a packet may decode to */ + OpusDecoder createDecoder(int sampleRate, int maxFrameSize, int channels); + + /** libopus' version string, for display. */ + String version(); +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/opus/OpusDecoder.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/opus/OpusDecoder.java new file mode 100644 index 0000000..7805193 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/opus/OpusDecoder.java @@ -0,0 +1,28 @@ +package eu.lixko.ts3j.client.audio.opus; + +/** One Opus decoder, used from one thread at a time. */ +public interface OpusDecoder extends AutoCloseable { + + /** Decodes {@code packet} into interleaved samples; returns the samples decoded per channel. */ + int decode(byte[] packet, float[] out); + + /** + * Makes up {@code frameSize} samples per channel for a packet that never arrived. Opus + * conceals exactly as much as it is asked for, so this should be the lost packet's length. + */ + int conceal(float[] out, int frameSize); + + /** + * Rebuilds {@code frameSize} samples per channel for a lost packet from the forward error + * correction copy carried in {@code next}, the packet that followed it. Falls back to + * concealment by itself when {@code next} carries none. {@code next} is then decoded as + * usual. + */ + int recover(byte[] next, float[] out, int frameSize); + + /** Forgets the stream's state, as at the start of a new talk burst. */ + void reset(); + + @Override + void close(); +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/opus/OpusEncoder.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/opus/OpusEncoder.java new file mode 100644 index 0000000..7071a71 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/opus/OpusEncoder.java @@ -0,0 +1,25 @@ +package eu.lixko.ts3j.client.audio.opus; + +/** One Opus encoder. Its methods may be called from different threads, but not concurrently. */ +public interface OpusEncoder extends AutoCloseable { + + enum Signal { VOICE, MUSIC } + + void setBitrate(int bitsPerSecond); + + void setComplexity(int complexity); + + void setVbr(boolean vbr); + + void setInbandFec(boolean fec); + + void setExpectedPacketLoss(int percent); + + void setSignal(Signal signal); + + /** Encodes exactly one frame of interleaved samples. */ + byte[] encode(float[] pcm); + + @Override + void close(); +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/AudioProcessor.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/AudioProcessor.java new file mode 100644 index 0000000..4474bdf --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/AudioProcessor.java @@ -0,0 +1,161 @@ +package eu.lixko.ts3j.client.audio.processing; + +import eu.lixko.ts3j.client.audio.processing.agc2.AdaptiveDigitalConfig; +import eu.lixko.ts3j.client.audio.processing.agc2.GainController2; +import eu.lixko.ts3j.client.audio.processing.ns.NoiseSuppressor; +import eu.lixko.ts3j.client.audio.processing.ns.SuppressionLevel; +import eu.lixko.ts3j.client.audio.processing.transients.TransientSuppressor; + +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * The microphone pre-processing chain, set up the way the TeamSpeak 3 client configures + * WebRTC's audio processing module. TS3's capture preprocessor applies, per 10 ms at + * 48 kHz: + *

      + *
    1. noise suppression ("Remove background noise") at {@code denoiser_level} 0–3, run + * on the three-band split. TS3 disables APM's high-pass filter, but APM forces it on + * whenever noise suppression runs, so a 100 Hz high-pass comes with it;
    2. + *
    3. transient suppression ("Typing attenuation"), told about key presses;
    4. + *
    5. automatic gain control. TS3 runs WebRTC's legacy AGC1 (adaptive digital, target + * -9 dBFS, 20 dB compression); this runs its successor, AGC2 adaptive digital. AGC2 won't + * amplify the noise floor above -50 dBFS, which also holds back a distant voice + * barely above the noise; {@link #setGainBoost} trades more noise for more of it.
    6. + *
    + * + *

    One deliberate difference: APM only splits into bands for band-wise stages, so with noise + * suppression and AGC1 both off its transient detector reads stale band data and never + * fires. TS3 hides this behind AGC1, which forces a split; with AGC2 it would show, so the + * split is done whenever typing attenuation is on. + * + *

    Pure DSP with no platform dependencies. Drive {@link #process} from the capture thread; + * the setters and {@link #keyPressed()} may be called from any thread and take effect at the + * next 10 ms frame. With every stage off, audio passes through untouched. + */ +public final class AudioProcessor { + + public static final int SAMPLE_RATE = 48_000; + public static final int FRAME_SIZE = ThreeBandFilterBank.FULL_BAND_SIZE; + + private volatile boolean noiseSuppression; + private volatile SuppressionLevel suppressionLevel = SuppressionLevel.DB_12; + private volatile boolean transientSuppression; + private volatile boolean gainControl; + private volatile float gainBoostDb; + private final AtomicBoolean keyPressed = new AtomicBoolean(); + + private final ThreeBandFilterBank filterBank = new ThreeBandFilterBank(); + private HighPassFilter highPassFilter; + private NoiseSuppressor noiseSuppressor; + private TransientSuppressor transientSuppressor; + private GainController2 gainController; + + private final float[] fullBand = new float[FRAME_SIZE]; + private final float[][] bands = new float[ThreeBandFilterBank.NUM_BANDS][ThreeBandFilterBank.SPLIT_BAND_SIZE]; + + public void setNoiseSuppression(boolean enabled) { + this.noiseSuppression = enabled; + } + + public void setSuppressionLevel(SuppressionLevel level) { + this.suppressionLevel = level; + } + + public void setTransientSuppression(boolean enabled) { + this.transientSuppression = enabled; + } + + public void setGainControl(boolean enabled) { + this.gainControl = enabled; + } + + /** Lets the gain control raise the noise floor this many dB higher to reach quiet speech. */ + public void setGainBoost(float db) { + this.gainBoostDb = db; + } + + /** Reports a key press anywhere on the system; the transient suppressor only acts while typing. */ + public void keyPressed() { + keyPressed.set(true); + } + + /** Drops all filter state; call when (re)starting capture. */ + public void reset() { + highPassFilter = null; + noiseSuppressor = null; + transientSuppressor = null; + gainController = null; + keyPressed.set(false); + } + + /** + * Processes mono samples in [-1, 1] in place. {@code len} must be a multiple of + * {@link #FRAME_SIZE}. + */ + public void process(float[] buf, int len) { + for (int offset = 0; offset + FRAME_SIZE <= len; offset += FRAME_SIZE) { + processFrame(buf, offset); + } + } + + private void processFrame(float[] buf, int offset) { + applyConfig(); + boolean key = keyPressed.getAndSet(false); + if (noiseSuppressor == null && transientSuppressor == null && gainController == null) return; + + // APM carries samples on the 16-bit scale. + for (int i = 0; i < FRAME_SIZE; i++) { + fullBand[i] = Math.max(-1.f, Math.min(1.f, buf[offset + i])) * 32768.f; + } + + if (highPassFilter != null) { + highPassFilter.process(fullBand, FRAME_SIZE); + } + if (noiseSuppressor != null || transientSuppressor != null) { + filterBank.analysis(fullBand, bands); + } + if (noiseSuppressor != null) { + noiseSuppressor.analyze(bands[0]); + noiseSuppressor.process(bands); + filterBank.synthesis(bands, fullBand); + } + if (transientSuppressor != null) { + transientSuppressor.suppress(fullBand, bands[0], key); + } + if (gainController != null) { + gainController.process(fullBand); + } + + for (int i = 0; i < FRAME_SIZE; i++) { + buf[offset + i] = Math.max(-32768.f, Math.min(32768.f, fullBand[i])) * (1.f / 32768.f); + } + } + + /** Creates or drops stages to match the settings, as APM's {@code ApplyConfig} does. */ + private void applyConfig() { + SuppressionLevel level = suppressionLevel; + if (!noiseSuppression) { + noiseSuppressor = null; + highPassFilter = null; + } else if (noiseSuppressor == null || noiseSuppressor.level() != level) { + // APM builds a fresh suppressor on a level change; the statistics restart too. + noiseSuppressor = new NoiseSuppressor(level, ThreeBandFilterBank.NUM_BANDS); + if (highPassFilter == null) highPassFilter = new HighPassFilter(); + } + + if (!transientSuppression) { + transientSuppressor = null; + } else if (transientSuppressor == null) { + transientSuppressor = new TransientSuppressor(SAMPLE_RATE / ThreeBandFilterBank.NUM_BANDS); + } + + if (!gainControl) { + gainController = null; + } else if (gainController == null) { + gainController = new GainController2(AdaptiveDigitalConfig.DEFAULT); + } + if (gainController != null) { + gainController.setMaxOutputNoiseLevelDbfs(AdaptiveDigitalConfig.DEFAULT.maxOutputNoiseLevelDbfs() + gainBoostDb); + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/HighPassFilter.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/HighPassFilter.java new file mode 100644 index 0000000..e3cd80d --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/HighPassFilter.java @@ -0,0 +1,32 @@ +package eu.lixko.ts3j.client.audio.processing; + +/** + * APM's high-pass filter at 48 kHz ({@code high_pass_filter.cc}): one second-order + * Butterworth section at 100 Hz, {@code butter(2, 100/24000, 'high')}, in direct form I. + */ +final class HighPassFilter { + + private static final float B0 = 0.99079f; + private static final float B1 = -1.98157f; + private static final float B2 = 0.99079f; + private static final float A1 = -1.98149f; + private static final float A2 = 0.98166f; + + private float x0, x1, y0, y1; + + void process(float[] y, int len) { + float mx0 = x0, mx1 = x1, my0 = y0, my1 = y1; + for (int k = 0; k < len; k++) { + final float tmp = y[k]; + y[k] = B0 * tmp + B1 * mx0 + B2 * mx1 - A1 * my0 - A2 * my1; + mx1 = mx0; + mx0 = tmp; + my1 = my0; + my0 = y[k]; + } + x0 = mx0; + x1 = mx1; + y0 = my0; + y1 = my1; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ThreeBandFilterBank.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ThreeBandFilterBank.java new file mode 100644 index 0000000..c4822dd --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ThreeBandFilterBank.java @@ -0,0 +1,152 @@ +package eu.lixko.ts3j.client.audio.processing; + +/** + * Splits 10 ms of 48 kHz audio into three 16 kHz bands (0–8, 8–16 and + * 16–24 kHz) and merges them back, ported from WebRTC's + * {@code three_band_filter_bank.cc}. It is how APM feeds the noise suppressor at 48 kHz. + * + *

    A cosine-modulated polyphase filter bank: the half-bandwidth low-pass prototype (a + * 48-tap Kaiser-windowed FIR, stored as ten non-zero 4-tap phases) is shifted to the three + * band centres by a DCT. + */ +final class ThreeBandFilterBank { + + static final int NUM_BANDS = 3; + static final int FULL_BAND_SIZE = 480; + static final int SPLIT_BAND_SIZE = FULL_BAND_SIZE / NUM_BANDS; + + private static final int SPARSITY = 4; + private static final int STRIDE_LOG2 = 2; + private static final int STRIDE = 1 << STRIDE_LOG2; + private static final int NUM_ZERO_FILTERS = 2; + private static final int FILTER_SIZE = 4; + private static final int MEMORY_SIZE = FILTER_SIZE * STRIDE - 1; + private static final int NUM_NON_ZERO_FILTERS = SPARSITY * NUM_BANDS - NUM_ZERO_FILTERS; + private static final int SUB_SAMPLING = NUM_BANDS; + private static final int ZERO_FILTER_INDEX_1 = 3; + private static final int ZERO_FILTER_INDEX_2 = 9; + + private static final float[][] FILTER_COEFFS = { + {-0.00047749f, -0.00496888f, +0.16547118f, +0.00425496f}, + {-0.00173287f, -0.01585778f, +0.14989004f, +0.00994113f}, + {-0.00304815f, -0.02536082f, +0.12154542f, +0.01157993f}, + {-0.00346946f, -0.02587886f, +0.04760441f, +0.00607594f}, + {-0.00154717f, -0.01136076f, +0.01387458f, +0.00186353f}, + {+0.00186353f, +0.01387458f, -0.01136076f, -0.00154717f}, + {+0.00607594f, +0.04760441f, -0.02587886f, -0.00346946f}, + {+0.00983212f, +0.08543175f, -0.02982767f, -0.00383509f}, + {+0.00994113f, +0.14989004f, -0.01585778f, -0.00173287f}, + {+0.00425496f, +0.16547118f, -0.00496888f, -0.00047749f}}; + + private static final float[][] DCT_MODULATION = { + {2.f, 2.f, 2.f}, + {1.73205077f, 0.f, -1.73205077f}, + {1.f, -2.f, 1.f}, + {-1.f, 2.f, -1.f}, + {-1.73205077f, 0.f, 1.73205077f}, + {-2.f, -2.f, -2.f}, + {-1.73205077f, 0.f, 1.73205077f}, + {-1.f, 2.f, -1.f}, + {1.f, -2.f, 1.f}, + {1.73205077f, 0.f, -1.73205077f}}; + + private final float[][] stateAnalysis = new float[NUM_NON_ZERO_FILTERS][MEMORY_SIZE]; + private final float[][] stateSynthesis = new float[NUM_NON_ZERO_FILTERS][MEMORY_SIZE]; + + private final float[] inSubsampled = new float[SPLIT_BAND_SIZE]; + private final float[] outSubsampled = new float[SPLIT_BAND_SIZE]; + + /** Splits {@code in} (480 samples) into {@code out[band]} (160 samples each). */ + void analysis(float[] in, float[][] out) { + for (int band = 0; band < NUM_BANDS; band++) { + java.util.Arrays.fill(out[band], 0, SPLIT_BAND_SIZE, 0.f); + } + + for (int downsamplingIndex = 0; downsamplingIndex < SUB_SAMPLING; downsamplingIndex++) { + for (int k = 0; k < SPLIT_BAND_SIZE; k++) { + inSubsampled[k] = in[(SUB_SAMPLING - 1) - downsamplingIndex + SUB_SAMPLING * k]; + } + + for (int inShift = 0; inShift < STRIDE; inShift++) { + int filterIndex = filterIndex(downsamplingIndex + inShift * SUB_SAMPLING); + if (filterIndex < 0) continue; + + filterCore(FILTER_COEFFS[filterIndex], inSubsampled, inShift, outSubsampled, + stateAnalysis[filterIndex]); + + float[] dct = DCT_MODULATION[filterIndex]; + for (int band = 0; band < NUM_BANDS; band++) { + float[] outBand = out[band]; + for (int n = 0; n < SPLIT_BAND_SIZE; n++) { + outBand[n] += dct[band] * outSubsampled[n]; + } + } + } + } + } + + /** Merges {@code in[band]} (160 samples each) back into {@code out} (480 samples). */ + void synthesis(float[][] in, float[] out) { + java.util.Arrays.fill(out, 0, FULL_BAND_SIZE, 0.f); + for (int upsamplingIndex = 0; upsamplingIndex < SUB_SAMPLING; upsamplingIndex++) { + for (int inShift = 0; inShift < STRIDE; inShift++) { + int filterIndex = filterIndex(upsamplingIndex + inShift * SUB_SAMPLING); + if (filterIndex < 0) continue; + + float[] dct = DCT_MODULATION[filterIndex]; + java.util.Arrays.fill(inSubsampled, 0.f); + for (int band = 0; band < NUM_BANDS; band++) { + float[] inBand = in[band]; + for (int n = 0; n < SPLIT_BAND_SIZE; n++) { + inSubsampled[n] += dct[band] * inBand[n]; + } + } + + filterCore(FILTER_COEFFS[filterIndex], inSubsampled, inShift, outSubsampled, + stateSynthesis[filterIndex]); + + final float upsamplingScaling = SUB_SAMPLING; + for (int k = 0; k < SPLIT_BAND_SIZE; k++) { + out[upsamplingIndex + SUB_SAMPLING * k] += upsamplingScaling * outSubsampled[k]; + } + } + } + } + + /** Maps a polyphase index to its stored filter, or -1 for the two all-zero phases. */ + private static int filterIndex(int index) { + if (index == ZERO_FILTER_INDEX_1 || index == ZERO_FILTER_INDEX_2) return -1; + if (index < ZERO_FILTER_INDEX_1) return index; + return index < ZERO_FILTER_INDEX_2 ? index - 1 : index - 2; + } + + /** Filters {@code in} with the sparse (upsampled by {@code STRIDE}) filter, shifted by {@code inShift}. */ + private static void filterCore(float[] filter, float[] in, int inShift, float[] out, float[] state) { + java.util.Arrays.fill(out, 0.f); + for (int k = 0; k < inShift; k++) { + for (int i = 0, j = MEMORY_SIZE + k - inShift; i < FILTER_SIZE; i++, j -= STRIDE) { + out[k] += state[j] * filter[i]; + } + } + + for (int k = inShift, shift = 0; k < FILTER_SIZE * STRIDE; k++, shift++) { + final int loopLimit = Math.min(FILTER_SIZE, 1 + (shift >> STRIDE_LOG2)); + for (int i = 0, j = shift; i < loopLimit; i++, j -= STRIDE) { + out[k] += in[j] * filter[i]; + } + for (int i = loopLimit, j = MEMORY_SIZE + shift - loopLimit * STRIDE; i < FILTER_SIZE; + i++, j -= STRIDE) { + out[k] += state[j] * filter[i]; + } + } + + for (int k = FILTER_SIZE * STRIDE, shift = FILTER_SIZE * STRIDE - inShift; k < SPLIT_BAND_SIZE; + k++, shift++) { + for (int i = 0, j = shift; i < FILTER_SIZE; i++, j -= STRIDE) { + out[k] += in[j] * filter[i]; + } + } + + System.arraycopy(in, SPLIT_BAND_SIZE - MEMORY_SIZE, state, 0, MEMORY_SIZE); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/AdaptiveDigitalConfig.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/AdaptiveDigitalConfig.java new file mode 100644 index 0000000..48d4d76 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/AdaptiveDigitalConfig.java @@ -0,0 +1,11 @@ +package eu.lixko.ts3j.client.audio.processing.agc2; + +/** + * AGC2's adaptive digital settings, {@code GainController2::AdaptiveDigital} in + * {@code audio_processing.h}. {@link #DEFAULT} holds WebRTC's defaults. + */ +public record AdaptiveDigitalConfig(float headroomDb, float maxGainDb, float initialGainDb, + float maxGainChangeDbPerSecond, float maxOutputNoiseLevelDbfs) { + + public static final AdaptiveDigitalConfig DEFAULT = new AdaptiveDigitalConfig(5.0f, 50.0f, 15.0f, 6.0f, -50.0f); +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/AdaptiveDigitalGainController.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/AdaptiveDigitalGainController.java new file mode 100644 index 0000000..d1b8310 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/AdaptiveDigitalGainController.java @@ -0,0 +1,103 @@ +package eu.lixko.ts3j.client.audio.processing.agc2; + +import static eu.lixko.ts3j.client.audio.processing.agc2.Agc2Common.FRAME_DURATION_MS; +import static eu.lixko.ts3j.client.audio.processing.agc2.Agc2Common.LIMITER_THRESHOLD_FOR_AGC_GAIN_DBFS; +import static eu.lixko.ts3j.client.audio.processing.agc2.Agc2Common.VAD_CONFIDENCE_THRESHOLD; + +/** + * Picks and applies the adaptive gain, from {@code agc2/adaptive_digital_gain_controller.cc}: + * enough to bring the speech level (plus headroom) up to just below full scale, limited so + * the noise floor stays under {@code maxOutputNoiseLevelDbfs}, and moved at most + * {@code maxGainChangeDbPerSecond}. It only raises the gain after a run of confident speech. + */ +final class AdaptiveDigitalGainController { + + /** What the controller knows about the current frame. */ + record FrameInfo(float speechProbability, float speechLevelDbfs, boolean speechLevelReliable, + float noiseRmsDbfs, float headroomDb, float limiterEnvelopeDbfs) { + } + + private final GainApplier gainApplier; + private final AdaptiveDigitalConfig config; + private final int adjacentSpeechFramesThreshold; + private final float maxGainChangeDbPer10ms; + private float maxOutputNoiseLevelDbfs; + private int framesToGainIncreaseAllowed; + private float lastGainDb; + + AdaptiveDigitalGainController(AdaptiveDigitalConfig config, int adjacentSpeechFramesThreshold) { + this.config = config; + this.adjacentSpeechFramesThreshold = adjacentSpeechFramesThreshold; + this.gainApplier = new GainApplier(Agc2Common.dbToRatio(config.initialGainDb())); + this.maxGainChangeDbPer10ms = config.maxGainChangeDbPerSecond() * FRAME_DURATION_MS / 1000.0f; + this.framesToGainIncreaseAllowed = adjacentSpeechFramesThreshold; + this.lastGainDb = config.initialGainDb(); + this.maxOutputNoiseLevelDbfs = config.maxOutputNoiseLevelDbfs(); + } + + void setMaxOutputNoiseLevelDbfs(float dbfs) { + maxOutputNoiseLevelDbfs = dbfs; + } + + void process(FrameInfo info, float[] frame, int samples) { + final float inputLevelDbfs = info.speechLevelDbfs() + info.headroomDb(); + final float targetGainDb = limitGainByLowConfidence( + limitGainByNoise(computeGainDb(inputLevelDbfs), info.noiseRmsDbfs()), + lastGainDb, info.limiterEnvelopeDbfs(), info.speechLevelReliable()); + + // Only allow the gain to rise after a run of confident speech frames. + boolean firstConfidentSpeechFrame = false; + if (info.speechProbability() < VAD_CONFIDENCE_THRESHOLD) { + framesToGainIncreaseAllowed = adjacentSpeechFramesThreshold; + } else if (framesToGainIncreaseAllowed > 0) { + framesToGainIncreaseAllowed--; + firstConfidentSpeechFrame = framesToGainIncreaseAllowed == 0; + } + final boolean gainIncreaseAllowed = framesToGainIncreaseAllowed == 0; + + float maxGainIncreaseDb = maxGainChangeDbPer10ms; + if (firstConfidentSpeechFrame) { + // Make up for the frames the increase was held back. + maxGainIncreaseDb *= adjacentSpeechFramesThreshold; + } + + float difference = targetGainDb - lastGainDb; + if (!gainIncreaseAllowed) { + difference = Math.min(difference, 0.0f); + } + final float gainChangeThisFrameDb = Math.max(-maxGainChangeDbPer10ms, Math.min(maxGainIncreaseDb, difference)); + + if (gainChangeThisFrameDb != 0.f) { + gainApplier.setGainFactor(Agc2Common.dbToRatio(lastGainDb + gainChangeThisFrameDb)); + } + gainApplier.applyGain(frame, samples); + lastGainDb = lastGainDb + gainChangeThisFrameDb; + } + + /** The gain that puts the input level at {@code -headroomDb}, capped at {@code maxGainDb}. */ + private float computeGainDb(float inputLevelDbfs) { + if (inputLevelDbfs < -(config.headroomDb() + config.maxGainDb())) { + return config.maxGainDb(); + } + if (inputLevelDbfs < -config.headroomDb()) { + return -config.headroomDb() - inputLevelDbfs; + } + return 0.0f; + } + + private float limitGainByNoise(float targetGainDb, float inputNoiseLevelDbfs) { + final float maxAllowedGainDb = maxOutputNoiseLevelDbfs - inputNoiseLevelDbfs; + return Math.min(targetGainDb, Math.max(maxAllowedGainDb, 0.0f)); + } + + /** Until the speech level is trusted, don't push the limiter's envelope above -1 dBFS. */ + private static float limitGainByLowConfidence(float targetGainDb, float lastGainDb, + float limiterAudioLevelDbfs, boolean estimateIsConfident) { + if (estimateIsConfident || limiterAudioLevelDbfs <= LIMITER_THRESHOLD_FOR_AGC_GAIN_DBFS) { + return targetGainDb; + } + final float limiterLevelDbfsBeforeGain = limiterAudioLevelDbfs - lastGainDb; + final float newTargetGainDb = Math.max(LIMITER_THRESHOLD_FOR_AGC_GAIN_DBFS - limiterLevelDbfsBeforeGain, 0.0f); + return Math.min(newTargetGainDb, targetGainDb); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/Agc2Common.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/Agc2Common.java new file mode 100644 index 0000000..5b71c82 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/Agc2Common.java @@ -0,0 +1,41 @@ +package eu.lixko.ts3j.client.audio.processing.agc2; + +/** Constants and level conversions shared by AGC2, from {@code agc2/agc2_common.h} and {@code audio_util.h}. */ +final class Agc2Common { + + static final float MIN_FLOAT_S16_VALUE = -32768.0f; + static final float MAX_FLOAT_S16_VALUE = 32767.0f; + static final float MIN_LEVEL_DBFS = -90.31f; + + static final int FRAME_DURATION_MS = 10; + static final int SUB_FRAMES_IN_FRAME = 20; + + /** Target peak for the limiter's envelope when the speech level isn't trusted yet. */ + static final float LIMITER_THRESHOLD_FOR_AGC_GAIN_DBFS = -1.0f; + + static final int VAD_RESET_PERIOD_MS = 1500; + static final float VAD_CONFIDENCE_THRESHOLD = 0.95f; + static final int ADJACENT_SPEECH_FRAMES_THRESHOLD = 12; + + static final float LEVEL_ESTIMATOR_TIME_TO_CONFIDENCE_MS = 400; + static final float LEVEL_ESTIMATOR_LEAK_FACTOR = 1.0f - 1.0f / LEVEL_ESTIMATOR_TIME_TO_CONFIDENCE_MS; + + static final float SATURATION_PROTECTOR_INITIAL_HEADROOM_DB = 20.0f; + static final int SATURATION_PROTECTOR_BUFFER_SIZE = 4; + + private Agc2Common() { + } + + static float dbToRatio(float db) { + return (float) Math.pow(10.0f, db / 20.0f); + } + + /** Level of a 16-bit-scale amplitude in dBFS, floored at the int16 noise floor. */ + static float floatS16ToDbfs(float v) { + final float minDbfs = -90.30899869919436f; + if (v <= 1.0f) { + return minDbfs; + } + return 20.0f * (float) Math.log10(v) + minDbfs; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/GainApplier.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/GainApplier.java new file mode 100644 index 0000000..eec3bc0 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/GainApplier.java @@ -0,0 +1,46 @@ +package eu.lixko.ts3j.client.audio.processing.agc2; + +/** + * Applies a gain factor, ramping linearly across the frame from the previous factor, from + * {@code agc2/gain_applier.cc}. + */ +final class GainApplier { + + private float lastGainFactor; + private float currentGainFactor; + + GainApplier(float initialGainFactor) { + this.lastGainFactor = initialGainFactor; + this.currentGainFactor = initialGainFactor; + } + + void setGainFactor(float gainFactor) { + currentGainFactor = gainFactor; + } + + void applyGain(float[] frame, int samples) { + final float last = lastGainFactor; + final float target = currentGainFactor; + lastGainFactor = currentGainFactor; + if (last == target && gainCloseToOne(target)) { + return; + } + if (last == target) { + for (int i = 0; i < samples; i++) { + frame[i] *= target; + } + return; + } + final float increment = (target - last) * (1.f / samples); + float gain = last; + for (int i = 0; i < samples; i++) { + frame[i] *= gain; + gain += increment; + } + } + + private static boolean gainCloseToOne(float gainFactor) { + return 1.f - 1.f / Agc2Common.MAX_FLOAT_S16_VALUE <= gainFactor + && gainFactor <= 1.f + 1.f / Agc2Common.MAX_FLOAT_S16_VALUE; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/GainController2.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/GainController2.java new file mode 100644 index 0000000..192db3b --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/GainController2.java @@ -0,0 +1,92 @@ +package eu.lixko.ts3j.client.audio.processing.agc2; + +import static eu.lixko.ts3j.client.audio.processing.agc2.Agc2Common.ADJACENT_SPEECH_FRAMES_THRESHOLD; +import static eu.lixko.ts3j.client.audio.processing.agc2.Agc2Common.FRAME_DURATION_MS; +import static eu.lixko.ts3j.client.audio.processing.agc2.Agc2Common.SATURATION_PROTECTOR_INITIAL_HEADROOM_DB; +import static eu.lixko.ts3j.client.audio.processing.agc2.Agc2Common.VAD_RESET_PERIOD_MS; + +import eu.lixko.ts3j.client.audio.vad.RnnSpeechDetector; + +/** + * WebRTC's AGC2 with the adaptive digital controller, as APM runs it + * ({@code gain_controller2.cc}): its own RNN VAD, speech and noise level estimators, a + * saturation protector choosing the headroom, the adaptive gain, and the output limiter. + * + *

    TS3 uses the older AGC1 in adaptive-digital mode instead. AGC2 is its replacement in + * WebRTC: it measures the speech level only on frames its RNN VAD calls speech, and caps + * the gain so the measured noise floor stays below -50 dBFS. + * + *

    It is also slower to adapt: the gain rises at most 6 dB/s, and only after 12 + * frames in a row that its VAD rates at 0.95 or more, holding still through pauses. A + * distant voice in a reverberant room (half its frames that confident) took about 9 s + * of talking to go from the initial 15 dB to the 26 dB it settled at. How fast + * AGC1 follows the same voice hasn't been measured. + * + *

    Takes 10 ms mono frames at 48 kHz on the 16-bit scale, in place. + */ +public final class GainController2 { + + private static final int FRAME_SIZE = 480; + + private final RnnSpeechDetector vad = new RnnSpeechDetector(48_000); + private final float[] vadFrame = new float[FRAME_SIZE]; + private final int vadResetPeriodFrames = VAD_RESET_PERIOD_MS / FRAME_DURATION_MS; + private int timeToVadReset = vadResetPeriodFrames; + + private final SpeechLevelEstimator speechLevelEstimator; + private final NoiseFloorEstimator noiseLevelEstimator = new NoiseFloorEstimator(); + private final SaturationProtector saturationProtector = + new SaturationProtector(SATURATION_PROTECTOR_INITIAL_HEADROOM_DB, ADJACENT_SPEECH_FRAMES_THRESHOLD); + private final AdaptiveDigitalGainController adaptiveDigitalController; + private final Limiter limiter = new Limiter(); + + public GainController2(AdaptiveDigitalConfig config) { + this.speechLevelEstimator = new SpeechLevelEstimator(config, ADJACENT_SPEECH_FRAMES_THRESHOLD); + this.adaptiveDigitalController = new AdaptiveDigitalGainController(config, ADJACENT_SPEECH_FRAMES_THRESHOLD); + } + + /** + * Moves the cap on the amplified noise floor away from the configured + * {@code maxOutputNoiseLevelDbfs}, keeping the rest of the controller's state. + */ + public void setMaxOutputNoiseLevelDbfs(float dbfs) { + adaptiveDigitalController.setMaxOutputNoiseLevelDbfs(dbfs); + } + + public void process(float[] frame) { + final float speechProbability = analyzeVad(frame); + + float peak = 0.0f; + float rms = 0.0f; + for (int i = 0; i < FRAME_SIZE; i++) { + peak = Math.max(Math.abs(frame[i]), peak); + rms += frame[i] * frame[i]; + } + final float peakDbfs = Agc2Common.floatS16ToDbfs(peak); + final float rmsDbfs = Agc2Common.floatS16ToDbfs((float) Math.sqrt(rms / FRAME_SIZE)); + + final float noiseRmsDbfs = noiseLevelEstimator.analyze(frame, FRAME_SIZE); + speechLevelEstimator.update(rmsDbfs, peakDbfs, speechProbability); + final float speechLevelDbfs = speechLevelEstimator.levelDbfs(); + + saturationProtector.analyze(speechProbability, peakDbfs, speechLevelDbfs); + final float limiterEnvelopeDbfs = Agc2Common.floatS16ToDbfs(limiter.lastAudioLevel()); + + adaptiveDigitalController.process(new AdaptiveDigitalGainController.FrameInfo( + speechProbability, speechLevelDbfs, speechLevelEstimator.isConfident(), + noiseRmsDbfs, saturationProtector.headroomDb(), limiterEnvelopeDbfs), frame, FRAME_SIZE); + limiter.process(frame, FRAME_SIZE); + } + + /** {@code vad_wrapper.cc}: the RNN's state is reset every 1.5 s so it can't latch. */ + private float analyzeVad(float[] frame) { + if (--timeToVadReset <= 0) { + vad.resetNetwork(); + timeToVadReset = vadResetPeriodFrames; + } + for (int i = 0; i < FRAME_SIZE; i++) { + vadFrame[i] = frame[i] * (1.f / 32768.f); + } + return (float) vad.process(vadFrame, FRAME_SIZE); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/InterpolatedGainCurve.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/InterpolatedGainCurve.java new file mode 100644 index 0000000..a327035 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/InterpolatedGainCurve.java @@ -0,0 +1,76 @@ +package eu.lixko.ts3j.client.audio.processing.agc2; + +/** + * The limiter's gain curve as a piecewise-linear table, from + * {@code agc2/interpolated_gain_curve.h}: identity below the knee (about -0.8 dBFS), + * then a soft knee into a hard limit at full scale. + */ +final class InterpolatedGainCurve { + + private static final float MAX_INPUT_LEVEL_LINEAR = 36766.300710566735f; + + private static final float[] X = { + 30057.296875f, 30148.986328125f, 30240.67578125f, 30424.052734375f, + 30607.4296875f, 30790.806640625f, 30974.18359375f, 31157.560546875f, + 31340.939453125f, 31524.31640625f, 31707.693359375f, 31891.0703125f, + 32074.447265625f, 32257.82421875f, 32441.201171875f, 32624.580078125f, + 32807.95703125f, 32991.33203125f, 33174.7109375f, 33358.08984375f, + 33541.46484375f, 33724.84375f, 33819.53515625f, 34009.5390625f, + 34200.05859375f, 34389.81640625f, 34674.48828125f, 35054.375f, + 35434.86328125f, 35814.81640625f, 36195.16796875f, 36575.03125f}; + + private static final float[] M = { + -3.515235675877192989e-07f, -1.050251626111275982e-06f, + -2.085213736791047268e-06f, -3.443004743530764244e-06f, + -4.773849468620028347e-06f, -6.077375928725814447e-06f, + -7.353257842623861507e-06f, -8.601219633419532329e-06f, + -9.821013009059242904e-06f, -1.101243378798244521e-05f, + -1.217532644659513608e-05f, -1.330956911260727793e-05f, + -1.441507538402220234e-05f, -1.549179251014720649e-05f, + -1.653970684856176376e-05f, -1.755882840370759368e-05f, + -1.854918446042574942e-05f, -1.951086778717581183e-05f, + -2.044398024736437947e-05f, -2.1348627342376858e-05f, + -2.222496914328075945e-05f, -2.265374678245279938e-05f, + -2.242570917587727308e-05f, -2.220122041762806475e-05f, + -2.19802095671184361e-05f, -2.176260204578284174e-05f, + -2.133731686626560986e-05f, -2.092481918225530535e-05f, + -2.052459603874012828e-05f, -2.013615448959171772e-05f, + -1.975903069251216948e-05f, -1.939277899509761482e-05f}; + + private static final float[] Q = { + 1.010565876960754395f, 1.031631827354431152f, 1.062929749488830566f, + 1.104239225387573242f, 1.144973039627075195f, 1.185109615325927734f, + 1.224629044532775879f, 1.263512492179870605f, 1.301741957664489746f, + 1.339300632476806641f, 1.376173257827758789f, 1.412345528602600098f, + 1.447803974151611328f, 1.482536554336547852f, 1.516532182693481445f, + 1.549780607223510742f, 1.582272171974182129f, 1.613999366760253906f, + 1.644955039024353027f, 1.675132393836975098f, 1.704526185989379883f, + 1.718986630439758301f, 1.711274504661560059f, 1.703639745712280273f, + 1.696081161499023438f, 1.688597679138183594f, 1.673851132392883301f, + 1.659391283988952637f, 1.645209431648254395f, 1.631297469139099121f, + 1.617647409439086914f, 1.604251742362976074f}; + + private InterpolatedGainCurve() { + } + + /** The gain to apply at {@code inputLevel}, a 16-bit-scale peak level. */ + static float lookUpGainToApply(float inputLevel) { + if (inputLevel <= X[0]) { + return 1.0f; + } + if (inputLevel >= MAX_INPUT_LEVEL_LINEAR) { + // Saturating: scale the peak straight down to full scale. + return 32768.f / inputLevel; + } + // Segment whose start is the last point below inputLevel (lower_bound - 1). + int lo = 0; + int hi = X.length; + while (lo < hi) { + int mid = (lo + hi) >>> 1; + if (X[mid] < inputLevel) lo = mid + 1; + else hi = mid; + } + final int index = lo - 1; + return M[index] * inputLevel + Q[index]; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/Limiter.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/Limiter.java new file mode 100644 index 0000000..2cdf4b8 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/Limiter.java @@ -0,0 +1,91 @@ +package eu.lixko.ts3j.client.audio.processing.agc2; + +import static eu.lixko.ts3j.client.audio.processing.agc2.Agc2Common.MAX_FLOAT_S16_VALUE; +import static eu.lixko.ts3j.client.audio.processing.agc2.Agc2Common.MIN_FLOAT_S16_VALUE; +import static eu.lixko.ts3j.client.audio.processing.agc2.Agc2Common.SUB_FRAMES_IN_FRAME; + +/** + * AGC2's output limiter, from {@code agc2/limiter.cc} and {@code fixed_digital_level_estimator.cc}: + * a peak envelope per 1/20 of the frame (instant attack, slow decay) looked up on the + * limiter's gain curve, with the gain interpolated across the sub-frames. + */ +final class Limiter { + + private static final float ATTACK_FILTER_CONSTANT = 0.0f; + private static final float DECAY_FILTER_CONSTANT = 0.9971259f; + private static final float ATTACK_FIRST_SUBFRAME_INTERPOLATION_POWER = 8.0f; + + private final float[] envelope = new float[SUB_FRAMES_IN_FRAME]; + private final float[] scalingFactors = new float[SUB_FRAMES_IN_FRAME + 1]; + private final float[] perSampleScalingFactors = new float[480]; + private float filterStateLevel; + private float lastScalingFactor = 1.f; + + /** The envelope level of the last sub-frame, on the 16-bit scale. */ + float lastAudioLevel() { + return filterStateLevel; + } + + void process(float[] frame, int samples) { + computeLevel(frame, samples); + + scalingFactors[0] = lastScalingFactor; + for (int i = 0; i < SUB_FRAMES_IN_FRAME; i++) { + scalingFactors[i + 1] = InterpolatedGainCurve.lookUpGainToApply(envelope[i]); + } + + computePerSampleSubframeFactors(samples); + for (int j = 0; j < samples; j++) { + frame[j] = Math.max(MIN_FLOAT_S16_VALUE, Math.min(MAX_FLOAT_S16_VALUE, frame[j] * perSampleScalingFactors[j])); + } + lastScalingFactor = scalingFactors[SUB_FRAMES_IN_FRAME]; + } + + private void computeLevel(float[] frame, int samples) { + final int samplesInSubFrame = samples / SUB_FRAMES_IN_FRAME; + java.util.Arrays.fill(envelope, 0.f); + for (int subFrame = 0; subFrame < SUB_FRAMES_IN_FRAME; subFrame++) { + for (int i = 0; i < samplesInSubFrame; i++) { + envelope[subFrame] = Math.max(envelope[subFrame], Math.abs(frame[subFrame * samplesInSubFrame + i])); + } + } + // Look one sub-frame ahead, so the gain is already down when a peak arrives. + for (int subFrame = 0; subFrame < SUB_FRAMES_IN_FRAME - 1; subFrame++) { + if (envelope[subFrame] < envelope[subFrame + 1]) { + envelope[subFrame] = envelope[subFrame + 1]; + } + } + for (int subFrame = 0; subFrame < SUB_FRAMES_IN_FRAME; subFrame++) { + final float value = envelope[subFrame]; + if (value > filterStateLevel) { + envelope[subFrame] = value * (1 - ATTACK_FILTER_CONSTANT) + filterStateLevel * ATTACK_FILTER_CONSTANT; + } else { + envelope[subFrame] = value * (1 - DECAY_FILTER_CONSTANT) + filterStateLevel * DECAY_FILTER_CONSTANT; + } + filterStateLevel = envelope[subFrame]; + } + } + + private void computePerSampleSubframeFactors(int samples) { + final int subframeSize = samples / SUB_FRAMES_IN_FRAME; + final boolean isAttack = scalingFactors[0] > scalingFactors[1]; + if (isAttack) { + // Upstream intends a power-curve fade here, but its i / n is integer division + // and always 0, so the first sub-frame holds the previous factor. Kept as is. + final int n = subframeSize; + for (int i = 0; i < n; i++) { + perSampleScalingFactors[i] = (float) Math.pow(1.f - i / n, ATTACK_FIRST_SUBFRAME_INTERPOLATION_POWER) + * (scalingFactors[0] - scalingFactors[1]) + scalingFactors[1]; + } + } + for (int i = isAttack ? 1 : 0; i < SUB_FRAMES_IN_FRAME; i++) { + final int subframeStart = i * subframeSize; + final float scalingStart = scalingFactors[i]; + final float scalingEnd = scalingFactors[i + 1]; + final float scalingDiff = (scalingEnd - scalingStart) / subframeSize; + for (int j = 0; j < subframeSize; j++) { + perSampleScalingFactors[subframeStart + j] = scalingStart + scalingDiff * j; + } + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/NoiseFloorEstimator.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/NoiseFloorEstimator.java new file mode 100644 index 0000000..fccbf8f --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/NoiseFloorEstimator.java @@ -0,0 +1,90 @@ +package eu.lixko.ts3j.client.audio.processing.agc2; + +/** + * Estimates the background noise level, from {@code agc2/noise_level_estimator.cc}: the + * minimum frame energy over 5 s periods, rising only slowly between periods, so AGC2 + * can cap its gain before it amplifies the noise floor. + */ +final class NoiseFloorEstimator { + + private static final int FRAMES_PER_SECOND = 100; + private static final int UPDATE_PERIOD_NUM_FRAMES = 500; + + private int sampleRateHz; + private float minNoiseEnergy; + private boolean firstPeriod; + private boolean preliminaryNoiseEnergySet; + private float preliminaryNoiseEnergy; + private float noiseEnergy; + private int counter; + + NoiseFloorEstimator() { + initialize(48000); + } + + /** @return the noise RMS in dBFS */ + float analyze(float[] frame, int samples) { + final int rate = samples * FRAMES_PER_SECOND; + if (rate != sampleRateHz) { + initialize(rate); + } + float frameEnergy = 0.0f; + for (int i = 0; i < samples; i++) { + frameEnergy += frame[i] * frame[i]; + } + if (frameEnergy <= minNoiseEnergy) { + // Ignore frames at or below the int16 noise floor, e.g. digital silence. + return energyToDbfs(noiseEnergy, samples); + } + + if (preliminaryNoiseEnergySet) { + preliminaryNoiseEnergy = Math.min(preliminaryNoiseEnergy, frameEnergy); + } else { + preliminaryNoiseEnergy = frameEnergy; + preliminaryNoiseEnergySet = true; + } + + if (counter == 0) { + // Period over: move towards the new minimum, slowly if it rose. + firstPeriod = false; + noiseEnergy = smooth(noiseEnergy, preliminaryNoiseEnergy); + counter = UPDATE_PERIOD_NUM_FRAMES; + preliminaryNoiseEnergySet = false; + } else if (firstPeriod) { + noiseEnergy = preliminaryNoiseEnergy; + counter--; + } else { + noiseEnergy = Math.min(noiseEnergy, preliminaryNoiseEnergy); + counter--; + } + return energyToDbfs(noiseEnergy, samples); + } + + private void initialize(int rate) { + sampleRateHz = rate; + firstPeriod = true; + preliminaryNoiseEnergySet = false; + // Two LSBs of RMS: anything quieter is treated as silence. + minNoiseEnergy = rate * 2.0f * 2.0f / FRAMES_PER_SECOND; + preliminaryNoiseEnergy = minNoiseEnergy; + noiseEnergy = minNoiseEnergy; + counter = UPDATE_PERIOD_NUM_FRAMES; + } + + private static float smooth(float currentEstimate, float newEstimate) { + final float attack = 0.5f; + if (currentEstimate < newEstimate) { + return attack * newEstimate + (1.0f - attack) * currentEstimate; + } + return newEstimate; + } + + private static float energyToDbfs(float signalEnergy, int numSamples) { + final float rmsSquare = signalEnergy / numSamples; + final float minDbfs = -90.30899869919436f; + if (rmsSquare <= 1.0f) { + return minDbfs; + } + return 10.0f * (float) Math.log10(rmsSquare) + minDbfs; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/SaturationProtector.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/SaturationProtector.java new file mode 100644 index 0000000..ef528a4 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/SaturationProtector.java @@ -0,0 +1,122 @@ +package eu.lixko.ts3j.client.audio.processing.agc2; + +import static eu.lixko.ts3j.client.audio.processing.agc2.Agc2Common.FRAME_DURATION_MS; +import static eu.lixko.ts3j.client.audio.processing.agc2.Agc2Common.MIN_LEVEL_DBFS; +import static eu.lixko.ts3j.client.audio.processing.agc2.Agc2Common.SATURATION_PROTECTOR_BUFFER_SIZE; +import static eu.lixko.ts3j.client.audio.processing.agc2.Agc2Common.VAD_CONFIDENCE_THRESHOLD; + +/** + * Chooses how much headroom to leave above the speech level, from + * {@code agc2/saturation_protector.cc}: it tracks how far the speech peaks, delayed by a + * few 400 ms super-frames, sit above the speech level, and keeps the margin within + * 12–25 dB. + */ +final class SaturationProtector { + + private static final int PEAK_ENVELOPER_SUPER_FRAME_LENGTH_MS = 400; + private static final float MIN_MARGIN_DB = 12.0f; + private static final float MAX_MARGIN_DB = 25.0f; + private static final float ATTACK = 0.9988493699365052f; + private static final float DECAY = 0.9997697679981565f; + + private static final class State { + float headroomDb; + /** Ring buffer of past super-frame peaks. */ + final float[] peakDelayBuffer = new float[SATURATION_PROTECTOR_BUFFER_SIZE]; + int next; + int size; + float maxPeaksDbfs; + int timeSincePushMs; + + void reset(float initialHeadroomDb) { + headroomDb = initialHeadroomDb; + next = 0; + size = 0; + maxPeaksDbfs = MIN_LEVEL_DBFS; + timeSincePushMs = 0; + } + + void copyFrom(State o) { + headroomDb = o.headroomDb; + System.arraycopy(o.peakDelayBuffer, 0, peakDelayBuffer, 0, peakDelayBuffer.length); + next = o.next; + size = o.size; + maxPeaksDbfs = o.maxPeaksDbfs; + timeSincePushMs = o.timeSincePushMs; + } + + void push(float v) { + peakDelayBuffer[next++] = v; + if (next == peakDelayBuffer.length) next = 0; + if (size < peakDelayBuffer.length) size++; + } + + /** The oldest buffered peak, or {@code fallback} while the buffer is empty. */ + float front(float fallback) { + if (size == 0) return fallback; + return peakDelayBuffer[size == peakDelayBuffer.length ? next : 0]; + } + + void update(float peakDbfs, float speechLevelDbfs) { + maxPeaksDbfs = Math.max(maxPeaksDbfs, peakDbfs); + timeSincePushMs += FRAME_DURATION_MS; + if (timeSincePushMs > PEAK_ENVELOPER_SUPER_FRAME_LENGTH_MS) { + push(maxPeaksDbfs); + maxPeaksDbfs = MIN_LEVEL_DBFS; + timeSincePushMs = 0; + } + + final float delayedPeakDbfs = front(maxPeaksDbfs); + final float differenceDb = delayedPeakDbfs - speechLevelDbfs; + if (differenceDb > headroomDb) { + headroomDb = headroomDb * ATTACK + differenceDb * (1.0f - ATTACK); + } else { + headroomDb = headroomDb * DECAY + differenceDb * (1.0f - DECAY); + } + headroomDb = Math.max(MIN_MARGIN_DB, Math.min(MAX_MARGIN_DB, headroomDb)); + } + } + + private final float initialHeadroomDb; + private final int adjacentSpeechFramesThreshold; + private final State preliminary = new State(); + private final State reliable = new State(); + private int numAdjacentSpeechFrames; + private float headroomDb; + + SaturationProtector(float initialHeadroomDb, int adjacentSpeechFramesThreshold) { + this.initialHeadroomDb = initialHeadroomDb; + this.adjacentSpeechFramesThreshold = adjacentSpeechFramesThreshold; + reset(); + } + + float headroomDb() { + return headroomDb; + } + + void analyze(float speechProbability, float peakDbfs, float speechLevelDbfs) { + if (speechProbability < VAD_CONFIDENCE_THRESHOLD) { + if (adjacentSpeechFramesThreshold > 1) { + if (numAdjacentSpeechFrames >= adjacentSpeechFramesThreshold) { + reliable.copyFrom(preliminary); + } else if (numAdjacentSpeechFrames > 0) { + preliminary.copyFrom(reliable); + } + } + numAdjacentSpeechFrames = 0; + } else { + numAdjacentSpeechFrames++; + preliminary.update(peakDbfs, speechLevelDbfs); + if (numAdjacentSpeechFrames >= adjacentSpeechFramesThreshold) { + headroomDb = preliminary.headroomDb; + } + } + } + + void reset() { + numAdjacentSpeechFrames = 0; + headroomDb = initialHeadroomDb; + preliminary.reset(initialHeadroomDb); + reliable.reset(initialHeadroomDb); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/SpeechLevelEstimator.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/SpeechLevelEstimator.java new file mode 100644 index 0000000..5c5b4c8 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/agc2/SpeechLevelEstimator.java @@ -0,0 +1,106 @@ +package eu.lixko.ts3j.client.audio.processing.agc2; + +import static eu.lixko.ts3j.client.audio.processing.agc2.Agc2Common.FRAME_DURATION_MS; +import static eu.lixko.ts3j.client.audio.processing.agc2.Agc2Common.LEVEL_ESTIMATOR_LEAK_FACTOR; +import static eu.lixko.ts3j.client.audio.processing.agc2.Agc2Common.LEVEL_ESTIMATOR_TIME_TO_CONFIDENCE_MS; +import static eu.lixko.ts3j.client.audio.processing.agc2.Agc2Common.SATURATION_PROTECTOR_INITIAL_HEADROOM_DB; +import static eu.lixko.ts3j.client.audio.processing.agc2.Agc2Common.VAD_CONFIDENCE_THRESHOLD; + +/** + * Estimates the speech RMS level, from {@code agc2/speech_level_estimator.cc}: a + * speech-probability-weighted average over confidently voiced frames, which only takes + * effect after a run of adjacent speech frames so short noises don't move it. + */ +final class SpeechLevelEstimator { + + /** A level estimate kept as a weighted ratio, and the time left until it is trusted. */ + private static final class State { + int timeToConfidenceMs; + float numerator; + float denominator; + + void copyFrom(State other) { + timeToConfidenceMs = other.timeToConfidenceMs; + numerator = other.numerator; + denominator = other.denominator; + } + } + + private final float initialSpeechLevelDbfs; + private final int adjacentSpeechFramesThreshold; + private final State preliminary = new State(); + private final State reliable = new State(); + private float levelDbfs; + private boolean confident; + private int numAdjacentSpeechFrames; + + SpeechLevelEstimator(AdaptiveDigitalConfig config, int adjacentSpeechFramesThreshold) { + this.initialSpeechLevelDbfs = clamp(-SATURATION_PROTECTOR_INITIAL_HEADROOM_DB + - config.initialGainDb() - config.headroomDb()); + this.adjacentSpeechFramesThreshold = adjacentSpeechFramesThreshold; + reset(); + } + + float levelDbfs() { + return levelDbfs; + } + + boolean isConfident() { + return confident; + } + + void update(float rmsDbfs, float peakDbfs, float speechProbability) { + if (speechProbability < VAD_CONFIDENCE_THRESHOLD) { + // Not a speech frame: commit or roll back the preliminary estimate. + if (adjacentSpeechFramesThreshold > 1) { + if (numAdjacentSpeechFrames >= adjacentSpeechFramesThreshold) { + reliable.copyFrom(preliminary); + } else if (numAdjacentSpeechFrames > 0) { + preliminary.copyFrom(reliable); + } + } + numAdjacentSpeechFrames = 0; + } else { + numAdjacentSpeechFrames++; + final boolean bufferIsFull = preliminary.timeToConfidenceMs == 0; + if (!bufferIsFull) { + preliminary.timeToConfidenceMs -= FRAME_DURATION_MS; + } + final float leakFactor = bufferIsFull ? LEVEL_ESTIMATOR_LEAK_FACTOR : 1.0f; + preliminary.numerator = preliminary.numerator * leakFactor + rmsDbfs * speechProbability; + preliminary.denominator = preliminary.denominator * leakFactor + speechProbability; + final float level = preliminary.numerator / preliminary.denominator; + if (numAdjacentSpeechFrames >= adjacentSpeechFramesThreshold) { + levelDbfs = clamp(level); + } + } + updateIsConfident(); + } + + private void updateIsConfident() { + if (adjacentSpeechFramesThreshold == 1) { + confident = preliminary.timeToConfidenceMs == 0; + return; + } + confident = reliable.timeToConfidenceMs == 0 + || (numAdjacentSpeechFrames >= adjacentSpeechFramesThreshold + && preliminary.timeToConfidenceMs == 0); + } + + void reset() { + resetState(preliminary); + resetState(reliable); + levelDbfs = initialSpeechLevelDbfs; + numAdjacentSpeechFrames = 0; + } + + private void resetState(State state) { + state.timeToConfidenceMs = (int) LEVEL_ESTIMATOR_TIME_TO_CONFIDENCE_MS; + state.numerator = initialSpeechLevelDbfs; + state.denominator = 1.0f; + } + + private static float clamp(float levelDbfs) { + return Math.max(-90.0f, Math.min(30.0f, levelDbfs)); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/FastMath.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/FastMath.java new file mode 100644 index 0000000..54a46b4 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/FastMath.java @@ -0,0 +1,49 @@ +package eu.lixko.ts3j.client.audio.processing.ns; + +/** + * The noise suppressor's approximate log/exp, ported from {@code ns/fast_math.cc}. They are + * deliberately inexact (the log reads the float's exponent bits), and the suppressor's + * statistics were tuned with these errors in place, so they are kept as they are. + */ +final class FastMath { + + private static final float LOG_OF_2 = 0.69314718056f; + private static final float LOG10_OF_E = 0.4342944819f; + + private FastMath() { + } + + /** Reads the float's bits as an integer: the exponent lands in the top, scaled. */ + private static float fastLog2(float in) { + float out = Float.floatToRawIntBits(in); + out *= 1.1920929e-7f; // 1/2^23 + out -= 126.942695f; // exponent bias + return out; + } + + static float sqrt(float f) { + return (float) Math.sqrt(f); + } + + static float pow2(float p) { + return (float) Math.pow(2.0f, p); + } + + static float pow(float x, float p) { + return pow2(p * fastLog2(x)); + } + + static float log(float x) { + return fastLog2(x) * LOG_OF_2; + } + + static void log(float[] x, float[] y) { + for (int k = 0; k < x.length; k++) { + y[k] = log(x[k]); + } + } + + static float exp(float x) { + return pow(10.f, x * LOG10_OF_E); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/NoiseEstimator.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/NoiseEstimator.java new file mode 100644 index 0000000..30278f7 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/NoiseEstimator.java @@ -0,0 +1,145 @@ +package eu.lixko.ts3j.client.audio.processing.ns; + +import static eu.lixko.ts3j.client.audio.processing.ns.NsCommon.FFT_SIZE_BY_2_PLUS_1; +import static eu.lixko.ts3j.client.audio.processing.ns.NsCommon.SHORT_STARTUP_PHASE_BLOCKS; + +/** + * The noise spectrum, from {@code ns/noise_estimator.cc}: a quantile estimate, blended during + * the first half second with a parametric white/pink model fitted to the input, then + * refined each block according to how likely each bin holds speech. + */ +final class NoiseEstimator { + + private static final int BINS = FFT_SIZE_BY_2_PLUS_1; + private static final int START_BAND = 5; + + /** Natural log of the bin index; the first five are unused. */ + private static final float[] LOG_TABLE = { + 0.f, 0.f, 0.f, 0.f, 0.f, 1.609438f, 1.791759f, + 1.945910f, 2.079442f, 2.197225f, 2.302585f, 2.397895f, 2.484907f, 2.564949f, + 2.639057f, 2.708050f, 2.772589f, 2.833213f, 2.890372f, 2.944439f, 2.995732f, + 3.044522f, 3.091043f, 3.135494f, 3.178054f, 3.218876f, 3.258097f, 3.295837f, + 3.332205f, 3.367296f, 3.401197f, 3.433987f, 3.465736f, 3.496507f, 3.526361f, + 3.555348f, 3.583519f, 3.610918f, 3.637586f, 3.663562f, 3.688879f, 3.713572f, + 3.737669f, 3.761200f, 3.784190f, 3.806663f, 3.828641f, 3.850147f, 3.871201f, + 3.891820f, 3.912023f, 3.931826f, 3.951244f, 3.970292f, 3.988984f, 4.007333f, + 4.025352f, 4.043051f, 4.060443f, 4.077538f, 4.094345f, 4.110874f, 4.127134f, + 4.143135f, 4.158883f, 4.174387f, 4.189655f, 4.204693f, 4.219508f, 4.234107f, + 4.248495f, 4.262680f, 4.276666f, 4.290460f, 4.304065f, 4.317488f, 4.330733f, + 4.343805f, 4.356709f, 4.369448f, 4.382027f, 4.394449f, 4.406719f, 4.418841f, + 4.430817f, 4.442651f, 4.454347f, 4.465908f, 4.477337f, 4.488636f, 4.499810f, + 4.510859f, 4.521789f, 4.532599f, 4.543295f, 4.553877f, 4.564348f, 4.574711f, + 4.584968f, 4.595119f, 4.605170f, 4.615121f, 4.624973f, 4.634729f, 4.644391f, + 4.653960f, 4.663439f, 4.672829f, 4.682131f, 4.691348f, 4.700480f, 4.709530f, + 4.718499f, 4.727388f, 4.736198f, 4.744932f, 4.753591f, 4.762174f, 4.770685f, + 4.779124f, 4.787492f, 4.795791f, 4.804021f, 4.812184f, 4.820282f, 4.828314f, + 4.836282f, 4.844187f, 4.852030f}; + + private final SuppressionLevel params; + private final QuantileNoiseEstimator quantileNoiseEstimator = new QuantileNoiseEstimator(); + + private float whiteNoiseLevel; + private float pinkNoiseNumerator; + private float pinkNoiseExp; + final float[] prevNoiseSpectrum = new float[BINS]; + final float[] conservativeNoiseSpectrum = new float[BINS]; + final float[] parametricNoiseSpectrum = new float[BINS]; + final float[] noiseSpectrum = new float[BINS]; + + NoiseEstimator(SuppressionLevel params) { + this.params = params; + } + + void prepareAnalysis() { + System.arraycopy(noiseSpectrum, 0, prevNoiseSpectrum, 0, BINS); + } + + /** First-stage estimate for this block, before the speech probability is known. */ + void preUpdate(int numAnalyzedFrames, float[] signalSpectrum, float signalSpectralSum) { + quantileNoiseEstimator.estimate(signalSpectrum, noiseSpectrum); + if (numAnalyzedFrames >= SHORT_STARTUP_PHASE_BLOCKS) return; + + // Fit white and pink noise models to the spectrum while the quantiles settle. + float sumLogILogMagn = 0.f; + float sumLogI = 0.f; + float sumLogISquare = 0.f; + float sumLogMagn = 0.f; + for (int i = START_BAND; i < BINS; i++) { + float logI = LOG_TABLE[i]; + sumLogI += logI; + sumLogISquare += logI * logI; + float logSignal = FastMath.log(signalSpectrum[i]); + sumLogMagn += logSignal; + sumLogILogMagn += logI * logSignal; + } + + final float oneByBins = 1.f / BINS; + whiteNoiseLevel += signalSpectralSum * oneByBins * params.overSubtractionFactor; + + float denom = sumLogISquare * (BINS - START_BAND) - sumLogI * sumLogI; + float num = sumLogISquare * sumLogMagn - sumLogI * sumLogILogMagn; + float pinkNoiseAdjustment = num / denom; + pinkNoiseAdjustment = Math.max(pinkNoiseAdjustment, 0.f); + pinkNoiseNumerator += pinkNoiseAdjustment; + num = sumLogI * sumLogMagn - (BINS - START_BAND) * sumLogILogMagn; + pinkNoiseAdjustment = num / denom; + pinkNoiseAdjustment = Math.max(Math.min(pinkNoiseAdjustment, 1.f), 0.f); + pinkNoiseExp += pinkNoiseAdjustment; + + final float oneByNumAnalyzedFramesPlus1 = 1.f / (numAnalyzedFrames + 1.f); + float parametricExp = 0.f; + float parametricNum = 0.f; + if (pinkNoiseExp > 0.f) { + parametricNum = FastMath.exp(pinkNoiseNumerator * oneByNumAnalyzedFramesPlus1); + parametricNum *= numAnalyzedFrames + 1.f; + parametricExp = pinkNoiseExp * oneByNumAnalyzedFramesPlus1; + } + + for (int i = 0; i < BINS; i++) { + if (pinkNoiseExp == 0.f) { + parametricNoiseSpectrum[i] = whiteNoiseLevel; + } else { + float useBand = i < START_BAND ? START_BAND : i; + parametricNoiseSpectrum[i] = parametricNum / FastMath.pow(useBand, parametricExp); + } + } + + final float oneByShortStartupPhaseBlocks = 1.f / SHORT_STARTUP_PHASE_BLOCKS; + for (int i = 0; i < BINS; i++) { + noiseSpectrum[i] *= numAnalyzedFrames; + float tmp = parametricNoiseSpectrum[i] * (SHORT_STARTUP_PHASE_BLOCKS - numAnalyzedFrames); + noiseSpectrum[i] += tmp * oneByNumAnalyzedFramesPlus1; + noiseSpectrum[i] *= oneByShortStartupPhaseBlocks; + } + } + + /** Refines the estimate, updating slowly where speech is likely. */ + void postUpdate(float[] speechProbability, float[] signalSpectrum) { + final float noiseUpdate = 0.9f; + final float probRange = .2f; + float gamma = noiseUpdate; + for (int i = 0; i < BINS; i++) { + final float probSpeech = speechProbability[i]; + final float probNonSpeech = 1.f - probSpeech; + + float noiseUpdateTmp = gamma * prevNoiseSpectrum[i] + + (1.f - gamma) * (probNonSpeech * signalSpectrum[i] + probSpeech * prevNoiseSpectrum[i]); + + float gammaOld = gamma; + gamma = probSpeech > probRange ? .99f : noiseUpdate; + + if (probSpeech < probRange) { + conservativeNoiseSpectrum[i] += 0.05f * (signalSpectrum[i] - conservativeNoiseSpectrum[i]); + } + + if (gamma == gammaOld) { + noiseSpectrum[i] = noiseUpdateTmp; + } else { + noiseSpectrum[i] = gamma * prevNoiseSpectrum[i] + + (1.f - gamma) * (probNonSpeech * signalSpectrum[i] + probSpeech * prevNoiseSpectrum[i]); + // A downward update is always safe. + noiseSpectrum[i] = Math.min(noiseSpectrum[i], noiseUpdateTmp); + } + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/NoiseSuppressor.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/NoiseSuppressor.java new file mode 100644 index 0000000..fbd2457 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/NoiseSuppressor.java @@ -0,0 +1,320 @@ +package eu.lixko.ts3j.client.audio.processing.ns; + +import static eu.lixko.ts3j.client.audio.processing.ns.NsCommon.FFT_SIZE; +import static eu.lixko.ts3j.client.audio.processing.ns.NsCommon.FFT_SIZE_BY_2_PLUS_1; +import static eu.lixko.ts3j.client.audio.processing.ns.NsCommon.NS_FRAME_SIZE; +import static eu.lixko.ts3j.client.audio.processing.ns.NsCommon.OVERLAP_SIZE; + +import eu.lixko.ts3j.client.audio.Fft; + +/** + * WebRTC's noise suppressor ({@code ns/noise_suppressor.cc}), the module behind TS3's + * "Remove background noise", for one channel. + * + *

    It works on band-split audio in 10 ms frames, samples on the 16-bit scale: the + * lowest band (0–8 kHz at 16 kHz) is filtered per bin, and the upper bands, if + * any, are delayed to match and scaled by one gain derived from the top of the lowest band. + * As in APM, call {@link #analyze} and then {@link #process} on every frame. + */ +public final class NoiseSuppressor { + + private static final int BINS = FFT_SIZE_BY_2_PLUS_1; + + /** Rising half of the hybrid Hann/flat analysis and synthesis window. */ + private static final float[] BLOCKS_160W256_FIRST_HALF = { + 0.00000000f, 0.01636173f, 0.03271908f, 0.04906767f, 0.06540313f, + 0.08172107f, 0.09801714f, 0.11428696f, 0.13052619f, 0.14673047f, + 0.16289547f, 0.17901686f, 0.19509032f, 0.21111155f, 0.22707626f, + 0.24298018f, 0.25881905f, 0.27458862f, 0.29028468f, 0.30590302f, + 0.32143947f, 0.33688985f, 0.35225005f, 0.36751594f, 0.38268343f, + 0.39774847f, 0.41270703f, 0.42755509f, 0.44228869f, 0.45690388f, + 0.47139674f, 0.48576339f, 0.50000000f, 0.51410274f, 0.52806785f, + 0.54189158f, 0.55557023f, 0.56910015f, 0.58247770f, 0.59569930f, + 0.60876143f, 0.62166057f, 0.63439328f, 0.64695615f, 0.65934582f, + 0.67155895f, 0.68359230f, 0.69544264f, 0.70710678f, 0.71858162f, + 0.72986407f, 0.74095113f, 0.75183981f, 0.76252720f, 0.77301045f, + 0.78328675f, 0.79335334f, 0.80320753f, 0.81284668f, 0.82226822f, + 0.83146961f, 0.84044840f, 0.84920218f, 0.85772861f, 0.86602540f, + 0.87409034f, 0.88192126f, 0.88951608f, 0.89687274f, 0.90398929f, + 0.91086382f, 0.91749450f, 0.92387953f, 0.93001722f, 0.93590593f, + 0.94154407f, 0.94693013f, 0.95206268f, 0.95694034f, 0.96156180f, + 0.96592583f, 0.97003125f, 0.97387698f, 0.97746197f, 0.98078528f, + 0.98384601f, 0.98664333f, 0.98917651f, 0.99144486f, 0.99344778f, + 0.99518473f, 0.99665524f, 0.99785892f, 0.99879546f, 0.99946459f, + 0.99986614f}; + + private final int numBands; + private final SuppressionLevel params; + private int numAnalyzedFrames = -1; + + private final SpeechProbabilityEstimator speechProbabilityEstimator = new SpeechProbabilityEstimator(); + private final WienerFilter wienerFilter; + private final NoiseEstimator noiseEstimator; + private final float[] prevAnalysisSignalSpectrum = new float[BINS]; + private final float[] analyzeAnalysisMemory = new float[OVERLAP_SIZE]; + private final float[] processAnalysisMemory = new float[OVERLAP_SIZE]; + private final float[] processSynthesisMemory = new float[OVERLAP_SIZE]; + private final float[][] processDelayMemory; + + // Scratch. + private final float[] extendedFrame = new float[FFT_SIZE]; + private final float[] real = new float[FFT_SIZE]; + private final float[] imag = new float[FFT_SIZE]; + private final double[] fftRe = new double[FFT_SIZE]; + private final double[] fftIm = new double[FFT_SIZE]; + private final float[] signalSpectrum = new float[BINS]; + private final float[] priorSnr = new float[BINS]; + private final float[] postSnr = new float[BINS]; + private final float[] delayedFrame = new float[NS_FRAME_SIZE]; + + /** + * @param level how hard to cut + * @param numBands 1 for 16 kHz audio, 3 for 48 kHz split by the three-band filter bank + */ + public NoiseSuppressor(SuppressionLevel level, int numBands) { + this.params = level; + this.numBands = numBands; + this.wienerFilter = new WienerFilter(level); + this.noiseEstimator = new NoiseEstimator(level); + java.util.Arrays.fill(prevAnalysisSignalSpectrum, 1.f); + this.processDelayMemory = new float[Math.max(0, numBands - 1)][OVERLAP_SIZE]; + } + + public SuppressionLevel level() { + return params; + } + + /** Updates the noise and speech statistics from the lowest band of this frame. */ + public void analyze(float[] band0) { + noiseEstimator.prepareAnalysis(); + + // Leave the statistics alone on digital silence: learning from zeros would make any + // later signal look like speech and nothing would be suppressed for a long while. + if (energyOfExtendedFrame(band0, analyzeAnalysisMemory) <= 0.f) { + return; + } + + if (++numAnalyzedFrames < 0) { + numAnalyzedFrames = 0; + } + + formExtendedFrame(band0, analyzeAnalysisMemory, extendedFrame); + applyFilterBankWindow(extendedFrame); + fft(extendedFrame, real, imag); + computeMagnitudeSpectrum(real, imag, signalSpectrum); + + float signalEnergy = 0.f; + for (int i = 0; i < BINS; i++) { + signalEnergy += real[i] * real[i] + imag[i] * imag[i]; + } + signalEnergy /= BINS; + + float signalSpectralSum = 0.f; + for (int i = 0; i < BINS; i++) { + signalSpectralSum += signalSpectrum[i]; + } + + noiseEstimator.preUpdate(numAnalyzedFrames, signalSpectrum, signalSpectralSum); + computeSnr(wienerFilter.filter, prevAnalysisSignalSpectrum, signalSpectrum, + noiseEstimator.prevNoiseSpectrum, noiseEstimator.noiseSpectrum, priorSnr, postSnr); + speechProbabilityEstimator.update(numAnalyzedFrames, priorSnr, postSnr, + noiseEstimator.conservativeNoiseSpectrum, signalSpectrum, signalSpectralSum, signalEnergy); + noiseEstimator.postUpdate(speechProbabilityEstimator.speechProbability, signalSpectrum); + + System.arraycopy(signalSpectrum, 0, prevAnalysisSignalSpectrum, 0, BINS); + } + + /** + * Suppresses noise in place. {@code bands[0]} is the lowest band; any further bands are + * the upper ones. Each holds {@value NsCommon#NS_FRAME_SIZE} samples on the 16-bit scale. + */ + public void process(float[][] bands) { + float[] band0 = bands[0]; + formExtendedFrame(band0, processAnalysisMemory, extendedFrame); + applyFilterBankWindow(extendedFrame); + float energyBeforeFiltering = energyOfExtendedFrame(extendedFrame); + + fft(extendedFrame, real, imag); + computeMagnitudeSpectrum(real, imag, signalSpectrum); + + wienerFilter.update(numAnalyzedFrames, noiseEstimator.noiseSpectrum, noiseEstimator.prevNoiseSpectrum, + noiseEstimator.parametricNoiseSpectrum, signalSpectrum); + + float upperBandGain = 1.f; + if (numBands > 1) { + upperBandGain = computeUpperBandsGain(params.minimumAttenuatingGain, wienerFilter.filter, + speechProbabilityEstimator.speechProbability, prevAnalysisSignalSpectrum, signalSpectrum); + } + + float[] filter = wienerFilter.filter; + for (int i = 0; i < BINS; i++) { + real[i] *= filter[i]; + imag[i] *= filter[i]; + } + ifft(real, imag, extendedFrame); + + float energyAfterFiltering = energyOfExtendedFrame(extendedFrame); + applyFilterBankWindow(extendedFrame); + + float gainAdjustment = wienerFilter.computeOverallScalingFactor(numAnalyzedFrames, + speechProbabilityEstimator.priorSpeechProbability, energyBeforeFiltering, energyAfterFiltering); + for (int i = 0; i < FFT_SIZE; i++) { + extendedFrame[i] = gainAdjustment * extendedFrame[i]; + } + + overlapAndAdd(extendedFrame, processSynthesisMemory, band0); + + for (int b = 1; b < numBands; b++) { + // Delay the upper bands to line up with the lowest band's filter bank. + float[] band = bands[b]; + delaySignal(band, processDelayMemory[b - 1], delayedFrame); + for (int j = 0; j < NS_FRAME_SIZE; j++) { + band[j] = upperBandGain * delayedFrame[j]; + } + } + + for (int b = 0; b < numBands; b++) { + float[] band = bands[b]; + for (int j = 0; j < NS_FRAME_SIZE; j++) { + band[j] = Math.min(Math.max(band[j], -32768.f), 32767.f); + } + } + } + + private static void applyFilterBankWindow(float[] x) { + for (int i = 0; i < 96; i++) { + x[i] = BLOCKS_160W256_FIRST_HALF[i] * x[i]; + } + for (int i = 161, k = 95; i < FFT_SIZE; i++, k--) { + x[i] = BLOCKS_160W256_FIRST_HALF[k] * x[i]; + } + } + + /** Prepends the kept tail of the previous frames, and keeps this frame's tail. */ + private static void formExtendedFrame(float[] frame, float[] oldData, float[] extended) { + System.arraycopy(oldData, 0, extended, 0, OVERLAP_SIZE); + System.arraycopy(frame, 0, extended, OVERLAP_SIZE, NS_FRAME_SIZE); + System.arraycopy(extended, FFT_SIZE - OVERLAP_SIZE, oldData, 0, OVERLAP_SIZE); + } + + private static void overlapAndAdd(float[] extended, float[] overlapMemory, float[] output) { + for (int i = 0; i < OVERLAP_SIZE; i++) { + output[i] = overlapMemory[i] + extended[i]; + } + System.arraycopy(extended, OVERLAP_SIZE, output, OVERLAP_SIZE, NS_FRAME_SIZE - OVERLAP_SIZE); + System.arraycopy(extended, NS_FRAME_SIZE, overlapMemory, 0, OVERLAP_SIZE); + } + + private static void delaySignal(float[] frame, float[] delayBuffer, float[] delayed) { + final int samplesFromFrame = NS_FRAME_SIZE - OVERLAP_SIZE; + System.arraycopy(delayBuffer, 0, delayed, 0, OVERLAP_SIZE); + System.arraycopy(frame, 0, delayed, OVERLAP_SIZE, samplesFromFrame); + System.arraycopy(frame, samplesFromFrame, delayBuffer, 0, OVERLAP_SIZE); + } + + private static float energyOfExtendedFrame(float[] x) { + float energy = 0.f; + for (float v : x) { + energy += v * v; + } + return energy; + } + + private static float energyOfExtendedFrame(float[] frame, float[] oldData) { + float energy = 0.f; + for (float v : oldData) { + energy += v * v; + } + for (int i = 0; i < NS_FRAME_SIZE; i++) { + energy += frame[i] * frame[i]; + } + return energy; + } + + private static void computeMagnitudeSpectrum(float[] real, float[] imag, float[] spectrum) { + spectrum[0] = Math.abs(real[0]) + 1.f; + spectrum[BINS - 1] = Math.abs(real[BINS - 1]) + 1.f; + for (int i = 1; i < BINS - 1; i++) { + spectrum[i] = FastMath.sqrt(real[i] * real[i] + imag[i] * imag[i]) + 1.f; + } + } + + private static void computeSnr(float[] filter, float[] prevSignalSpectrum, float[] signalSpectrum, + float[] prevNoiseSpectrum, float[] noiseSpectrum, + float[] priorSnr, float[] postSnr) { + for (int i = 0; i < BINS; i++) { + float prevEstimate = prevSignalSpectrum[i] / (prevNoiseSpectrum[i] + 0.0001f) * filter[i]; + if (signalSpectrum[i] > noiseSpectrum[i]) { + postSnr[i] = signalSpectrum[i] / (noiseSpectrum[i] + 0.0001f) - 1.f; + } else { + postSnr[i] = 0.f; + } + // Decision-directed estimate of the prior SNR. + priorSnr[i] = 0.98f * prevEstimate + (1.f - 0.98f) * postSnr[i]; + } + } + + /** One gain for the upper bands, from speech probability and gain at the top of band 0. */ + private static float computeUpperBandsGain(float minimumAttenuatingGain, float[] filter, + float[] speechProbability, + float[] prevAnalysisSignalSpectrum, float[] signalSpectrum) { + final int numAvgBins = 32; + final float oneByNumAvgBins = 1.f / numAvgBins; + float avgProbSpeech = 0.f; + float avgFilterGain = 0.f; + for (int i = BINS - numAvgBins - 1; i < BINS - 1; i++) { + avgProbSpeech += speechProbability[i]; + avgFilterGain += filter[i]; + } + avgProbSpeech = avgProbSpeech * oneByNumAvgBins; + avgFilterGain = avgFilterGain * oneByNumAvgBins; + + // Speech removed between analysis and processing (by an AEC) should not count. + float sumAnalysisSpectrum = 0.f; + float sumProcessingSpectrum = 0.f; + for (int i = 0; i < BINS; i++) { + sumAnalysisSpectrum += prevAnalysisSignalSpectrum[i]; + sumProcessingSpectrum += signalSpectrum[i]; + } + avgProbSpeech *= sumProcessingSpectrum / sumAnalysisSpectrum; + + float gain = 0.5f * (1.f + (float) Math.tanh(2.f * avgProbSpeech - 1.f)); + if (avgProbSpeech >= 0.5f) { + gain = 0.25f * gain + 0.75f * avgFilterGain; + } else { + gain = 0.5f * gain + 0.5f * avgFilterGain; + } + return Math.min(Math.max(gain, minimumAttenuatingGain), 1.f); + } + + private void fft(float[] timeData, float[] re, float[] im) { + for (int i = 0; i < FFT_SIZE; i++) { + fftRe[i] = timeData[i]; + fftIm[i] = 0; + } + Fft.forward(fftRe, fftIm); + for (int i = 0; i < BINS; i++) { + re[i] = (float) fftRe[i]; + im[i] = (float) fftIm[i]; + } + im[0] = 0; + im[BINS - 1] = 0; + } + + private void ifft(float[] re, float[] im, float[] timeData) { + fftRe[0] = re[0]; + fftIm[0] = 0; + fftRe[BINS - 1] = re[BINS - 1]; + fftIm[BINS - 1] = 0; + for (int i = 1; i < BINS - 1; i++) { + fftRe[i] = re[i]; + fftIm[i] = im[i]; + fftRe[FFT_SIZE - i] = re[i]; + fftIm[FFT_SIZE - i] = -im[i]; + } + Fft.inverse(fftRe, fftIm); + for (int i = 0; i < FFT_SIZE; i++) { + timeData[i] = (float) fftRe[i]; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/NsCommon.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/NsCommon.java new file mode 100644 index 0000000..2d44704 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/NsCommon.java @@ -0,0 +1,29 @@ +package eu.lixko.ts3j.client.audio.processing.ns; + +/** + * Sizes and constants of WebRTC's noise suppressor, mirroring {@code ns/ns_common.h}. + * + *

    The suppressor works on the lowest 0–8 kHz band at 16 kHz: 10 ms + * frames of 160 samples, analysed with a 256-point FFT over a 96-sample overlap. + */ +final class NsCommon { + + static final int FFT_SIZE = 256; + static final int FFT_SIZE_BY_2_PLUS_1 = FFT_SIZE / 2 + 1; + static final int NS_FRAME_SIZE = 160; + static final int OVERLAP_SIZE = FFT_SIZE - NS_FRAME_SIZE; + + static final int SHORT_STARTUP_PHASE_BLOCKS = 50; + static final int LONG_STARTUP_PHASE_BLOCKS = 200; + static final int FEATURE_UPDATE_WINDOW_SIZE = 500; + + static final float LTR_FEATURE_THR = 0.5f; + static final float BIN_SIZE_LRT = 0.1f; + static final float BIN_SIZE_SPEC_FLAT = 0.05f; + static final float BIN_SIZE_SPEC_DIFF = 0.1f; + + static final int HISTOGRAM_SIZE = 1000; + + private NsCommon() { + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/QuantileNoiseEstimator.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/QuantileNoiseEstimator.java new file mode 100644 index 0000000..e3adac4 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/QuantileNoiseEstimator.java @@ -0,0 +1,79 @@ +package eu.lixko.ts3j.client.audio.processing.ns; + +import static eu.lixko.ts3j.client.audio.processing.ns.NsCommon.FFT_SIZE_BY_2_PLUS_1; +import static eu.lixko.ts3j.client.audio.processing.ns.NsCommon.LONG_STARTUP_PHASE_BLOCKS; + +import java.util.Arrays; + +/** + * Tracks a low quantile of each bin's log spectrum as the noise floor, from + * {@code ns/quantile_noise_estimator.cc}. Three estimates run staggered so that one of + * them completes a 200-block window every 67 blocks. + */ +final class QuantileNoiseEstimator { + + private static final int SIMULT = 3; + private static final int BINS = FFT_SIZE_BY_2_PLUS_1; + + private final float[] density = new float[SIMULT * BINS]; + private final float[] logQuantile = new float[SIMULT * BINS]; + private final float[] quantile = new float[BINS]; + private final int[] counter = new int[SIMULT]; + private int numUpdates = 1; + + private final float[] logSpectrum = new float[BINS]; + + QuantileNoiseEstimator() { + Arrays.fill(density, 0.3f); + Arrays.fill(logQuantile, 8.f); + final float oneBySimult = 1.f / SIMULT; + for (int i = 0; i < SIMULT; i++) { + counter[i] = (int) Math.floor(LONG_STARTUP_PHASE_BLOCKS * (i + 1.f) * oneBySimult); + } + } + + void estimate(float[] signalSpectrum, float[] noiseSpectrum) { + FastMath.log(signalSpectrum, logSpectrum); + + int quantileIndexToReturn = -1; + for (int s = 0, k = 0; s < SIMULT; s++, k += BINS) { + final float oneByCounterPlus1 = 1.f / (counter[s] + 1.f); + for (int i = 0, j = k; i < BINS; i++, j++) { + final float delta = density[j] > 1.f ? 40.f / density[j] : 40.f; + final float multiplier = delta * oneByCounterPlus1; + if (logSpectrum[i] > logQuantile[j]) { + logQuantile[j] += 0.25f * multiplier; + } else { + logQuantile[j] -= 0.75f * multiplier; + } + + final float width = 0.01f; + final float oneByWidthPlus2 = 1.f / (2.f * width); + if (Math.abs(logSpectrum[i] - logQuantile[j]) < width) { + density[j] = (counter[s] * density[j] + oneByWidthPlus2) * oneByCounterPlus1; + } + } + + if (counter[s] >= LONG_STARTUP_PHASE_BLOCKS) { + counter[s] = 0; + if (numUpdates >= LONG_STARTUP_PHASE_BLOCKS) { + quantileIndexToReturn = k; + } + } + counter[s]++; + } + + // During startup, follow the last estimate so the noise is non-zero from the start. + if (numUpdates < LONG_STARTUP_PHASE_BLOCKS) { + quantileIndexToReturn = BINS * (SIMULT - 1); + numUpdates++; + } + + if (quantileIndexToReturn >= 0) { + for (int i = 0; i < BINS; i++) { + quantile[i] = FastMath.exp(logQuantile[quantileIndexToReturn + i]); + } + } + System.arraycopy(quantile, 0, noiseSpectrum, 0, BINS); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/SignalModelEstimator.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/SignalModelEstimator.java new file mode 100644 index 0000000..97598d4 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/SignalModelEstimator.java @@ -0,0 +1,255 @@ +package eu.lixko.ts3j.client.audio.processing.ns; + +import static eu.lixko.ts3j.client.audio.processing.ns.NsCommon.BIN_SIZE_LRT; +import static eu.lixko.ts3j.client.audio.processing.ns.NsCommon.BIN_SIZE_SPEC_DIFF; +import static eu.lixko.ts3j.client.audio.processing.ns.NsCommon.BIN_SIZE_SPEC_FLAT; +import static eu.lixko.ts3j.client.audio.processing.ns.NsCommon.FEATURE_UPDATE_WINDOW_SIZE; +import static eu.lixko.ts3j.client.audio.processing.ns.NsCommon.FFT_SIZE_BY_2_PLUS_1; +import static eu.lixko.ts3j.client.audio.processing.ns.NsCommon.HISTOGRAM_SIZE; +import static eu.lixko.ts3j.client.audio.processing.ns.NsCommon.LTR_FEATURE_THR; + +import java.util.Arrays; + +/** + * The three speech features the suppressor weighs (likelihood ratio, spectral flatness and + * difference from the noise template) and the prior model that decides how to weigh them, + * re-fitted from feature histograms every 500 blocks. Ports {@code signal_model_estimator.cc}, + * {@code prior_signal_model_estimator.cc}, {@code histograms.cc} and the two model structs. + */ +final class SignalModelEstimator { + + private static final int BINS = FFT_SIZE_BY_2_PLUS_1; + private static final float ONE_BY_BINS = 1.f / BINS; + + // SignalModel. + float lrt = LTR_FEATURE_THR; + float spectralFlatness = 0.5f; + float spectralDiff = 0.5f; + final float[] avgLogLrt = new float[BINS]; + + // PriorSignalModel. + float priorLrt = LTR_FEATURE_THR; + float flatnessThreshold = .5f; + float templateDiffThreshold = .5f; + float lrtWeighting = 1.f; + float flatnessWeighting = 0.f; + float differenceWeighting = 0.f; + + private final int[] lrtHistogram = new int[HISTOGRAM_SIZE]; + private final int[] flatnessHistogram = new int[HISTOGRAM_SIZE]; + private final int[] diffHistogram = new int[HISTOGRAM_SIZE]; + + private float diffNormalization; + private float signalEnergySum; + private int histogramAnalysisCounter = 500; + + SignalModelEstimator() { + Arrays.fill(avgLogLrt, LTR_FEATURE_THR); + } + + void adjustNormalization(int numAnalyzedFrames, float signalEnergy) { + diffNormalization *= numAnalyzedFrames; + diffNormalization += signalEnergy; + diffNormalization /= (numAnalyzedFrames + 1); + } + + void update(float[] priorSnr, float[] postSnr, float[] conservativeNoiseSpectrum, + float[] signalSpectrum, float signalSpectralSum, float signalEnergy) { + updateSpectralFlatness(signalSpectrum, signalSpectralSum); + + float diff = computeSpectralDiff(conservativeNoiseSpectrum, signalSpectrum, signalSpectralSum); + spectralDiff += 0.3f * (diff - spectralDiff); + + signalEnergySum += signalEnergy; + + if (--histogramAnalysisCounter > 0) { + updateHistograms(); + } else { + updatePriorModel(); + Arrays.fill(lrtHistogram, 0); + Arrays.fill(flatnessHistogram, 0); + Arrays.fill(diffHistogram, 0); + histogramAnalysisCounter = FEATURE_UPDATE_WINDOW_SIZE; + + signalEnergySum = signalEnergySum / FEATURE_UPDATE_WINDOW_SIZE; + diffNormalization = 0.5f * (signalEnergySum + diffNormalization); + signalEnergySum = 0.f; + } + + updateSpectralLrt(priorSnr, postSnr); + } + + private float computeSpectralDiff(float[] conservativeNoiseSpectrum, float[] signalSpectrum, + float signalSpectralSum) { + float noiseAverage = 0.f; + for (int i = 0; i < BINS; i++) { + noiseAverage += conservativeNoiseSpectrum[i]; + } + noiseAverage = noiseAverage * ONE_BY_BINS; + float signalAverage = signalSpectralSum * ONE_BY_BINS; + + float covariance = 0.f; + float noiseVariance = 0.f; + float signalVariance = 0.f; + for (int i = 0; i < BINS; i++) { + float signalDiff = signalSpectrum[i] - signalAverage; + float noiseDiff = conservativeNoiseSpectrum[i] - noiseAverage; + covariance += signalDiff * noiseDiff; + noiseVariance += noiseDiff * noiseDiff; + signalVariance += signalDiff * signalDiff; + } + covariance *= ONE_BY_BINS; + noiseVariance *= ONE_BY_BINS; + signalVariance *= ONE_BY_BINS; + + float diff = signalVariance - (covariance * covariance) / (noiseVariance + 0.0001f); + return diff / (diffNormalization + 0.0001f); + } + + private void updateSpectralFlatness(float[] signalSpectrum, float signalSpectralSum) { + final float averaging = 0.3f; + for (int i = 1; i < BINS; i++) { + if (signalSpectrum[i] == 0.f) { + spectralFlatness -= averaging * spectralFlatness; + return; + } + } + float num = 0.f; + for (int i = 1; i < BINS; i++) { + num += FastMath.log(signalSpectrum[i]); + } + float denom = signalSpectralSum - signalSpectrum[0]; + denom = denom * ONE_BY_BINS; + num = num * ONE_BY_BINS; + float tmp = FastMath.exp(num) / denom; + spectralFlatness += averaging * (tmp - spectralFlatness); + } + + private void updateSpectralLrt(float[] priorSnr, float[] postSnr) { + for (int i = 0; i < BINS; i++) { + float tmp1 = 1.f + 2.f * priorSnr[i]; + float tmp2 = 2.f * priorSnr[i] / (tmp1 + 0.0001f); + float besselTmp = (postSnr[i] + 1.f) * tmp2; + avgLogLrt[i] += .5f * (besselTmp - FastMath.log(tmp1) - avgLogLrt[i]); + } + float sum = 0.f; + for (int i = 0; i < BINS; i++) { + sum += avgLogLrt[i]; + } + lrt = sum * ONE_BY_BINS; + } + + private void updateHistograms() { + final float oneByBinSizeLrt = 1.f / BIN_SIZE_LRT; + if (lrt < HISTOGRAM_SIZE * BIN_SIZE_LRT && lrt >= 0.f) { + lrtHistogram[(int) (oneByBinSizeLrt * lrt)]++; + } + final float oneByBinSizeSpecFlat = 1.f / BIN_SIZE_SPEC_FLAT; + if (spectralFlatness < HISTOGRAM_SIZE * BIN_SIZE_SPEC_FLAT && spectralFlatness >= 0.f) { + flatnessHistogram[(int) (spectralFlatness * oneByBinSizeSpecFlat)]++; + } + final float oneByBinSizeSpecDiff = 1.f / BIN_SIZE_SPEC_DIFF; + if (spectralDiff < HISTOGRAM_SIZE * BIN_SIZE_SPEC_DIFF && spectralDiff >= 0.f) { + diffHistogram[(int) (spectralDiff * oneByBinSizeSpecDiff)]++; + } + } + + private void updatePriorModel() { + boolean lowLrtFluctuations = updatePriorLrt(); + + float[] flat = firstOfTwoLargestPeaks(BIN_SIZE_SPEC_FLAT, flatnessHistogram); + float flatPeakPosition = flat[0]; + int flatPeakWeight = (int) flat[1]; + float[] diff = firstOfTwoLargestPeaks(BIN_SIZE_SPEC_DIFF, diffHistogram); + float diffPeakPosition = diff[0]; + int diffPeakWeight = (int) diff[1]; + + // Only use the features whose histograms show a clear peak. + final int useSpecFlat = flatPeakWeight < 0.3f * 500 || flatPeakPosition < 0.6f ? 0 : 1; + final int useSpecDiff = diffPeakWeight < 0.3f * 500 || lowLrtFluctuations ? 0 : 1; + + templateDiffThreshold = 1.2f * diffPeakPosition; + templateDiffThreshold = Math.min(1.f, Math.max(0.16f, templateDiffThreshold)); + + float oneByFeatureSum = 1.f / (1.f + useSpecFlat + useSpecDiff); + lrtWeighting = oneByFeatureSum; + + if (useSpecFlat == 1) { + flatnessThreshold = 0.9f * flatPeakPosition; + flatnessThreshold = Math.min(.95f, Math.max(0.1f, flatnessThreshold)); + flatnessWeighting = oneByFeatureSum; + } else { + flatnessWeighting = 0.f; + } + + differenceWeighting = useSpecDiff == 1 ? oneByFeatureSum : 0.f; + } + + /** Re-fits the prior LRT; returns whether the LRT barely fluctuates. */ + private boolean updatePriorLrt() { + float average = 0.f; + float averageCompl = 0.f; + float averageSquared = 0.f; + int count = 0; + for (int i = 0; i < 10; i++) { + float binMid = (i + 0.5f) * BIN_SIZE_LRT; + average += lrtHistogram[i] * binMid; + count += lrtHistogram[i]; + } + if (count > 0) { + average = average / count; + } + for (int i = 0; i < HISTOGRAM_SIZE; i++) { + float binMid = (i + 0.5f) * BIN_SIZE_LRT; + averageSquared += lrtHistogram[i] * binMid * binMid; + averageCompl += lrtHistogram[i] * binMid; + } + final float oneByWindow = 1.f / FEATURE_UPDATE_WINDOW_SIZE; + averageSquared = averageSquared * oneByWindow; + averageCompl = averageCompl * oneByWindow; + + boolean lowLrtFluctuations = averageSquared - average * averageCompl < 0.05f; + final float maxLrt = 1.f; + final float minLrt = .2f; + if (lowLrtFluctuations) { + priorLrt = maxLrt; + } else { + priorLrt = Math.min(maxLrt, Math.max(minLrt, 1.2f * average)); + } + return lowLrtFluctuations; + } + + /** Returns {position, weight} of the larger peak, merged with the runner-up when adjacent. */ + private static float[] firstOfTwoLargestPeaks(float binSize, int[] histogram) { + int peakValue = 0; + int secondaryPeakValue = 0; + float peakPosition = 0.f; + float secondaryPeakPosition = 0.f; + int peakWeight = 0; + int secondaryPeakWeight = 0; + + for (int i = 0; i < HISTOGRAM_SIZE; i++) { + final float binMid = (i + 0.5f) * binSize; + if (histogram[i] > peakValue) { + secondaryPeakValue = peakValue; + secondaryPeakWeight = peakWeight; + secondaryPeakPosition = peakPosition; + + peakValue = histogram[i]; + peakWeight = histogram[i]; + peakPosition = binMid; + } else if (histogram[i] > secondaryPeakValue) { + secondaryPeakValue = histogram[i]; + secondaryPeakWeight = histogram[i]; + secondaryPeakPosition = binMid; + } + } + + if (Math.abs(secondaryPeakPosition - peakPosition) < 2 * binSize + && secondaryPeakWeight > 0.5f * peakWeight) { + peakWeight += secondaryPeakWeight; + peakPosition = 0.5f * (peakPosition + secondaryPeakPosition); + } + return new float[]{peakPosition, peakWeight}; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/SpeechProbabilityEstimator.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/SpeechProbabilityEstimator.java new file mode 100644 index 0000000..512595d --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/SpeechProbabilityEstimator.java @@ -0,0 +1,53 @@ +package eu.lixko.ts3j.client.audio.processing.ns; + +import static eu.lixko.ts3j.client.audio.processing.ns.NsCommon.FFT_SIZE_BY_2_PLUS_1; +import static eu.lixko.ts3j.client.audio.processing.ns.NsCommon.LONG_STARTUP_PHASE_BLOCKS; + +/** + * Per-bin speech presence probability, from {@code ns/speech_probability_estimator.cc}: the + * features are mapped through sigmoids around the prior model's thresholds into a prior + * speech probability, which is then combined with each bin's likelihood ratio. + */ +final class SpeechProbabilityEstimator { + + private static final int BINS = FFT_SIZE_BY_2_PLUS_1; + private static final float WIDTH_PRIOR_0 = 4.f; + private static final float WIDTH_PRIOR_1 = 2.f * WIDTH_PRIOR_0; + + private final SignalModelEstimator model = new SignalModelEstimator(); + float priorSpeechProbability = .5f; + final float[] speechProbability = new float[BINS]; + + void update(int numAnalyzedFrames, float[] priorSnr, float[] postSnr, float[] conservativeNoiseSpectrum, + float[] signalSpectrum, float signalSpectralSum, float signalEnergy) { + if (numAnalyzedFrames < LONG_STARTUP_PHASE_BLOCKS) { + model.adjustNormalization(numAnalyzedFrames, signalEnergy); + } + model.update(priorSnr, postSnr, conservativeNoiseSpectrum, signalSpectrum, signalSpectralSum, + signalEnergy); + + float widthPrior = model.lrt < model.priorLrt ? WIDTH_PRIOR_1 : WIDTH_PRIOR_0; + float indicator0 = 0.5f * ((float) Math.tanh(widthPrior * (model.lrt - model.priorLrt)) + 1.f); + + widthPrior = model.spectralFlatness > model.flatnessThreshold ? WIDTH_PRIOR_1 : WIDTH_PRIOR_0; + float indicator1 = 0.5f * ((float) Math.tanh( + 1.f * widthPrior * (model.flatnessThreshold - model.spectralFlatness)) + 1.f); + + widthPrior = model.spectralDiff < model.templateDiffThreshold ? WIDTH_PRIOR_1 : WIDTH_PRIOR_0; + float indicator2 = 0.5f * ((float) Math.tanh( + widthPrior * (model.spectralDiff - model.templateDiffThreshold)) + 1.f); + + float indPrior = model.lrtWeighting * indicator0 + + model.flatnessWeighting * indicator1 + + model.differenceWeighting * indicator2; + + priorSpeechProbability += 0.1f * (indPrior - priorSpeechProbability); + priorSpeechProbability = Math.max(Math.min(priorSpeechProbability, 1.f), 0.01f); + + float gainPrior = (1.f - priorSpeechProbability) / (priorSpeechProbability + 0.0001f); + for (int i = 0; i < BINS; i++) { + float invLrt = FastMath.exp(-model.avgLogLrt[i]); + speechProbability[i] = 1.f / (1.f + gainPrior * invLrt); + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/SuppressionLevel.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/SuppressionLevel.java new file mode 100644 index 0000000..2e19e63 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/SuppressionLevel.java @@ -0,0 +1,30 @@ +package eu.lixko.ts3j.client.audio.processing.ns; + +/** + * How hard the noise suppressor cuts, from {@code ns/suppression_params.cc}. TS3's + * {@code denoiser_level} slider (0–3) picks one of these directly, in this order. + */ +public enum SuppressionLevel { + + DB_6(1.f, 0.5f, false), + DB_12(1.f, 0.25f, true), + DB_18(1.1f, 0.125f, true), + DB_21(1.25f, 0.09f, true); + + final float overSubtractionFactor; + final float minimumAttenuatingGain; + final boolean useAttenuationAdjustment; + + SuppressionLevel(float overSubtractionFactor, float minimumAttenuatingGain, + boolean useAttenuationAdjustment) { + this.overSubtractionFactor = overSubtractionFactor; + this.minimumAttenuatingGain = minimumAttenuatingGain; + this.useAttenuationAdjustment = useAttenuationAdjustment; + } + + /** TS3's {@code denoiser_level}: 0 is 6 dB, 3 is 21 dB; out of range is clamped. */ + public static SuppressionLevel fromDenoiserLevel(int level) { + SuppressionLevel[] all = values(); + return all[Math.max(0, Math.min(all.length - 1, level))]; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/WienerFilter.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/WienerFilter.java new file mode 100644 index 0000000..1214ade --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/ns/WienerFilter.java @@ -0,0 +1,93 @@ +package eu.lixko.ts3j.client.audio.processing.ns; + +import static eu.lixko.ts3j.client.audio.processing.ns.NsCommon.FFT_SIZE_BY_2_PLUS_1; +import static eu.lixko.ts3j.client.audio.processing.ns.NsCommon.LONG_STARTUP_PHASE_BLOCKS; +import static eu.lixko.ts3j.client.audio.processing.ns.NsCommon.SHORT_STARTUP_PHASE_BLOCKS; + +import java.util.Arrays; + +/** + * The per-bin suppression gain, from {@code ns/wiener_filter.cc}: a Wiener filter on the + * decision-directed prior SNR, floored at the level's minimum gain, plus the overall + * adjustment that eases the cut when it removed a lot of a likely-speech frame. + */ +final class WienerFilter { + + private static final int BINS = FFT_SIZE_BY_2_PLUS_1; + + private final SuppressionLevel params; + private final float[] spectrumPrevProcess = new float[BINS]; + private final float[] initialSpectralEstimate = new float[BINS]; + final float[] filter = new float[BINS]; + + WienerFilter(SuppressionLevel params) { + this.params = params; + Arrays.fill(filter, 1.f); + } + + void update(int numAnalyzedFrames, float[] noiseSpectrum, float[] prevNoiseSpectrum, + float[] parametricNoiseSpectrum, float[] signalSpectrum) { + for (int i = 0; i < BINS; i++) { + // Previous estimate based on the previous frame with the gain filter. + float prevTsa = spectrumPrevProcess[i] / (prevNoiseSpectrum[i] + 0.0001f) * filter[i]; + + float currentTsa; + if (signalSpectrum[i] > noiseSpectrum[i]) { + currentTsa = signalSpectrum[i] / (noiseSpectrum[i] + 0.0001f) - 1.f; + } else { + currentTsa = 0.f; + } + + float snrPrior = 0.98f * prevTsa + (1.f - 0.98f) * currentTsa; + filter[i] = snrPrior / (params.overSubtractionFactor + snrPrior); + filter[i] = Math.max(Math.min(filter[i], 1.f), params.minimumAttenuatingGain); + } + + if (numAnalyzedFrames < SHORT_STARTUP_PHASE_BLOCKS) { + // Blend in the parametric noise model while the estimates settle. + final float oneByShortStartupPhaseBlocks = 1.f / SHORT_STARTUP_PHASE_BLOCKS; + for (int i = 0; i < BINS; i++) { + initialSpectralEstimate[i] += signalSpectrum[i]; + float filterInitial = initialSpectralEstimate[i] + - params.overSubtractionFactor * parametricNoiseSpectrum[i]; + filterInitial /= initialSpectralEstimate[i] + 0.0001f; + filterInitial = Math.max(Math.min(filterInitial, 1.f), params.minimumAttenuatingGain); + + filterInitial *= SHORT_STARTUP_PHASE_BLOCKS - numAnalyzedFrames; + filter[i] *= numAnalyzedFrames; + filter[i] += filterInitial; + filter[i] *= oneByShortStartupPhaseBlocks; + } + } + + System.arraycopy(signalSpectrum, 0, spectrumPrevProcess, 0, BINS); + } + + float computeOverallScalingFactor(int numAnalyzedFrames, float priorSpeechProbability, + float energyBeforeFiltering, float energyAfterFiltering) { + if (!params.useAttenuationAdjustment || numAnalyzedFrames <= LONG_STARTUP_PHASE_BLOCKS) { + return 1.f; + } + + float gain = FastMath.sqrt(energyAfterFiltering / (energyBeforeFiltering + 1.f)); + + final float bLim = 0.5f; + float scaleFactor1 = 1.f; + if (gain > bLim) { + scaleFactor1 = 1.f + 1.3f * (gain - bLim); + if (gain * scaleFactor1 > 1.f) { + scaleFactor1 = 1.f / gain; + } + } + + float scaleFactor2 = 1.f; + if (gain < bLim) { + // Do not reduce the scale too much for pause regions: attenuation is already + // controlled by the gain floor. + gain = Math.max(gain, params.minimumAttenuatingGain); + scaleFactor2 = 1.f - 0.3f * (bLim - gain); + } + + return priorSpeechProbability * scaleFactor1 + (1.f - priorSpeechProbability) * scaleFactor2; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/transients/TransientDetector.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/transients/TransientDetector.java new file mode 100644 index 0000000..a2e9478 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/transients/TransientDetector.java @@ -0,0 +1,125 @@ +package eu.lixko.ts3j.client.audio.processing.transients; + +import java.util.ArrayDeque; + +/** + * Scores how likely a 10 ms chunk holds a transient such as a key click, from + * {@code transient/transient_detector.cc}. Each wavelet sub-band sample is compared against + * the moving mean and variance of the preceding 30 ms; the summed normalised deviation + * maps through a raised cosine to [0, 1], and the result is the maximum over the last three + * chunks so a click's tail stays covered. + */ +final class TransientDetector { + + private static final int CHUNK_MS = 10; + private static final int TRANSIENT_LENGTH_MS = 30; + private static final int CHUNKS_AT_STARTUP_LEFT_TO_DELETE = TRANSIENT_LENGTH_MS / CHUNK_MS; + private static final float DETECT_THRESHOLD = 16.f; + private static final float PI = 3.14159265358979323846f; + + private final int samplesPerChunk; + private final int leafLength; + private final WaveletPacketTree tree; + private final MovingMoments[] movingMoments = new MovingMoments[WaveletPacketTree.LEAVES]; + private final float[] firstMoments; + private final float[] secondMoments; + private final float[] lastFirstMoment = new float[WaveletPacketTree.LEAVES]; + private final float[] lastSecondMoment = new float[WaveletPacketTree.LEAVES]; + private final ArrayDeque previousResults = new ArrayDeque<>(); + private int chunksAtStartupLeftToDelete = CHUNKS_AT_STARTUP_LEFT_TO_DELETE; + + TransientDetector(int sampleRateHz) { + int perChunk = sampleRateHz * CHUNK_MS / 1000; + int perTransient = sampleRateHz * TRANSIENT_LENGTH_MS / 1000; + perChunk -= perChunk % WaveletPacketTree.LEAVES; + perTransient -= perTransient % WaveletPacketTree.LEAVES; + this.samplesPerChunk = perChunk; + this.tree = new WaveletPacketTree(perChunk); + this.leafLength = tree.leafLength(); + for (int i = 0; i < WaveletPacketTree.LEAVES; i++) { + movingMoments[i] = new MovingMoments(perTransient / WaveletPacketTree.LEAVES); + } + this.firstMoments = new float[leafLength]; + this.secondMoments = new float[leafLength]; + for (int i = 0; i < CHUNKS_AT_STARTUP_LEFT_TO_DELETE; i++) { + previousResults.add(0.f); + } + } + + int samplesPerChunk() { + return samplesPerChunk; + } + + /** Returns a detection score in [0, 1] for the chunk at {@code data[offset..]}. */ + float detect(float[] data, int offset) { + tree.update(data, offset); + + float result = 0.f; + for (int i = 0; i < WaveletPacketTree.LEAVES; i++) { + float[] leaf = tree.leaf(i); + movingMoments[i].calculateMoments(leaf, leafLength, firstMoments, secondMoments); + + // Each sample is judged against the moments of the samples before it. + float unbiased = leaf[0] - lastFirstMoment[i]; + result += unbiased * unbiased / (lastSecondMoment[i] + Float.MIN_NORMAL); + for (int j = 1; j < leafLength; j++) { + unbiased = leaf[j] - firstMoments[j - 1]; + result += unbiased * unbiased / (secondMoments[j - 1] + Float.MIN_NORMAL); + } + + lastFirstMoment[i] = firstMoments[leafLength - 1]; + lastSecondMoment[i] = secondMoments[leafLength - 1]; + } + result /= leafLength; + + // The moments need a full transient length of history before they mean anything. + if (chunksAtStartupLeftToDelete > 0) { + chunksAtStartupLeftToDelete--; + result = 0.f; + } + + if (result >= DETECT_THRESHOLD) { + result = 1.f; + } else { + // Raised cosine from 0 to 1 over [0, threshold), squared. + final float horizontalScaling = PI / DETECT_THRESHOLD; + result = ((float) Math.cos(result * horizontalScaling + PI) + 1.f) * 0.5f; + result *= result; + } + + previousResults.pollFirst(); + previousResults.addLast(result); + float max = 0.f; + for (float r : previousResults) { + max = Math.max(max, r); + } + return max; + } + + /** Running mean and mean square over a fixed window, from {@code moving_moments.cc}. */ + private static final class MovingMoments { + private final int length; + private final float[] queue; + private int head; + private float sum; + private float sumOfSquares; + + MovingMoments(int length) { + this.length = length; + this.queue = new float[length]; + } + + void calculateMoments(float[] in, int n, float[] first, float[] second) { + for (int i = 0; i < n; i++) { + final float oldValue = queue[head]; + queue[head] = in[i]; + head = (head + 1) % length; + + sum += in[i] - oldValue; + sumOfSquares += in[i] * in[i] - oldValue * oldValue; + first[i] = sum / length; + second[i] = Math.max(0.f, sumOfSquares / length); + } + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/transients/TransientSuppressor.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/transients/TransientSuppressor.java new file mode 100644 index 0000000..7cb7b6a --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/transients/TransientSuppressor.java @@ -0,0 +1,186 @@ +package eu.lixko.ts3j.client.audio.processing.transients; + +import eu.lixko.ts3j.client.audio.Fft; + +/** + * WebRTC's transient suppressor ({@code transient/transient_suppressor_impl.cc}), the module + * behind TS3's "Typing attenuation", for one 48 kHz channel. + * + *

    It only acts while the user is typing: every key press is reported through + * {@code keyPressed}, the detector switches on with the first press and the suppression + * with the second within about a second; four seconds without a press switch both off. + * While suppressing, spectral peaks that jump above the running spectral mean during a + * detected transient are pulled back towards it. + * + *

    TS3 runs it with no analog AGC, so APM hands it a voice probability of 1: the + * suppressor always uses its "soft", voiced restoration, and the unvoiced "hard" path with + * its random phases is never taken. That path is left out here. + * + *

    The output is delayed by 544 samples (11.3 ms) whether or not it is suppressing, + * exactly as upstream, so switching on and off doesn't shift the signal. + */ +public final class TransientSuppressor { + + private static final int CHUNK_MS = 10; + private static final float MEAN_IIR_COEFFICIENT = 0.5f; + private static final int MIN_VOICE_BIN = 3; + private static final int MAX_VOICE_BIN = 60; + + private static final int KEYPRESS_PENALTY = 1000 / CHUNK_MS; + private static final int IS_TYPING_THRESHOLD = 1000 / CHUNK_MS; + private static final int CHUNKS_UNTIL_NOT_TYPING = 4000 / CHUNK_MS; + + private static final int DATA_LENGTH = 480; + private static final int ANALYSIS_LENGTH = 1024; + private static final int BUFFER_DELAY = ANALYSIS_LENGTH - DATA_LENGTH; + private static final int COMPLEX_LENGTH = ANALYSIS_LENGTH / 2 + 1; + + /** + * {@code kBlocks480w1024}: a half-sine over [32, 992], zero outside. Upstream stores it + * as a table; this formula reproduces it to within float rounding. + */ + private static final float[] WINDOW = new float[ANALYSIS_LENGTH]; + + static { + for (int i = 32; i < 992; i++) { + WINDOW[i] = (float) Math.sin(Math.PI * (i - 32) / 960.0); + } + } + + private final TransientDetector detector; + private final float[] inBuffer = new float[ANALYSIS_LENGTH]; + private final float[] outBuffer = new float[ANALYSIS_LENGTH]; + private final float[] spectralMean = new float[COMPLEX_LENGTH]; + private final float[] magnitudes = new float[COMPLEX_LENGTH]; + private final float[] meanFactor = new float[COMPLEX_LENGTH]; + private final double[] fftRe = new double[ANALYSIS_LENGTH]; + private final double[] fftIm = new double[ANALYSIS_LENGTH]; + + private float detectorSmoothed; + private int keypressCounter; + private int chunksSinceKeypress; + private boolean detectionEnabled; + private boolean suppressionEnabled; + + /** @param detectionRateHz rate of the detection data passed to {@link #suppress} */ + public TransientSuppressor(int detectionRateHz) { + this.detector = new TransientDetector(detectionRateHz); + // A double sigmoid with its minimum over the voice range (300 Hz - 3 kHz at 16 kHz bins). + final float factorHeight = 10.f; + final float lowSlope = 1.f; + final float highSlope = 0.3f; + for (int i = 0; i < COMPLEX_LENGTH; i++) { + meanFactor[i] = factorHeight / (1.f + (float) Math.exp(lowSlope * (i - MIN_VOICE_BIN))) + + factorHeight / (1.f + (float) Math.exp(highSlope * (MAX_VOICE_BIN - i))); + } + } + + /** + * Processes 10 ms in place. + * + * @param data 480 samples at 48 kHz + * @param detectionData one chunk at the detection rate: APM passes the 0–8 kHz band + * @param keyPressed whether a key went down since the previous call + */ + public void suppress(float[] data, float[] detectionData, boolean keyPressed) { + updateKeypress(keyPressed); + updateBuffers(data); + + if (detectionEnabled) { + float detectorResult = detector.detect(detectionData, 0); + // Rise with the detector, but decay slowly so the ringing of a click is covered. + final float smoothFactor = 0.1f; + detectorSmoothed = detectorResult >= detectorSmoothed + ? detectorResult + : smoothFactor * detectorSmoothed + (1 - smoothFactor) * detectorResult; + suppressChunk(); + } + + // When not suppressing, the input buffer supplies the same delay. + System.arraycopy(suppressionEnabled ? outBuffer : inBuffer, 0, data, 0, DATA_LENGTH); + } + + private void suppressChunk() { + for (int i = 0; i < ANALYSIS_LENGTH; i++) { + fftRe[i] = inBuffer[i] * WINDOW[i]; + fftIm[i] = 0; + } + Fft.forward(fftRe, fftIm); + + for (int i = 0; i < COMPLEX_LENGTH; i++) { + magnitudes[i] = Math.abs((float) fftRe[i]) + Math.abs((float) fftIm[i]); + } + + if (suppressionEnabled) { + softRestoration(); + } + + for (int i = 0; i < COMPLEX_LENGTH; i++) { + spectralMean[i] = (1 - MEAN_IIR_COEFFICIENT) * spectralMean[i] + MEAN_IIR_COEFFICIENT * magnitudes[i]; + } + + // Back to the time domain; the restoration touched the lower half, mirror it. + for (int i = 1; i < COMPLEX_LENGTH - 1; i++) { + fftRe[ANALYSIS_LENGTH - i] = fftRe[i]; + fftIm[ANALYSIS_LENGTH - i] = -fftIm[i]; + } + fftIm[0] = 0; + fftIm[COMPLEX_LENGTH - 1] = 0; + Fft.inverse(fftRe, fftIm); + for (int i = 0; i < ANALYSIS_LENGTH; i++) { + outBuffer[i] += (float) fftRe[i] * WINDOW[i]; + } + } + + /** + * Pulls peaks above the spectral mean back towards it by the detector's confidence, + * skipping those far above the block's voice-band mean: those are more likely voice. + */ + private void softRestoration() { + float blockFrequencyMean = 0; + for (int i = MIN_VOICE_BIN; i < MAX_VOICE_BIN; i++) { + blockFrequencyMean += magnitudes[i]; + } + blockFrequencyMean /= (MAX_VOICE_BIN - MIN_VOICE_BIN); + + for (int i = 0; i < COMPLEX_LENGTH; i++) { + if (magnitudes[i] > spectralMean[i] && magnitudes[i] > 0 + && magnitudes[i] < blockFrequencyMean * meanFactor[i]) { + final float newMagnitude = magnitudes[i] - detectorSmoothed * (magnitudes[i] - spectralMean[i]); + final float ratio = newMagnitude / magnitudes[i]; + fftRe[i] *= ratio; + fftIm[i] *= ratio; + magnitudes[i] = newMagnitude; + } + } + } + + private void updateKeypress(boolean keyPressed) { + if (keyPressed) { + keypressCounter += KEYPRESS_PENALTY; + chunksSinceKeypress = 0; + detectionEnabled = true; + } + keypressCounter = Math.max(0, keypressCounter - 1); + + if (keypressCounter > IS_TYPING_THRESHOLD) { + suppressionEnabled = true; + keypressCounter = 0; + } + + if (detectionEnabled && ++chunksSinceKeypress > CHUNKS_UNTIL_NOT_TYPING) { + detectionEnabled = false; + suppressionEnabled = false; + keypressCounter = 0; + } + } + + private void updateBuffers(float[] data) { + System.arraycopy(inBuffer, DATA_LENGTH, inBuffer, 0, BUFFER_DELAY); + System.arraycopy(data, 0, inBuffer, BUFFER_DELAY, DATA_LENGTH); + if (detectionEnabled) { + System.arraycopy(outBuffer, DATA_LENGTH, outBuffer, 0, BUFFER_DELAY); + java.util.Arrays.fill(outBuffer, BUFFER_DELAY, ANALYSIS_LENGTH, 0.f); + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/transients/WaveletPacketTree.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/transients/WaveletPacketTree.java new file mode 100644 index 0000000..896781f --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/processing/transients/WaveletPacketTree.java @@ -0,0 +1,124 @@ +package eu.lixko.ts3j.client.audio.processing.transients; + +/** + * A three-level wavelet packet decomposition with Daubechies-8 filters, ported from + * {@code transient/wpd_tree.cc} and {@code wpd_node.cc}. Each node low- or high-pass + * filters its parent, keeps the odd samples and rectifies them; the eight leaves hand the + * transient detector the signal's envelope in eight sub-bands. + */ +final class WaveletPacketTree { + + static final int LEVELS = 3; + static final int LEAVES = 1 << LEVELS; + + private static final float[] HIGH_PASS = { + -5.44158422430816093862e-02f, 3.12871590914465924627e-01f, + -6.75630736298012846142e-01f, 5.85354683654869090148e-01f, + 1.58291052560238926228e-02f, -2.84015542962428091389e-01f, + -4.72484573997972536787e-04f, 1.28747426620186011803e-01f, + 1.73693010020221083600e-02f, -4.40882539310647192377e-02f, + -1.39810279170155156436e-02f, 8.74609404701565465445e-03f, + 4.87035299301066034600e-03f, -3.91740372995977108837e-04f, + -6.75449405998556772109e-04f, -1.17476784002281916305e-04f}; + + private static final float[] LOW_PASS = { + -1.17476784002281916305e-04f, 6.75449405998556772109e-04f, + -3.91740372995977108837e-04f, -4.87035299301066034600e-03f, + 8.74609404701565465445e-03f, 1.39810279170155156436e-02f, + -4.40882539310647192377e-02f, -1.73693010020221083600e-02f, + 1.28747426620186011803e-01f, 4.72484573997972536787e-04f, + -2.84015542962428091389e-01f, -1.58291052560238926228e-02f, + 5.85354683654869090148e-01f, 6.75630736298012846142e-01f, + 3.12871590914465924627e-01f, 5.44158422430816093862e-02f}; + + /** Heap-ordered: node 1 is the root, node {@code n}'s children are {@code 2n} and {@code 2n+1}. */ + private final Node[] nodes = new Node[(1 << (LEVELS + 1))]; + + WaveletPacketTree(int dataLength) { + nodes[1] = new Node(dataLength, null); + for (int level = 0; level < LEVELS; level++) { + for (int i = 0; i < (1 << level); i++) { + int index = (1 << level) + i; + nodes[2 * index] = new Node(nodes[index].length / 2, LOW_PASS); + nodes[2 * index + 1] = new Node(nodes[index].length / 2, HIGH_PASS); + } + } + } + + void update(float[] data, int offset) { + System.arraycopy(data, offset, nodes[1].data, 0, nodes[1].length); + for (int level = 0; level < LEVELS; level++) { + for (int i = 0; i < (1 << level); i++) { + int index = (1 << level) + i; + nodes[2 * index].update(nodes[index]); + nodes[2 * index + 1].update(nodes[index]); + } + } + } + + /** The data of leaf {@code index}; its first {@link #leafLength()} samples are valid. */ + float[] leaf(int index) { + return nodes[LEAVES + index].data; + } + + int leafLength() { + return nodes[LEAVES].length; + } + + private static final class Node { + final int length; + /** Sized for the parent's length: the filter output lands here before decimation. */ + final float[] data; + private final float[] coefficients; // reversed, as FIRFilterC stores them + private final float[] state; + + Node(int length, float[] coefficients) { + this.length = length; + this.data = new float[2 * length + 1]; + if (coefficients == null) { + this.coefficients = null; + this.state = null; + } else { + int n = coefficients.length; + this.coefficients = new float[n]; + for (int i = 0; i < n; i++) { + this.coefficients[i] = coefficients[n - i - 1]; + } + this.state = new float[n - 1]; + } + } + + void update(Node parent) { + filter(parent.data, parent.length, data); + // Keep the odd samples, then rectify. + for (int i = 0; i < length; i++) { + data[i] = data[2 * i + 1]; + } + for (int i = 0; i < length; i++) { + data[i] = Math.abs(data[i]); + } + } + + /** FIR convolution carrying the last {@code taps - 1} inputs over, as in {@code fir_filter_c.cc}. */ + private void filter(float[] in, int n, float[] out) { + int stateLength = state.length; + for (int i = 0; i < n; i++) { + float acc = 0.f; + int j = 0; + for (; stateLength > i && j < stateLength - i; j++) { + acc += state[i + j] * coefficients[j]; + } + for (; j < coefficients.length; j++) { + acc += in[j + i - stateLength] * coefficients[j]; + } + out[i] = acc; + } + if (n >= stateLength) { + System.arraycopy(in, n - stateLength, state, 0, stateLength); + } else { + System.arraycopy(state, n, state, 0, stateLength - n); + System.arraycopy(in, 0, state, stateLength - n, n); + } + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/LinearPrediction.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/LinearPrediction.java new file mode 100644 index 0000000..be289f0 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/LinearPrediction.java @@ -0,0 +1,99 @@ +package eu.lixko.ts3j.client.audio.vad; + +import static eu.lixko.ts3j.client.audio.vad.VadConstants.NUM_LPC_COEFFICIENTS; + +/** + * Linear-prediction analysis for the pitch search, ported from WebRTC's + * {@code rnn_vad/lp_residual.cc}. + * + *

    Whitening the signal before searching for a pitch makes the auto-correlation peak at + * the true period rather than at whichever formant happens to dominate. + */ +final class LinearPrediction { + + private final float[] autoCorr = new float[NUM_LPC_COEFFICIENTS]; + private final float[] reflection = new float[NUM_LPC_COEFFICIENTS - 1]; + + /** Computes the 5 post-processed inverse-filter coefficients for {@code x}. */ + void computeLpcCoefficients(float[] x, float[] lpcCoeffs) { + for (int lag = 0; lag < NUM_LPC_COEFFICIENTS; lag++) { + float sum = 0; + for (int i = 0; i < x.length - lag; i++) { + sum += x[i] * x[i + lag]; + } + autoCorr[lag] = sum; + } + if (autoCorr[0] == 0.0f) { // Empty frame. + java.util.Arrays.fill(lpcCoeffs, 0.0f); + return; + } + + // Assume a -40 dB white noise floor. + autoCorr[0] *= 1.0001f; + autoCorr[1] -= autoCorr[1] * 0.000064f; + autoCorr[2] -= autoCorr[2] * 0.000256f; + autoCorr[3] -= autoCorr[3] * 0.000576f; + autoCorr[4] -= autoCorr[4] * 0.001024f; + + java.util.Arrays.fill(reflection, 0.0f); + computeInitialInverseFilterCoefficients(); + + // Bandwidth expansion, then convolution with (1 + 0.8 z^-1). + reflection[0] *= 0.9f; + reflection[1] *= 0.9f * 0.9f; + reflection[2] *= 0.9f * 0.9f * 0.9f; + reflection[3] *= 0.9f * 0.9f * 0.9f * 0.9f; + final float c = 0.8f; + lpcCoeffs[0] = reflection[0] + c; + lpcCoeffs[1] = reflection[1] + c * reflection[0]; + lpcCoeffs[2] = reflection[2] + c * reflection[1]; + lpcCoeffs[3] = reflection[3] + c * reflection[2]; + lpcCoeffs[4] = c * reflection[3]; + } + + /** Levinson–Durbin recursion over {@link #autoCorr}, writing {@link #reflection}. */ + private void computeInitialInverseFilterCoefficients() { + float error = autoCorr[0]; + for (int i = 0; i < NUM_LPC_COEFFICIENTS - 1; i++) { + float reflectionCoeff = 0; + for (int j = 0; j < i; j++) { + reflectionCoeff += reflection[j] * autoCorr[i - j]; + } + reflectionCoeff += autoCorr[i + 1]; + + // Avoid dividing by numbers close to zero. + final float minErrorMagnitude = 1e-6f; + if (Math.abs(error) < minErrorMagnitude) { + error = Math.copySign(minErrorMagnitude, error); + } + reflectionCoeff /= -error; + + reflection[i] = reflectionCoeff; + for (int j = 0; j < ((i + 1) >> 1); j++) { + float tmp1 = reflection[j]; + float tmp2 = reflection[i - 1 - j]; + reflection[j] = tmp1 + reflectionCoeff * tmp2; + reflection[i - 1 - j] = tmp2 + reflectionCoeff * tmp1; + } + error -= reflectionCoeff * reflectionCoeff * error; + if (error < 0.001f * autoCorr[0]) { + break; + } + } + } + + /** + * Applies the inverse filter: {@code y[i] = x[i] + sum_j lpc[j] * x[i - 1 - j]}, + * with the sum truncated near the start of the buffer. + */ + static void computeLpResidual(float[] lpcCoeffs, float[] x, float[] y) { + for (int i = 0; i < x.length; i++) { + float sum = x[i]; + int taps = Math.min(i, NUM_LPC_COEFFICIENTS); + for (int j = 0; j < taps; j++) { + sum += lpcCoeffs[j] * x[i - 1 - j]; + } + y[i] = sum; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/PitchEstimator.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/PitchEstimator.java new file mode 100644 index 0000000..a8a04d9 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/PitchEstimator.java @@ -0,0 +1,329 @@ +package eu.lixko.ts3j.client.audio.vad; + +import static eu.lixko.ts3j.client.audio.vad.VadConstants.BUF_SIZE_12K; +import static eu.lixko.ts3j.client.audio.vad.VadConstants.FRAME_20MS_12K; +import static eu.lixko.ts3j.client.audio.vad.VadConstants.FRAME_20MS_24K; +import static eu.lixko.ts3j.client.audio.vad.VadConstants.INITIAL_NUM_LAGS_24K; +import static eu.lixko.ts3j.client.audio.vad.VadConstants.MAX_PITCH_24K; +import static eu.lixko.ts3j.client.audio.vad.VadConstants.MAX_PITCH_48K; +import static eu.lixko.ts3j.client.audio.vad.VadConstants.MIN_PITCH_24K; +import static eu.lixko.ts3j.client.audio.vad.VadConstants.MIN_PITCH_48K; +import static eu.lixko.ts3j.client.audio.vad.VadConstants.NUM_LAGS_12K; +import static eu.lixko.ts3j.client.audio.vad.VadConstants.REFINE_NUM_LAGS_24K; + +/** + * Pitch period estimation for {@code rnn_vad}, ported from WebRTC's + * {@code rnn_vad/pitch_search.cc} and {@code pitch_search_internal.cc}. + * + *

    Three stages: a coarse search over the 12 kHz decimated LP residual picks two + * candidates, those are refined against the 24 kHz buffer, and finally sub-harmonics + * of the winner are tested so that an octave error can be corrected. The result is a + * period expressed at 48 kHz, which is what the network was trained on. + * + *

    Lags are stored inverted: index 0 corresponds to the maximum pitch period. + */ +final class PitchEstimator { + + /** + * For each divisor k in [2, 15], the multiplier n such that n*T/k is a sub-harmonic + * worth checking alongside T/k, chosen so no multiple is visited twice. + */ + private static final int[] SUB_HARMONIC_MULTIPLIERS = + {3, 2, 3, 2, 5, 2, 3, 2, 3, 2, 5, 2, 3, 2}; + + /** Thresholds on the initial period, computed as {@code [5*k*k for k in range(16)]}. */ + private static final int[] INITIAL_PITCH_PERIOD_THRESHOLDS = + {20, 45, 80, 125, 180, 245, 320, 405, 500, 605, 720, 845, 980, 1125}; + + /** Number of pitch periods analysed either side of a candidate during refinement. */ + private static final int PITCH_NEIGHBORHOOD_RADIUS = 2; + + private final float[] pitchBuffer12k = new float[BUF_SIZE_12K]; + private final float[] autoCorrelation12k = new float[NUM_LAGS_12K]; + private final float[] yEnergy24k = new float[REFINE_NUM_LAGS_24K]; + private final float[] autoCorrelation24k = new float[INITIAL_NUM_LAGS_24K]; + private final int[] invertedLagsIndex = new int[2 * (2 * PITCH_NEIGHBORHOOD_RADIUS + 1)]; + private int invertedLagsCount; + + // Pitch tracking: the previous estimate biases the sub-harmonic decision. + private int lastPeriod48k; + private float lastStrength; + + void reset() { + lastPeriod48k = 0; + lastStrength = 0; + } + + /** Returns the pitch period at 48 kHz for the given 24 kHz LP residual buffer. */ + int estimate(float[] pitchBuffer) { + // Coarse search at 12 kHz. WebRTC decimates without an anti-aliasing filter here; + // the refinement stage below is what recovers the accuracy. + for (int i = 0; i < BUF_SIZE_12K; i++) { + pitchBuffer12k[i] = pitchBuffer[2 * i]; + } + computeAutoCorrelation12k(); + long candidates = computePitchPeriod12kHz(); + int best = (int) (candidates >> 32) * 2; + int secondBest = (int) candidates * 2; + + computeSlidingFrameSquareEnergies24k(pitchBuffer); + int pitchLag48k = computePitchPeriod48kHz(pitchBuffer, best, secondBest); + computeExtendedPitchPeriod48kHz(pitchBuffer, MAX_PITCH_48K - pitchLag48k); + return lastPeriod48k; + } + + /** + * {@code autoCorrelation12k[lag]} is the correlation of the most recent 20 ms with the + * frame starting {@code lag} samples into the buffer. + */ + private void computeAutoCorrelation12k() { + final int refOffset = BUF_SIZE_12K - FRAME_20MS_12K; + for (int lag = 0; lag < NUM_LAGS_12K; lag++) { + float sum = 0; + for (int i = 0; i < FRAME_20MS_12K; i++) { + sum += pitchBuffer12k[refOffset + i] * pitchBuffer12k[lag + i]; + } + autoCorrelation12k[lag] = sum; + } + } + + /** Returns the best and second-best inverted lags packed into a long. */ + private long computePitchPeriod12kHz() { + float denominator = 1.0f; + for (int i = 0; i < FRAME_20MS_12K + 1; i++) { + denominator += pitchBuffer12k[i] * pitchBuffer12k[i]; + } + + int bestLag = 0; + float bestNumerator = -1.0f; + float bestDenominator = 0.0f; + int secondLag = 1; + float secondNumerator = -1.0f; + float secondDenominator = 0.0f; + + for (int invertedLag = 0; invertedLag < NUM_LAGS_12K; invertedLag++) { + // A pitch candidate must have positive correlation. + if (autoCorrelation12k[invertedLag] > 0.0f) { + float numerator = autoCorrelation12k[invertedLag] * autoCorrelation12k[invertedLag]; + // Compare numerator/denominator ratios without dividing. + if (numerator * secondDenominator > secondNumerator * denominator) { + if (numerator * bestDenominator > bestNumerator * denominator) { + secondLag = bestLag; + secondNumerator = bestNumerator; + secondDenominator = bestDenominator; + bestLag = invertedLag; + bestNumerator = numerator; + bestDenominator = denominator; + } else { + secondLag = invertedLag; + secondNumerator = numerator; + secondDenominator = denominator; + } + } + } + // Slide the energy window to the next inverted lag. + float yOld = pitchBuffer12k[invertedLag]; + float yNew = pitchBuffer12k[invertedLag + FRAME_20MS_12K]; + denominator -= yOld * yOld; + denominator += yNew * yNew; + denominator = Math.max(0.0f, denominator); + } + return ((long) bestLag << 32) | (secondLag & 0xffffffffL); + } + + /** Energy of the sliding 20 ms frame for every inverted lag. */ + private void computeSlidingFrameSquareEnergies24k(float[] pitchBuffer) { + float yy = 0; + for (int i = 0; i < FRAME_20MS_24K; i++) { + yy += pitchBuffer[i] * pitchBuffer[i]; + } + yEnergy24k[0] = yy; + for (int invertedLag = 0; invertedLag < MAX_PITCH_24K; invertedLag++) { + yy -= pitchBuffer[invertedLag] * pitchBuffer[invertedLag]; + yy += pitchBuffer[invertedLag + FRAME_20MS_24K] * pitchBuffer[invertedLag + FRAME_20MS_24K]; + yy = Math.max(1.0f, yy); + yEnergy24k[invertedLag + 1] = yy; + } + } + + /** Correlation of the most recent 20 ms with the frame at {@code invertedLag}. */ + private static float autoCorrelation(int invertedLag, float[] pitchBuffer) { + float sum = 0; + for (int i = 0; i < FRAME_20MS_24K; i++) { + sum += pitchBuffer[MAX_PITCH_24K + i] * pitchBuffer[invertedLag + i]; + } + return sum; + } + + /** + * Recomputes the auto-correlation around both candidates at 24 kHz and returns the + * strongest inverted lag, pseudo-interpolated to 48 kHz. + */ + private int computePitchPeriod48kHz(float[] pitchBuffer, int bestCandidate, int secondCandidate) { + invertedLagsCount = 0; + // Order the two neighbourhoods so the first precedes the second. + boolean swap = bestCandidate > secondCandidate; + int firstCenter = swap ? secondCandidate : bestCandidate; + int secondCenter = swap ? bestCandidate : secondCandidate; + int r1min = Math.max(firstCenter - PITCH_NEIGHBORHOOD_RADIUS, 0); + int r1max = Math.min(firstCenter + PITCH_NEIGHBORHOOD_RADIUS, INITIAL_NUM_LAGS_24K - 1); + int r2min = Math.max(secondCenter - PITCH_NEIGHBORHOOD_RADIUS, 0); + int r2max = Math.min(secondCenter + PITCH_NEIGHBORHOOD_RADIUS, INITIAL_NUM_LAGS_24K - 1); + + if (r1max + 1 >= r2min) { // Overlapping or adjacent ranges. + computeAutoCorrelationRange(pitchBuffer, r1min, r2max); + } else { + computeAutoCorrelationRange(pitchBuffer, r1min, r1max); + computeAutoCorrelationRange(pitchBuffer, r2min, r2max); + } + + int bestInvertedLag = 0; + float bestNumerator = -1.0f; + float bestDenominator = 0.0f; + for (int i = 0; i < invertedLagsCount; i++) { + int invertedLag = invertedLagsIndex[i]; + if (autoCorrelation24k[invertedLag] > 0.0f) { + float numerator = autoCorrelation24k[invertedLag] * autoCorrelation24k[invertedLag]; + float denominator = yEnergy24k[invertedLag]; + if (numerator * bestDenominator > bestNumerator * denominator) { + bestInvertedLag = invertedLag; + bestNumerator = numerator; + bestDenominator = denominator; + } + } + } + + if (bestInvertedLag == 0 || bestInvertedLag >= INITIAL_NUM_LAGS_24K - 1) { + return bestInvertedLag * 2; // Cannot interpolate at the boundaries. + } + int offset = pseudoInterpolationOffset( + autoCorrelation24k[bestInvertedLag + 1], + autoCorrelation24k[bestInvertedLag], + autoCorrelation24k[bestInvertedLag - 1]); + return 2 * bestInvertedLag + offset; + } + + private void computeAutoCorrelationRange(float[] pitchBuffer, int min, int max) { + // The pseudo-interpolation reads one lag either side, so zero those rather than + // clearing the whole array. + if (min > 0) { + autoCorrelation24k[min - 1] = 0.0f; + } + if (max < INITIAL_NUM_LAGS_24K - 1) { + autoCorrelation24k[max + 1] = 0.0f; + } + for (int invertedLag = min; invertedLag <= max; invertedLag++) { + autoCorrelation24k[invertedLag] = autoCorrelation(invertedLag, pitchBuffer); + invertedLagsIndex[invertedLagsCount++] = invertedLag; + } + } + + /** Returns a lag correction in {-1, 0, +1} based on the neighbouring correlations. */ + private static int pseudoInterpolationOffset(float prev, float curr, float next) { + if ((next - prev) > 0.7f * (curr - prev)) { + return 1; + } else if ((prev - next) > 0.7f * (curr - next)) { + return -1; + } + return 0; + } + + /** Refines {@code lag} (24 kHz) to a 48 kHz lag using pseudo-interpolation. */ + private static int pseudoInterpolationLagPitchBuf(int lag, float[] pitchBuffer) { + int offset = 0; + if (lag > 0 && lag < MAX_PITCH_24K) { + int invertedLag = MAX_PITCH_24K - lag; + offset = pseudoInterpolationOffset( + autoCorrelation(invertedLag + 1, pitchBuffer), + autoCorrelation(invertedLag, pitchBuffer), + autoCorrelation(invertedLag - 1, pitchBuffer)); + } + return 2 * lag + offset; + } + + /** Same as {@code round(multiplier * pitchPeriod / divisor)}. */ + private static int alternativePitchPeriod(int pitchPeriod, int multiplier, int divisor) { + return (2 * multiplier * pitchPeriod + divisor) / (2 * divisor); + } + + /** + * Tests sub-harmonics of the refined period and keeps the strongest, then stores the + * winner in {@link #lastPeriod48k}/{@link #lastStrength}. + */ + private void computeExtendedPitchPeriod48kHz(float[] pitchBuffer, int initialPeriod48k) { + final float xEnergy = yEnergy24k[MAX_PITCH_24K]; + + int bestPeriod = Math.min(initialPeriod48k / 2, MAX_PITCH_24K - 1); + float bestXy = autoCorrelation(MAX_PITCH_24K - bestPeriod, pitchBuffer); + float bestYEnergy = yEnergy24k[MAX_PITCH_24K - bestPeriod]; + float bestStrength = pitchStrength(bestXy, bestYEnergy, xEnergy); + + final int initialPeriod = bestPeriod; + final float initialStrength = bestStrength; + // The tracked pitch is kept at 48 kHz but compared at 24 kHz. + final int lastPeriod = lastPeriod48k / 2; + + // Largest divisor for which the alternative period is still above the minimum. + int maxPeriodDivisor = (2 * initialPeriod) / (2 * MIN_PITCH_24K - 1); + for (int periodDivisor = 2; periodDivisor <= maxPeriodDivisor; periodDivisor++) { + int alternativePeriod = alternativePitchPeriod(initialPeriod, 1, periodDivisor); + int dualPeriod = alternativePitchPeriod( + initialPeriod, SUB_HARMONIC_MULTIPLIERS[periodDivisor - 2], periodDivisor); + // Special case: for a divisor of 2 the sub-harmonic can exceed the pitch range. + if (periodDivisor == 2 && dualPeriod > MAX_PITCH_24K) { + dualPeriod = initialPeriod; + } + + // Score the candidate together with its sub-harmonic. + float xyPrimary = autoCorrelation(MAX_PITCH_24K - alternativePeriod, pitchBuffer); + float xySecondary = autoCorrelation(MAX_PITCH_24K - dualPeriod, pitchBuffer); + float xy = 0.5f * (xyPrimary + xySecondary); + float yy = 0.5f * (yEnergy24k[MAX_PITCH_24K - alternativePeriod] + + yEnergy24k[MAX_PITCH_24K - dualPeriod]); + float alternativeStrength = pitchStrength(xy, yy, xEnergy); + + if (isAlternativeStronger(lastPeriod, initialPeriod, initialStrength, + alternativePeriod, alternativeStrength, periodDivisor)) { + bestPeriod = alternativePeriod; + bestStrength = alternativeStrength; + bestXy = xy; + bestYEnergy = yy; + } + } + + bestXy = Math.max(0.0f, bestXy); + float finalStrength = (bestYEnergy <= bestXy) ? 1.0f : bestXy / (bestYEnergy + 1.0f); + finalStrength = Math.min(bestStrength, finalStrength); + + lastPeriod48k = Math.max(MIN_PITCH_48K, pseudoInterpolationLagPitchBuf(bestPeriod, pitchBuffer)); + lastStrength = finalStrength; + } + + private static float pitchStrength(float xy, float yEnergy, float xEnergy) { + return xy / (float) Math.sqrt(1.0f + xEnergy * yEnergy); + } + + private boolean isAlternativeStronger(int lastPeriod, int initialPeriod, float initialStrength, + int alternativePeriod, float alternativeStrength, + int periodDivisor) { + // Pitch tracking: a candidate close to the previous estimate clears a lower bar. + float lowerThresholdTerm = 0.0f; + int distance = Math.abs(alternativePeriod - lastPeriod); + if (distance <= 1) { + lowerThresholdTerm = lastStrength; + } else if (distance == 2 + && initialPeriod > INITIAL_PITCH_PERIOD_THRESHOLDS[periodDivisor - 2]) { + lowerThresholdTerm = 0.5f * lastStrength; + } + + // Higher frequencies get a stricter threshold: short-term correlations bias + // the search towards them and cause false positives. + float threshold = Math.max(0.3f, 0.7f * initialStrength - lowerThresholdTerm); + if (alternativePeriod < 3 * MIN_PITCH_24K) { + threshold = Math.max(0.4f, 0.85f * initialStrength - lowerThresholdTerm); + } else if (alternativePeriod < 2 * MIN_PITCH_24K) { + threshold = Math.max(0.5f, 0.9f * initialStrength - lowerThresholdTerm); + } + return alternativeStrength > threshold; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/RealFft.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/RealFft.java new file mode 100644 index 0000000..4c3d5de --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/RealFft.java @@ -0,0 +1,224 @@ +package eu.lixko.ts3j.client.audio.vad; + +/** + * Real-input FFT for the {@code rnn_vad} spectral analysis. + * + *

    The transform length is 480 (a 20 ms frame at 24 kHz), which is not a + * power of two, so the shared radix-2 {@code Fft} cannot be used. This is a + * mixed-radix Cooley–Tukey complex FFT (radices 2, 3, 4 and 5, with a generic + * DFT for any other factor) wrapped in the standard real-input trick: an + * {@code n}-point real transform is computed as an {@code n/2}-point complex one + * followed by a split step. + * + *

    Output uses the packed layout WebRTC's PFFFT produces, which the band + * correlator indexes directly: + *

    + *   out[0]     = Re(X[0])      (DC)
    + *   out[1]     = Re(X[n/2])    (Nyquist)
    + *   out[2k]    = Re(X[k])
    + *   out[2k+1]  = Im(X[k])      for k in [1, n/2)
    + * 
    + */ +final class RealFft { + + private final int size; + private final int half; + + // Twiddles for the complex sub-transform and for the real split step. + private final float[] halfRe; + private final float[] halfIm; + private final float[] splitCos; + private final float[] splitSin; + + private final ComplexFft complexFft; + + RealFft(int size) { + if (size < 2 || (size & 1) != 0) { + throw new IllegalArgumentException("Real FFT length must be even: " + size); + } + this.size = size; + this.half = size / 2; + this.halfRe = new float[half]; + this.halfIm = new float[half]; + this.complexFft = new ComplexFft(half); + + this.splitCos = new float[half / 2 + 1]; + this.splitSin = new float[half / 2 + 1]; + for (int k = 0; k <= half / 2; k++) { + double angle = -2.0 * Math.PI * k / size; + splitCos[k] = (float) Math.cos(angle); + splitSin[k] = (float) Math.sin(angle); + } + } + + int size() { + return size; + } + + /** + * Transforms {@code in} ({@link #size} real samples) into {@code out} + * ({@link #size} floats in the packed layout described above). + */ + void forward(float[] in, float[] out) { + // Pack the real signal as half/2 complex samples: z[i] = x[2i] + j*x[2i+1]. + for (int i = 0; i < half; i++) { + halfRe[i] = in[2 * i]; + halfIm[i] = in[2 * i + 1]; + } + complexFft.forward(halfRe, halfIm); + + // Split Z into the transforms of the even and odd sample sequences, then + // recombine them into the spectrum of the original real signal. + out[0] = halfRe[0] + halfIm[0]; + out[1] = halfRe[0] - halfIm[0]; + for (int k = 1; k <= half / 2; k++) { + int mirror = half - k; + + // Even part: hermitian-symmetric average; odd part: the difference. + float evenRe = 0.5f * (halfRe[k] + halfRe[mirror]); + float evenIm = 0.5f * (halfIm[k] - halfIm[mirror]); + float oddRe = 0.5f * (halfIm[k] + halfIm[mirror]); + float oddIm = -0.5f * (halfRe[k] - halfRe[mirror]); + + float c = splitCos[k]; + float s = splitSin[k]; + float twRe = oddRe * c - oddIm * s; + float twIm = oddRe * s + oddIm * c; + + float re = evenRe + twRe; + float im = evenIm + twIm; + out[2 * k] = re; + out[2 * k + 1] = im; + + if (mirror != k) { + // X[n/2 - k] is the conjugate-mirrored companion of X[k]. + out[2 * mirror] = evenRe - twRe; + out[2 * mirror + 1] = -(evenIm - twIm); + } + } + } + + /** + * Mixed-radix complex FFT, decimation in time. + * + *

    A transform of length {@code n = r * m} is computed by transforming the {@code r} + * interleaved subsequences of length {@code m} and combining them: + * {@code X[k1*m + k2] = sum_j (W_n^(j*k2) * X_j[k2]) * W_r^(j*k1)}. + * + *

    The recursion is expressed directly rather than as an iterative digit-reversed + * loop, which keeps it correct for any factorisation. Scratch buffers are allocated + * once per recursion level so no transform allocates. + */ + static final class ComplexFft { + + private final int n; + private final float[] cosTable; + private final float[] sinTable; + private final float[][] scratchRe; + private final float[][] scratchIm; + private final float[] dftRe; + private final float[] dftIm; + + ComplexFft(int n) { + this.n = n; + this.cosTable = new float[n]; + this.sinTable = new float[n]; + for (int i = 0; i < n; i++) { + double angle = -2.0 * Math.PI * i / n; + cosTable[i] = (float) Math.cos(angle); + sinTable[i] = (float) Math.sin(angle); + } + int depth = 0; + int maxRadix = 1; + for (int rest = n; rest > 1; depth++) { + int r = smallestFactor(rest); + maxRadix = Math.max(maxRadix, r); + rest /= r; + } + this.scratchRe = new float[depth + 1][n]; + this.scratchIm = new float[depth + 1][n]; + this.dftRe = new float[maxRadix]; + this.dftIm = new float[maxRadix]; + } + + /** Transforms {@code re}/{@code im} of length {@code n} in place. */ + void forward(float[] re, float[] im) { + transform(re, im, 0, 1, n, scratchRe[0], scratchIm[0], 0, 1); + System.arraycopy(scratchRe[0], 0, re, 0, n); + System.arraycopy(scratchIm[0], 0, im, 0, n); + } + + /** + * Transforms the {@code len} samples starting at {@code inOff} with the given + * {@code stride}, writing the spectrum to {@code outRe}/{@code outIm} at + * {@code outOff}. + */ + private void transform(float[] inRe, float[] inIm, int inOff, int stride, int len, + float[] outRe, float[] outIm, int outOff, int depth) { + if (len == 1) { + outRe[outOff] = inRe[inOff]; + outIm[outOff] = inIm[inOff]; + return; + } + int r = smallestFactor(len); + int m = len / r; + + // Sub-transforms of the r interleaved subsequences, laid out end to end. + float[] subRe = scratchRe[depth]; + float[] subIm = scratchIm[depth]; + for (int j = 0; j < r; j++) { + transform(inRe, inIm, inOff + j * stride, stride * r, m, + subRe, subIm, outOff + j * m, depth + 1); + } + + // Twiddle step for this transform size, expressed in top-level table units. + int unit = n / len; + for (int k2 = 0; k2 < m; k2++) { + for (int j = 0; j < r; j++) { + int idx = outOff + j * m + k2; + int t = (j * k2 * unit) % n; + float c = cosTable[t]; + float s = sinTable[t]; + dftRe[j] = subRe[idx] * c - subIm[idx] * s; + dftIm[j] = subRe[idx] * s + subIm[idx] * c; + } + combine(outRe, outIm, outOff + k2, m, r); + } + } + + /** Length-{@code r} DFT of {@code dftRe}/{@code dftIm}, written with stride {@code m}. */ + private void combine(float[] outRe, float[] outIm, int outOff, int m, int r) { + switch (r) { + case 2 -> { + outRe[outOff] = dftRe[0] + dftRe[1]; + outIm[outOff] = dftIm[0] + dftIm[1]; + outRe[outOff + m] = dftRe[0] - dftRe[1]; + outIm[outOff + m] = dftIm[0] - dftIm[1]; + } + default -> { + int unit = n / r; + for (int k1 = 0; k1 < r; k1++) { + float sumRe = 0; + float sumIm = 0; + for (int j = 0; j < r; j++) { + int t = (j * k1 % r) * unit; + float c = cosTable[t]; + float s = sinTable[t]; + sumRe += dftRe[j] * c - dftIm[j] * s; + sumIm += dftRe[j] * s + dftIm[j] * c; + } + outRe[outOff + k1 * m] = sumRe; + outIm[outOff + k1 * m] = sumIm; + } + } + } + } + + private static int smallestFactor(int v) { + for (int f = 2; f * f <= v; f++) { + if (v % f == 0) return f; + } + return v; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/RnnNetwork.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/RnnNetwork.java new file mode 100644 index 0000000..17a8082 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/RnnNetwork.java @@ -0,0 +1,203 @@ +package eu.lixko.ts3j.client.audio.vad; + +/** + * The {@code rnn_vad} network: a 42→24 dense layer, a 24-unit GRU and a 24→1 + * dense output. Ported from WebRTC's {@code rnn_vad/rnn.cc}, {@code rnn_fc.cc} and + * {@code rnn_gru.cc}, using the activation approximations from RNNoise. + * + *

    The GRU carries state between frames, so the caller must feed frames in order and + * {@link #reset()} on a discontinuity. Silence resets the state, matching WebRTC. + */ +final class RnnNetwork { + + private static final int INPUT_SIZE = 42; + private static final int FC1_SIZE = 24; + private static final int GRU_SIZE = 24; + private static final int NUM_GATES = 3; // update, reset, output + + private final float[] fc1Weights; // [output][input] + private final float[] fc1Bias; + private final float[] fc2Weights; + private final float[] fc2Bias; + + private final float[] gruWeights; // [gate][output][input] + private final float[] gruRecurrentWeights; // [gate][output][output] + private final float[] gruBias; // [gate][output] + + private final float[] fc1Output = new float[FC1_SIZE]; + private final float[] state = new float[GRU_SIZE]; + private final float[] update = new float[GRU_SIZE]; + private final float[] resetGate = new float[GRU_SIZE]; + private final float[] resetTimesState = new float[GRU_SIZE]; + + RnnNetwork() { + fc1Weights = transposeAndScale(RnnVadWeights.INPUT_DENSE_WEIGHTS, INPUT_SIZE, FC1_SIZE); + fc1Bias = scale(RnnVadWeights.INPUT_DENSE_BIAS); + // The output layer is 24x1, so its stored layout already matches. + fc2Weights = scale(RnnVadWeights.OUTPUT_DENSE_WEIGHTS); + fc2Bias = scale(RnnVadWeights.OUTPUT_DENSE_BIAS); + gruWeights = transposeGruTensor(RnnVadWeights.HIDDEN_GRU_WEIGHTS, FC1_SIZE, GRU_SIZE); + gruRecurrentWeights = + transposeGruTensor(RnnVadWeights.HIDDEN_GRU_RECURRENT_WEIGHTS, GRU_SIZE, GRU_SIZE); + gruBias = transposeGruTensor(RnnVadWeights.HIDDEN_GRU_BIAS, 1, GRU_SIZE); + } + + void reset() { + java.util.Arrays.fill(state, 0.0f); + } + + /** + * Returns the speech probability for a feature vector. When {@code silence} is set the + * state is cleared and zero is returned without running the network. + */ + float computeVadProbability(float[] featureVector, boolean silence) { + if (silence) { + reset(); + return 0.0f; + } + for (int o = 0; o < FC1_SIZE; o++) { + float x = fc1Bias[o] + dot(featureVector, fc1Weights, o * INPUT_SIZE, INPUT_SIZE); + fc1Output[o] = tansigApproximated(x); + } + computeGruOutput(fc1Output); + float x = fc2Bias[0] + dot(state, fc2Weights, 0, GRU_SIZE); + return sigmoidApproximated(x); + } + + private void computeGruOutput(float[] input) { + final int strideWeights = FC1_SIZE * GRU_SIZE; + final int strideRecurrent = GRU_SIZE * GRU_SIZE; + + // u = sigmoid(W_u.i + R_u.s + b_u) + computeGate(input, 0, 0, 0, update); + // r = sigmoid(W_r.i + R_r.s + b_r) + computeGate(input, GRU_SIZE, strideWeights, strideRecurrent, resetGate); + + // s' = u.s + (1 - u).ReLU(W_s.i + R_s.(s.r) + b_s) + for (int o = 0; o < GRU_SIZE; o++) { + resetTimesState[o] = state[o] * resetGate[o]; + } + for (int o = 0; o < GRU_SIZE; o++) { + float x = gruBias[2 * GRU_SIZE + o]; + x += dot(input, gruWeights, 2 * strideWeights + o * FC1_SIZE, FC1_SIZE); + x += dot(resetTimesState, gruRecurrentWeights, + 2 * strideRecurrent + o * GRU_SIZE, GRU_SIZE); + state[o] = update[o] * state[o] + (1.0f - update[o]) * Math.max(0.0f, x); + } + } + + private void computeGate(float[] input, int biasOffset, int weightsOffset, + int recurrentOffset, float[] gate) { + for (int o = 0; o < GRU_SIZE; o++) { + float x = gruBias[biasOffset + o]; + x += dot(input, gruWeights, weightsOffset + o * FC1_SIZE, FC1_SIZE); + x += dot(state, gruRecurrentWeights, recurrentOffset + o * GRU_SIZE, GRU_SIZE); + gate[o] = sigmoidApproximated(x); + } + } + + private static float dot(float[] a, float[] weights, int weightsOffset, int len) { + float sum = 0; + for (int i = 0; i < len; i++) { + sum += a[i] * weights[weightsOffset + i]; + } + return sum; + } + + // ---- weight layout ---- + + private static float[] scale(byte[] src) { + float[] out = new float[src.length]; + for (int i = 0; i < src.length; i++) { + out[i] = RnnVadWeights.SCALE * src[i]; + } + return out; + } + + /** Stored as {@code [input][output]}; the dot products want {@code [output][input]}. */ + private static float[] transposeAndScale(byte[] src, int inputSize, int outputSize) { + float[] out = new float[src.length]; + for (int o = 0; o < outputSize; o++) { + for (int i = 0; i < inputSize; i++) { + out[o * inputSize + i] = RnnVadWeights.SCALE * src[i * outputSize + o]; + } + } + return out; + } + + /** + * GRU tensors are stored as {@code [n][gate][output]} and are wanted as + * {@code [gate][output][n]}, where {@code n} is the input size (1 for the bias). + */ + private static float[] transposeGruTensor(byte[] src, int n, int outputSize) { + float[] out = new float[src.length]; + int strideSrc = NUM_GATES * outputSize; + int strideDst = n * outputSize; + for (int g = 0; g < NUM_GATES; g++) { + for (int o = 0; o < outputSize; o++) { + for (int i = 0; i < n; i++) { + out[g * strideDst + o * n + i] = + RnnVadWeights.SCALE * src[i * strideSrc + g * outputSize + o]; + } + } + } + return out; + } + + // ---- activations (RNNoise approximations, bit-compatible with WebRTC) ---- + + /** tanh sampled every 0.04, copied verbatim from RNNoise's {@code rnn_activations.h}. */ + private static final float[] TANSIG_TABLE = { + 0.000000f, 0.039979f, 0.079830f, 0.119427f, 0.158649f, 0.197375f, 0.235496f, 0.272905f, + 0.309507f, 0.345214f, 0.379949f, 0.413644f, 0.446244f, 0.477700f, 0.507977f, 0.537050f, + 0.564900f, 0.591519f, 0.616909f, 0.641077f, 0.664037f, 0.685809f, 0.706419f, 0.725897f, + 0.744277f, 0.761594f, 0.777888f, 0.793199f, 0.807569f, 0.821040f, 0.833655f, 0.845456f, + 0.856485f, 0.866784f, 0.876393f, 0.885352f, 0.893698f, 0.901468f, 0.908698f, 0.915420f, + 0.921669f, 0.927473f, 0.932862f, 0.937863f, 0.942503f, 0.946806f, 0.950795f, 0.954492f, + 0.957917f, 0.961090f, 0.964028f, 0.966747f, 0.969265f, 0.971594f, 0.973749f, 0.975743f, + 0.977587f, 0.979293f, 0.980869f, 0.982327f, 0.983675f, 0.984921f, 0.986072f, 0.987136f, + 0.988119f, 0.989027f, 0.989867f, 0.990642f, 0.991359f, 0.992020f, 0.992631f, 0.993196f, + 0.993718f, 0.994199f, 0.994644f, 0.995055f, 0.995434f, 0.995784f, 0.996108f, 0.996407f, + 0.996682f, 0.996937f, 0.997172f, 0.997389f, 0.997590f, 0.997775f, 0.997946f, 0.998104f, + 0.998249f, 0.998384f, 0.998508f, 0.998623f, 0.998728f, 0.998826f, 0.998916f, 0.999000f, + 0.999076f, 0.999147f, 0.999213f, 0.999273f, 0.999329f, 0.999381f, 0.999428f, 0.999472f, + 0.999513f, 0.999550f, 0.999585f, 0.999617f, 0.999646f, 0.999673f, 0.999699f, 0.999722f, + 0.999743f, 0.999763f, 0.999781f, 0.999798f, 0.999813f, 0.999828f, 0.999841f, 0.999853f, + 0.999865f, 0.999875f, 0.999885f, 0.999893f, 0.999902f, 0.999909f, 0.999916f, 0.999923f, + 0.999929f, 0.999934f, 0.999939f, 0.999944f, 0.999948f, 0.999952f, 0.999956f, 0.999959f, + 0.999962f, 0.999965f, 0.999968f, 0.999970f, 0.999973f, 0.999975f, 0.999977f, 0.999978f, + 0.999980f, 0.999982f, 0.999983f, 0.999984f, 0.999986f, 0.999987f, 0.999988f, 0.999989f, + 0.999990f, 0.999990f, 0.999991f, 0.999992f, 0.999992f, 0.999993f, 0.999994f, 0.999994f, + 0.999994f, 0.999995f, 0.999995f, 0.999996f, 0.999996f, 0.999996f, 0.999997f, 0.999997f, + 0.999997f, 0.999997f, 0.999997f, 0.999998f, 0.999998f, 0.999998f, 0.999998f, 0.999998f, + 0.999998f, 0.999999f, 0.999999f, 0.999999f, 0.999999f, 0.999999f, 0.999999f, 0.999999f, + 0.999999f, 0.999999f, 0.999999f, 0.999999f, 0.999999f, 0.999999f, 1.000000f, 1.000000f, + 1.000000f, 1.000000f, 1.000000f, 1.000000f, 1.000000f, 1.000000f, 1.000000f, 1.000000f, + 1.000000f + }; + + private static float tansigApproximated(float x) { + // Tests are reversed to catch NaNs. + if (!(x < 8.0f)) { + return 1.0f; + } + if (!(x > -8.0f)) { + return -1.0f; + } + float sign = 1.0f; + if (x < 0.0f) { + x = -x; + sign = -1.0f; + } + int i = (int) Math.floor(0.5f + 25 * x); + float y = TANSIG_TABLE[i]; + // Newton step back to x's own scale (undoing the table's factor of 25). + x -= 0.04f * i; + y = y + x * (1.0f - y * y) * (1.0f - y * x); + return sign * y; + } + + private static float sigmoidApproximated(float x) { + return 0.5f + 0.5f * tansigApproximated(0.5f * x); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/RnnSpeechDetector.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/RnnSpeechDetector.java new file mode 100644 index 0000000..d46015b --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/RnnSpeechDetector.java @@ -0,0 +1,145 @@ +package eu.lixko.ts3j.client.audio.vad; + +import eu.lixko.ts3j.client.audio.SpeechProbabilityDetector; + +/** + * {@link SpeechProbabilityDetector} backed by {@link RnnVad}, adapting an arbitrary + * capture rate and frame size to the detector's fixed 10 ms frames at 24 kHz. + * + *

    Capture frames rarely divide into 10 ms chunks exactly, so leftover samples are + * carried into the next call. The reported probability is that of the most recent complete + * 10 ms frame; a capture frame long enough to span several of them advances the + * detector several times, exactly as feeding it directly would. + */ +public final class RnnSpeechDetector implements SpeechProbabilityDetector { + + /** Half-band FIR used when decimating; long enough to keep aliasing out of the passband. */ + private static final int FILTER_TAPS = 32; + + private final RnnVad vad = new RnnVad(); + + private final int sampleRate; + private final boolean decimateByTwo; + private final float[] filterCoeffs; + private final float[] filterState; + private int filterPos; + + /** Resampled samples not yet consumed as a whole 10 ms frame. */ + private final float[] pending = new float[RnnVad.FRAME_SIZE]; + private int pendingCount; + + /** Fractional read position, for capture rates that are not a multiple of 24 kHz. */ + private double resamplePos; + + public RnnSpeechDetector(int sampleRate) { + this.sampleRate = sampleRate; + this.decimateByTwo = sampleRate == 2 * RnnVad.SAMPLE_RATE; + if (decimateByTwo) { + this.filterCoeffs = lowPass(FILTER_TAPS, 0.25); + this.filterState = new float[FILTER_TAPS]; + } else { + this.filterCoeffs = null; + this.filterState = null; + } + } + + @Override + public double process(float[] frame, int length) { + if (sampleRate == RnnVad.SAMPLE_RATE) { + feed(frame, 0, length, 1); + } else if (decimateByTwo) { + decimateAndFeed(frame, length); + } else { + resampleAndFeed(frame, length); + } + return vad.probability(); + } + + @Override + public double probability() { + return vad.probability(); + } + + @Override + public void reset() { + vad.reset(); + pendingCount = 0; + resamplePos = 0; + filterPos = 0; + if (filterState != null) { + java.util.Arrays.fill(filterState, 0.0f); + } + } + + /** See {@link RnnVad#resetNetwork()}. */ + public void resetNetwork() { + vad.resetNetwork(); + } + + /** Appends samples (taking every {@code step}-th) and runs the detector per full frame. */ + private void feed(float[] src, int offset, int length, int step) { + for (int i = offset; i < offset + length; i += step) { + push(src[i]); + } + } + + /** 48 kHz (the common case): low-pass, then keep every other sample. */ + private void decimateAndFeed(float[] frame, int length) { + for (int i = 0; i < length; i++) { + filterState[filterPos] = frame[i]; + filterPos = (filterPos + 1) % FILTER_TAPS; + if ((i & 1) == 1) { + float acc = 0; + int idx = filterPos; + for (int t = 0; t < FILTER_TAPS; t++) { + acc += filterCoeffs[t] * filterState[idx]; + idx = (idx + 1) % FILTER_TAPS; + } + push(acc); + } + } + } + + /** + * Any other capture rate. Linear interpolation is enough here: the detector's own + * analysis is far coarser than the resampling error. + */ + private void resampleAndFeed(float[] frame, int length) { + double ratio = (double) sampleRate / RnnVad.SAMPLE_RATE; + while (resamplePos < length) { + int i = (int) resamplePos; + double frac = resamplePos - i; + float a = frame[i]; + float b = frame[Math.min(i + 1, length - 1)]; + push((float) ((1 - frac) * a + frac * b)); + resamplePos += ratio; + } + resamplePos -= length; + } + + private void push(float sample) { + pending[pendingCount++] = sample; + if (pendingCount == RnnVad.FRAME_SIZE) { + vad.process(pending, 0); + pendingCount = 0; + } + } + + /** Windowed-sinc low-pass with the given normalised cutoff, scaled to unit DC gain. */ + private static float[] lowPass(int taps, double cutoff) { + float[] h = new float[taps]; + double centre = (taps - 1) / 2.0; + double sum = 0; + for (int i = 0; i < taps; i++) { + double t = i - centre; + double sinc = (t == 0) ? 2 * cutoff : Math.sin(2 * Math.PI * cutoff * t) / (Math.PI * t); + double window = 0.54 - 0.46 * Math.cos(2 * Math.PI * i / (taps - 1)); // Hamming + h[i] = (float) (sinc * window); + sum += h[i]; + } + for (int i = 0; i < taps; i++) { + h[i] /= (float) sum; + } + return h; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/RnnVad.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/RnnVad.java new file mode 100644 index 0000000..4cd601a --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/RnnVad.java @@ -0,0 +1,111 @@ +package eu.lixko.ts3j.client.audio.vad; + +import static eu.lixko.ts3j.client.audio.vad.VadConstants.BUF_SIZE_24K; +import static eu.lixko.ts3j.client.audio.vad.VadConstants.FEATURE_VECTOR_SIZE; +import static eu.lixko.ts3j.client.audio.vad.VadConstants.FRAME_10MS_24K; +import static eu.lixko.ts3j.client.audio.vad.VadConstants.FRAME_20MS_24K; +import static eu.lixko.ts3j.client.audio.vad.VadConstants.MAX_PITCH_24K; +import static eu.lixko.ts3j.client.audio.vad.VadConstants.NUM_LPC_COEFFICIENTS; + +/** + * WebRTC's {@code rnn_vad} speech-probability detector, ported to Java. + * + *

    This is the detector the TeamSpeak 3 client uses for its "Automatic" and "Hybrid" + * voice-activation modes: TS3 links the same network with byte-identical weights, so at a + * given threshold this gates on the same frames theirs does. + * + *

    Feed exactly {@link VadConstants#FRAME_10MS_24K} samples of 24 kHz mono audio in + * [-1, 1] per call, in order. Combines {@code features_extraction.cc} and {@code rnn.cc}. + */ +public final class RnnVad { + + /** Samples per call: 10 ms at 24 kHz. */ + public static final int FRAME_SIZE = FRAME_10MS_24K; + + /** Sample rate this detector expects. */ + public static final int SAMPLE_RATE = VadConstants.SAMPLE_RATE_24K; + + /** + * WebRTC's audio processing carries float samples on the 16-bit integer scale, and the + * network's thresholds (the silence cut-off, the pitch energy floor) are calibrated for + * it. Callers pass [-1, 1], so scale on the way in. + */ + private static final float INT16_SCALE = 32768.0f; + + /** + * Rolling window of 24 kHz samples: one maximum pitch period of history followed by + * the most recent 20 ms. + */ + private final float[] pitchBuffer = new float[BUF_SIZE_24K]; + private final float[] lpResidual = new float[BUF_SIZE_24K]; + private final float[] lpcCoeffs = new float[NUM_LPC_COEFFICIENTS]; + private final float[] featureVector = new float[FEATURE_VECTOR_SIZE]; + + private final LinearPrediction linearPrediction = new LinearPrediction(); + private final PitchEstimator pitchEstimator = new PitchEstimator(); + private final SpectralFeatures spectralFeatures = new SpectralFeatures(); + private final RnnNetwork network = new RnnNetwork(); + + private float probability; + private int pitchPeriod48k; + + /** Clears all history. Call on a capture discontinuity. */ + public void reset() { + java.util.Arrays.fill(pitchBuffer, 0.0f); + pitchEstimator.reset(); + pitchPeriod48k = 0; + spectralFeatures.reset(); + network.reset(); + probability = 0.0f; + } + + /** + * Clears only the network's recurrent state, keeping the feature history. AGC2 does this + * every 1.5 s so its detector cannot latch. + */ + public void resetNetwork() { + network.reset(); + } + + /** Speech probability in [0, 1] from the most recent {@link #process} call. */ + public float probability() { + return probability; + } + + /** + * Pitch period of the most recent frame, expressed at 48 kHz as the network's + * feature is. Exposed for diagnostics and tests. + */ + public int pitchPeriod48kHz() { + return pitchPeriod48k; + } + + /** + * Analyses one 10 ms frame and returns the speech probability in [0, 1]. + * + * @param frame mono samples in [-1, 1] + * @param offset index of the first sample + */ + public float process(float[] frame, int offset) { + System.arraycopy(pitchBuffer, FRAME_10MS_24K, pitchBuffer, 0, BUF_SIZE_24K - FRAME_10MS_24K); + int start = BUF_SIZE_24K - FRAME_10MS_24K; + for (int i = 0; i < FRAME_10MS_24K; i++) { + pitchBuffer[start + i] = frame[offset + i] * INT16_SCALE; + } + + // Search the pitch on the whitened signal so formants don't dominate the peak. + linearPrediction.computeLpcCoefficients(pitchBuffer, lpcCoeffs); + LinearPrediction.computeLpResidual(lpcCoeffs, pitchBuffer, lpResidual); + pitchPeriod48k = pitchEstimator.estimate(lpResidual); + // Normalisation based on the training-set statistics. + featureVector[FEATURE_VECTOR_SIZE - 2] = 0.01f * (pitchPeriod48k - 300); + + // Compare the most recent 20 ms against the 20 ms one pitch period earlier. + int laggedOffset = MAX_PITCH_24K - pitchPeriod48k / 2; + boolean silence = spectralFeatures.checkSilenceComputeFeatures( + pitchBuffer, BUF_SIZE_24K - FRAME_20MS_24K, pitchBuffer, laggedOffset, featureVector); + + probability = network.computeVadProbability(featureVector, silence); + return probability; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/RnnVadWeights.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/RnnVadWeights.java new file mode 100644 index 0000000..80a7abb --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/RnnVadWeights.java @@ -0,0 +1,273 @@ +package eu.lixko.ts3j.client.audio.vad; + +/** + * Quantised weights of WebRTC's {@code rnn_vad} network, copied verbatim from + * {@code third_party/rnnoise/src/rnn_vad_weights.cc} (BSD, Xiph/Jean-Marc Valin). + * + *

    These are the same 4585 bytes the TeamSpeak 3 client links in, so our detector + * produces the same speech probabilities theirs does. + * + *

    Values are stored quantised; {@link #SCALE} converts them to float. + */ +final class RnnVadWeights { + + /** Dequantisation factor applied to every table below. */ + static final float SCALE = 1.0f / 256.0f; + + /** FC1 weights, laid out as [input][output] (42 x 24). */ + static final byte[] INPUT_DENSE_WEIGHTS = { + -10, 0, -3, 1, -8, -6, 3, -13, 1, 0, -3, -7, -5, -3, 6, -1, -6, 0, -6, -4, -1, -2, 1, 1, -7, 2, + 21, 10, -5, -20, 24, 23, 37, 8, -2, 33, -6, 22, 13, -2, 50, 8, 13, 1, -15, 30, -10, 30, 0, 3, 5, + 27, 1, 4, -3, 41, 56, 35, -2, 49, -13, 11, 13, -2, -47, 5, -16, -60, -15, 77, -17, 26, -3, 14, + -21, 19, -5, -19, -13, 0, 10, 14, 9, 31, -13, -41, -10, 4, 22, 18, -48, -6, -10, 62, -3, -18, + -14, 12, 26, -28, 3, 14, 25, -13, -19, 6, 5, 36, -3, -65, -12, 0, 31, -7, -9, 101, -4, 26, 16, + 17, -12, -12, 14, -36, -3, 5, -15, 21, 2, 30, -3, 38, -4, 1, -6, 7, -7, 14, 38, -22, -30, -3, + -7, 3, -39, -70, -126, 25, 34, 94, -67, -22, -33, 83, -47, -118, 4, 70, 33, 25, 62, -128, -76, + -118, -113, 49, -12, -100, -18, -114, -33, 43, 32, 61, 40, -9, -106, 2, 36, -100, -40, -5, 20, + -75, 61, -51, -9, 126, -27, -52, 5, -24, -21, -126, -114, -12, 15, 106, -2, 73, -125, 50, 13, + -120, 35, 35, 4, -61, 29, -124, 6, -53, -69, -125, 64, -89, 36, -107, -103, -7, 27, 121, 69, 77, + -35, 35, 95, -125, -49, 97, -45, -43, -23, 23, -28, -65, -118, 2, 8, -126, 27, -97, 92, 5, 55, + 82, 17, -57, -115, 37, 8, -106, -46, 41, -2, 21, -44, 8, -73, -58, -39, 34, 89, -95, 95, -117, + 120, -58, 31, 123, 1, -32, -109, -110, 60, -120, -43, -74, 5, 91, 26, 21, 114, 82, -83, -126, + 123, 22, -16, -67, 25, -83, 46, 48, -34, -121, -124, -63, -35, -9, 31, 82, 123, 6, -3, 117, 93, + -2, -13, -36, 124, -112, -6, -102, -5, -33, -15, 44, -69, -127, -23, -40, -34, -85, 68, 83, -1, + 40, 8, 84, 118, -58, -55, -102, 123, -55, -14, -123, 44, -63, -14, 21, 35, 16, 24, -126, -13, + -114, 35, 20, -36, 61, -9, 97, 34, 19, -32, -109, 76, -104, 99, -119, 45, -125, -51, -28, -8, + -69, -8, 125, -45, -93, 113, 103, -41, -82, 52, 7, 126, 0, -40, 104, 55, -58, 17, -124, -93, + -58, 8, -45, 1, 56, -123, 108, -47, -23, 115, 127, 17, -68, -13, 116, -82, -44, 45, 67, -120, + -101, -15, -125, 120, -113, 17, -48, -73, 126, -64, -86, -118, -19, 112, -1, -66, -27, -62, 121, + -86, -58, 50, 89, -38, -75, 95, -111, 12, -113, 2, -68, 2, -94, -121, 91, -5, 0, 79, 43, -7, + -18, 79, 35, -38, 47, 1, -45, 83, -50, 102, 32, 55, -96, 15, -122, -69, 45, -27, 91, -62, -30, + 46, -95, 22, -72, -97, -1, 14, -122, 28, 127, 61, -126, 121, 9, 68, -120, 49, -60, 90, 3, 43, + 68, 54, 34, -10, 28, 21, -24, -54, 22, -113, -12, 82, -2, -17, -9, 127, 8, 116, -92, 0, -70, + -33, 123, 66, 116, -74, -4, 74, -72, -22, -47, 1, -83, -60, -124, 1, 122, -57, -43, 49, 40, + -126, -128, -8, -29, 28, -24, -123, -121, -70, -93, -37, -126, 11, -125, -37, 11, -31, -51, + -124, 116, -128, 8, -25, 109, 75, -12, 7, 8, 10, 117, 124, -128, -128, 29, -26, 101, 21, -128, + 87, 8, -39, 23, -128, 127, -127, 74, -55, 74, 112, 127, 4, 55, 44, -92, 123, 34, -93, 47, -21, + -92, 17, 49, -121, 92, 7, -126, -125, 124, -74, 3, -59, 18, -91, 3, -9, 9, 56, 116, 7, -29, 33, + 87, -21, -128, -13, 57, 74, 9, -29, -61, -97, -21, -95, -12, -114, 16, 82, 125, -7, 10, -24, 9, + 77, -128, -102, -25, 3, -126, 10, 13, -18, 51, 26, 127, -79, 35, 51, 12, -50, -24, 1, -7, 22, + 81, 65, 120, -30, -38, 85, 122, -4, -106, -11, 27, 53, 41, 8, -104, -66, -38, -124, 10, 12, 76, + 117, -109, 9, 11, 2, -18, 3, 113, -16, -79, -39, -123, -20, -128, 2, 13, -33, -58, 10, 84, -104, + 13, 64, 109, 1, 54, -12, 28, 24, 63, -126, 118, -82, 46, -12, -15, 14, -43, 60, 22, -32, -19, + -46, 91, -107, 24, -94, 26, -47, 125, 6, 58, -15, -75, -26, -38, -35, 103, -16, -17, -13, 63, + -2, 45, -45, -73, -23, 70, -87, 51, -17, 53, 76, 14, -18, -31, -14, 103, 8, 21, -28, -33, -20, + -47, 6, 39, 40, -30, 7, -76, 55, 31, -20, -21, -59, 1, 25, -11, 17, 5, -13, -39, 0, -76, 50, + -33, -29, -50, -16, -11, -12, -1, -46, 40, -10, 65, -19, 21, -41, -32, -83, -19, -4, 49, -60, + 118, -24, -46, 9, 102, -20, 8, -19, 25, 31, -3, -37, 0, 25, 7, 29, 2, -39, 127, -64, -20, 64, + 115, -30, 36, 100, 35, 122, 127, 127, -127, 127, -127, 19, 127, -89, -79, -32, 39, -127, 125, + -80, 126, -127, 26, 8, 98, -8, -57, -90, -50, 126, 61, 127, -126, 40, -106, -68, 104, -125, + -119, 11, 10, -127, 66, -56, -12, -126, -104, 27, 75, 38, -124, -126, -125, 84, -123, -45, -114, + -128, 127, 103, -101, -124, 127, -11, -23, -123, 92, -123, 24, 126, 41, -2, -39, -27, -94, 40, + -112, -48, 127, 58, 14, 38, -75, -64, 73, 117, 100, -119, -11, 6, 32, -126, -14, 35, 121, -10, + 54, -60, 89, -3, 69, -25, -20, 43, -86, -34, 24, 27, 7, -81, -99, -23, -16, -26, 13, 35, -97, + 80, -29, -13, -121, -12, -65, -94, 70, -89, -126, -95, 88, 33, 96, 29, -90, 69, 114, -78, 65, + 90, -47, -47, 89, 1, -12, 3, 8, 30, 5, 2, -30, -1, 6, -7, 10, -4, 46, -27, -40, 22, -6, -17, 45, + 24, -9, 23, -14, -63, -26, -12, -57, 27, 25, 55, -76, -47, 21, 34, 33, 26, 17, 14, 6, 9, 26, 25, + -25, -25, -18 + }; + + /** FC1 bias (24). */ + static final byte[] INPUT_DENSE_BIAS = { + 38, -6, 127, 127, 127, -43, -127, 78, 127, 5, 127, 123, 127, 127, -128, -76, -126, 28, 127, 125, + -30, 127, -89, -20 + }; + + /** GRU1 input weights, [input][gate][output] (24 x 3 x 24). */ + static final byte[] HIDDEN_GRU_WEIGHTS = { + -124, 23, -123, -33, -95, -4, 8, -84, 4, 101, -119, 116, -4, 123, 103, -51, 29, -124, -114, -49, + 31, 9, 75, -128, 0, -49, 37, -50, 46, -21, -63, -104, 54, 82, 33, 21, 70, 127, -9, -79, -39, + -23, -127, 107, 122, -96, -46, -18, -39, 13, -28, -48, 14, 56, -52, 49, -1, -121, 25, -18, -36, + -52, -57, -30, 54, -124, -26, -47, 10, 39, 12, 2, 9, -127, -128, 102, 21, 11, -64, -71, 89, + -113, -111, 54, 31, 94, 121, -40, 30, 40, -109, 73, -9, 108, -92, 2, -127, 116, 127, 127, -122, + 95, 127, -37, -127, 28, 89, 10, 24, -104, -62, -67, -14, 38, 14, -71, 22, -41, 20, -50, 39, 63, + 86, 127, -18, 79, 4, -51, 2, 33, 117, -113, -78, 56, -91, 37, 34, -45, -44, -22, 21, -16, 56, + 30, -84, -79, 38, -74, 127, 9, -25, 2, 82, 61, 25, -26, 26, 11, 117, -65, 12, -58, 42, -62, -93, + 11, 11, 124, -123, 80, -125, 11, -90, 42, 94, 4, -109, -1, 85, -52, 45, -26, -27, 77, -5, 30, + 90, 0, 95, -7, 53, 29, -82, 22, -9, 74, 2, -12, -73, 114, 97, -64, 122, -77, 43, 91, 86, 126, + 106, 72, 90, -43, 46, 96, -51, 21, 22, 68, 22, 41, 79, 75, -46, -105, 23, -116, 127, -123, 102, + 57, 85, 10, -29, 34, 125, 126, 124, 81, -15, 54, 96, -128, 39, -124, 103, 74, 126, 127, -50, + -71, -122, -64, 93, -75, 71, 105, 122, 123, 126, 122, -127, 33, -63, -74, 124, -71, 33, 41, -56, + 19, 6, 65, 41, 90, -116, -3, -46, 75, -13, 98, -74, -42, 74, -95, -96, 81, 24, 32, -19, -123, + 74, 55, 109, 115, 0, 32, 33, 12, -20, 9, 127, 127, -61, 79, -48, -54, -49, 101, -9, 27, -106, + 74, 119, 77, 87, -126, -24, 127, 124, 31, 34, 127, 40, 3, -90, 127, 23, 57, -53, 127, -69, -88, + -33, 127, 19, -46, -9, -125, 13, -126, -113, 127, -41, 46, 106, -62, 3, -10, 111, 49, -34, -24, + -20, -112, 11, 101, -50, -34, 50, 65, -64, -106, 70, -48, 60, 9, -122, -45, 15, -112, -26, -4, + 1, 39, 23, 58, -45, -80, 127, 82, 58, 30, -94, -119, 51, -89, 95, -107, 30, 127, 125, 58, -52, + -42, -38, -20, -122, 115, 39, -26, 5, 73, 13, -39, 43, -23, -20, -125, 23, 35, 53, -61, -66, 72, + -20, 33, 8, 35, 4, 7, 18, 19, 16, -45, -50, -71, 31, -29, -41, -27, 10, 14, 27, 9, -23, 98, 6, + -94, 92, 127, -114, 59, -26, -100, -62, -127, -17, -85, -60, 126, -42, -6, 33, -120, -26, -126, + -127, -35, -114, -31, 25, -126, -100, -126, -64, -46, -31, 30, 25, -74, -111, -97, -81, -104, + -114, -19, -9, -116, -69, 22, 30, 59, 8, -51, 16, -97, 18, -4, -89, 80, -50, 3, 36, -67, 56, 69, + -26, 107, -10, 58, -28, -4, -57, -72, -111, 0, -75, -119, 14, -75, -49, -66, -49, 8, -121, 22, + -54, 121, 30, 54, -26, -126, -123, 56, 5, 48, 21, -127, -11, 23, 25, -82, 6, -25, 119, 78, 4, + -104, 27, 61, -48, 37, -13, -52, 50, -50, 44, -1, -22, -43, -59, -78, -67, -32, -26, 9, -3, 40, + 16, 19, 3, -9, 20, -6, -37, 28, 39, 17, -19, -10, 1, 6, -59, 74, 47, 3, -119, 0, -128, -107, + -25, -22, -69, -23, -111, -42, -93, -120, 90, -85, -54, -118, 76, -79, 124, 101, -77, -75, -17, + -71, -114, 68, 55, 79, -1, -123, -20, 127, -65, -123, -128, -87, 123, 9, -115, -14, 7, -4, 127, + -79, -115, 125, -28, 89, -83, 49, 89, 119, -69, -5, 12, -49, 60, 57, -24, -99, -110, 76, -83, + 125, 73, 81, 11, 8, -45, 1, 83, 13, -70, -2, 97, 112, -97, 53, -9, -94, 124, 44, -49, -24, 52, + 76, -110, -70, -114, -12, 72, -4, -114, 43, -43, 81, 102, -84, -27, 62, -40, 52, 58, 124, -35, + -51, -123, -43, 56, -75, -34, -35, -106, 93, -43, 14, -16, 46, 62, -97, 21, 30, -53, 21, -11, + -33, -20, -95, 4, -126, 12, 45, 20, 108, 85, 11, 20, -40, 99, 4, -25, -18, -23, -12, -126, -55, + -20, -44, -51, 91, -127, 127, -44, 7, 127, 78, 38, 125, -6, -94, -103, 73, 126, -126, 18, 59, + -46, 106, 76, 116, -31, 75, -4, 92, 102, 32, -31, 73, 42, -21, -28, 57, 127, -8, -107, 115, 124, + -94, -4, -128, 29, -57, 70, -82, 50, -13, -44, 38, 67, -93, 6, -39, -46, 56, 68, 27, 61, 26, 18, + -72, 127, 22, 18, -31, 127, 61, -65, -38, 1, -67, -1, 8, -73, 46, -116, -94, 58, -49, 71, -40, + -63, -82, -20, -60, 93, 76, 69, -106, 34, -31, 4, -25, 107, -18, 45, 4, -61, 126, 54, -126, + -125, 41, 19, 44, 32, -98, 125, -24, 125, -96, -125, 15, 87, -4, -90, 18, -40, 28, -69, 67, 22, + 41, 39, 7, -48, -44, 12, 69, -13, 2, 44, -38, 111, -7, -126, -22, -9, 74, -128, -36, -7, -123, + -15, -79, -91, -37, -127, -122, 104, 30, 7, 98, -37, 111, -116, -47, 127, -45, 118, -111, -123, + -120, -77, -64, -125, 124, 77, 111, 77, 18, -113, 117, -9, 67, -77, 126, 49, -20, -124, 39, 41, + -124, -34, 114, -87, -126, 98, -20, 59, -17, -24, 125, 107, 54, 35, 33, -44, 12, -29, 125, -71, + -28, -63, -114, 28, -17, 121, -36, 127, 89, -122, -49, -18, -48, 17, 24, 19, -64, -128, 13, 86, + 45, 13, -49, 55, 84, 48, 80, -39, 99, -127, 70, -33, 30, 50, 126, -65, -117, -13, -20, -24, 127, + 115, -72, -104, 63, 126, -42, 57, 17, 46, 21, 119, 110, -100, -60, -112, 62, -33, 28, 26, -22, + -60, -33, -54, 78, 25, 32, -114, 86, 44, 26, 43, 76, 121, 19, 97, -2, -3, -73, -68, 6, -116, 6, + -43, -97, 46, -128, -120, -31, -119, -29, 16, 16, -126, -128, -126, -46, -9, -3, 92, -31, -76, + -126, -3, -107, -12, -23, -69, 5, 51, 27, -42, 23, -70, -128, -29, 22, 29, -126, -55, 50, -71, + -3, 127, 44, -27, -70, -63, -66, -70, 104, 86, 115, 29, -92, 41, -90, 44, -11, -28, 20, -11, + -63, -16, 43, 31, 17, -73, -31, -1, -17, -11, -39, 56, 18, 124, 72, -14, 28, 69, -121, -125, 34, + 127, 63, 86, -80, -126, -125, -124, -47, 124, 77, 124, -19, 23, -7, -50, 96, -128, -93, 102, + -53, -36, -87, 119, -125, 92, -126, 118, 102, 72, -2, 125, 10, 97, 124, -125, 125, 71, -20, -47, + -116, -121, -4, -9, -32, 79, -124, -36, 33, -128, -74, 125, 23, 127, -29, -115, -32, 124, -89, + 32, -107, 43, -17, 24, 24, 18, 29, -13, -15, -36, 62, -91, 4, -41, 95, 28, -23, 6, 46, 84, 66, + 77, 68, -70, -1, -23, -6, 65, 70, -21, 9, 77, -12, 2, -118, 4, 9, -108, 84, 52, 2, 52, 13, -10, + 58, -110, 18, 66, -95, -23, 70, 31, -3, 56, 56, -3, -7, 1, -27, -48, -61, 41, -4, 10, -62, 32, + -7, -24, 9, -48, -60, -4, 79, -20, -38, -76, 68, -49, -97, 0, -15, 5, -100, -49, -95, -99, -115, + -9, -40, 10, 104, 13, 56, 127, -27, -109, -94, -118, -102, -44, -85, 52, 127, -4, 14, 62, 121, + -122, -26, -79, -42, -34, 1, 25, -38, -79, -58, -31, -31, -90, -30, -123, 32, -56, 125, 66, 124, + -1, 3, 91, -103, -7, 23, 78, -18, 9, 69, -69, 76, -38, -33, -2, -98, 18, 106, 84, 55, 87, -47, + 35, -124, 64, 41, -14, 46, 25, -2, 120, -21, 82, 19, -79, -37, -3, -8, -16, 21, 19, -5, -28, + -112, 39, -6, -30, 53, -69, 53, 46, 127, 123, 78, 20, 28, -7, 73, 72, 17, -40, 41, 111, 57, 32, + -95, 29, 28, -39, -65, 54, -20, -63, 29, -67, 3, 44, -57, -47, 11, 61, -22, -44, 61, 48, -100, + 20, 125, 96, -24, -16, 3, -69, -126, 74, -125, 9, 45, -67, -123, -59, -72, 118, 69, 45, 50, -57, + 67, 13, -66, -106, 47, 62, 22, -1, -22, -25, -40, -125, 3, 125, 32, 102, -56, -25, -75, -30, + 122, 60, -13, 36, -73, 7, -84, 124, 40, -118, 17, -87, -118, -8, 3, -27, 111, -40, 40, -51, 127, + 125, -45, -30, -54, 46, 80, -1, -30, 101, -17, 18, 26, 54, 7, -12, 1, -127, 123, -122, -27, -75, + 64, 10, 25, -15, -44, 127, -127, 5, -84, -81, -7, 19, -26, 126, 15, 116, -126, 14, -76, 44, 62, + -110, -124, 125, -29, -87, -3, -69, 82, 90, 57, -123, 123, 100, -19, -51, -32, 69, 37, -57, + -128, -124, -72, -13, 51, -7, -45, -73, 5, 99, -26, -117, -96, -109, 4, -31, -12, 0, 31, -42, + -27, 12, -81, 118, 39, 83, 14, 41, -126, 107, -82, 94, -116, -122, -47, -109, -84, -128, -35, + -56, 66, 8, -65, 19, 42, -46, -72, -109, 41, 43, -127, -113, 58, 127, 42, -75, -1, 65, 117, -55, + -113, -123, 124, 43, -96, -115, -19, 68, 15, 94, 3, 75, 0, 34, 9, 42, 110, -48, 92, -76, 99, + -17, 27, 32, 13, 125, 50, -17, 56, 4, 53, 34, -8, 99, 80, -126, -21, -65, -11, -46, 44, -81, -3, + -121, 123, 66, -81, -84, 119, 127, 84, 105, 45, -66, -42, -23, 32, -25, 12, 111, 127, 88, 125, + 30, 24, -127, -9, -54, 127, -116, -119, 88, 70, 94, -120, 35, -93, 15, 22, -21, 25, -110, -123, + -45, 8, -109, 125, -122, -86, -126, 8, -14, -120, -45, -45, 69, -125, -122, 6, 81, 86, 125, 95, + 54, 77, 54, -123, 126, -85, -117, 56, 11, 0, -61, -91, -12, -2, -113, -3, -15, -122, -63, -91, + 10, 84, -111, 125, 93, 21, 62, -78, -116, 13, -57, 28, -124, 126, 110, 12, 15, 95, 15, -19, + -125, -97, 52, -7, 101, 9, 20, -125, -26, -56, 72, 77, 12, -126, 22, -29, 47, 62, 95, 112, 69, + 32, 97, -83, -8, -5, 67, -63, -123, 79, 59, 0, -6, -17, 4, -111, -52, 27, 65, 0 + }; + + /** GRU1 recurrent weights, same layout (24 x 3 x 24). */ + static final byte[] HIDDEN_GRU_RECURRENT_WEIGHTS = { + 65, 83, 35, 56, 24, -34, -28, -2, 125, 19, 42, -9, 124, -53, 24, -87, 11, 35, -81, -35, -125, + -31, 123, -21, 33, -91, 113, -93, 45, -6, 53, 38, -92, 8, -27, 87, 4, 43, 43, 10, -128, -128, + -46, 127, -38, -45, 25, -87, 19, 5, 52, -96, -23, -29, 121, -126, -24, -20, -2, 69, -50, 6, 71, + -81, -125, 90, -94, 1, -38, 36, 89, 17, -60, 71, -48, 18, -15, 44, -18, 59, 11, 114, -51, 32, + 110, 1, 4, 109, -24, 127, 27, 60, 88, 24, 45, -59, 75, -36, 8, 57, -32, -25, 13, 126, -89, -61, + -76, 127, 18, -62, -68, 23, -113, 5, 126, 43, -88, 26, -78, 18, 75, 21, 9, -74, 20, 41, 126, + -118, -15, 9, 116, 126, -127, 34, -6, 126, -128, -53, -54, -55, -121, 70, 127, -12, -68, 82, + -25, 104, -126, 126, -21, -26, 124, -75, -127, -120, 13, 61, -64, -108, -63, -65, -44, -35, -61, + -39, 109, -74, 113, -3, 108, -30, 125, 120, 39, 125, -128, -95, -99, 111, 9, 25, 114, -75, -92, + -54, -12, -32, -38, 10, 31, 10, 63, 51, 40, -99, 74, 4, 50, -128, -36, -35, -11, -28, -126, -7, + 66, -58, -126, -22, -83, -61, -127, 49, 126, -8, 7, 62, 36, -11, -32, -44, 63, 116, 41, 65, + -127, 126, 63, -30, -96, 74, -92, 127, 38, -18, -128, 68, -5, 101, -4, 85, 58, 79, 0, -58, 8, + 119, -70, -1, -79, -68, 114, -28, -90, -6, -112, 2, 127, -8, 10, 55, -59, -126, 127, 125, 80, + 72, 35, -54, 95, -124, -124, 79, 23, -46, -61, -127, -100, 99, -77, 8, -87, 5, -2, 49, 85, 7, + -71, 82, 53, -41, 22, -22, -93, -103, 6, 52, -56, 14, -8, -111, 85, 16, 54, 32, -118, -24, 61, + -53, 96, -70, -5, -17, -67, -84, -7, -82, -107, -96, 21, -83, -58, 50, 12, -126, -1, -28, 34, + -126, 115, 17, 91, 1, -127, 72, 11, 126, -81, 6, 96, -8, 77, 15, -6, 63, -27, 20, -123, -109, + 85, -79, -17, 126, -92, 2, -61, 20, 14, 17, 121, 123, 30, 57, 120, 127, 57, 42, 117, 98, 67, 39, + -20, -70, 100, 7, 125, 122, 40, 16, -79, 125, 83, 41, -106, -57, 24, 55, 27, -66, -111, -44, -7, + -43, -66, 121, 42, -128, -45, 35, 15, -127, 34, -35, -34, -40, -18, -6, 63, 111, 31, 116, 127, + 19, 24, -71, -39, 34, 11, 19, -40, 27, 12, 106, -10, 56, -82, -106, -2, -50, -52, 114, -126, + -34, -43, -68, 10, 76, 57, -118, -128, 37, -104, 76, 125, 3, -76, 127, -29, 84, -94, -15, 55, + 125, 79, 127, -57, -125, 104, -68, 126, 126, -77, 51, 45, 33, -109, 115, -11, 1, 95, -121, -5, + -9, -126, -114, 39, 68, -126, -107, -51, -42, 24, -8, 51, -27, -43, 66, -45, 62, -98, -109, 69, + 67, 0, -125, -128, 49, 31, 126, -122, 2, -55, -67, -126, -70, -128, -125, -77, 25, 16, -8, -102, + 11, -75, 82, 38, -5, 5, 19, 34, 47, -127, -93, 21, 24, -97, -18, 31, 39, 34, -20, 22, 123, 7, + -77, -81, -46, -9, 1, 23, 39, -127, -43, -8, -50, 10, -21, 59, -9, -4, -13, -27, 44, 127, 52, + -47, 70, -43, 52, 101, -49, 27, 45, 49, 33, -125, 55, 114, 20, -1, 76, -24, -96, 105, 24, 126, + 75, -21, -105, 13, -42, 40, 126, -30, -39, -95, 125, -63, 11, 6, 125, 125, -14, 5, 42, -61, -4, + 49, 88, 6, -107, -28, 19, -29, 47, 126, 6, -46, -89, -18, 91, -20, -6, 118, -21, -22, 39, 115, + 11, -42, 54, 73, -55, -77, 62, -27, -59, -99, -12, -127, -40, 56, -3, -124, -91, 71, -111, 6, + -19, 82, -24, -35, 102, -42, 7, -126, -126, -125, 18, 98, -52, 127, 105, -52, 40, -83, 126, + -122, 109, 5, 127, 48, 6, 5, -125, 100, -16, 29, 85, -89, 8, 4, 41, 62, -127, 62, 122, 85, 122, + -107, 8, -125, 93, -127, 127, 102, 19, 19, -66, 41, -42, 114, 127, -48, -117, -29, -6, -73, + -102, -3, -19, 0, 88, 42, 87, -117, -20, 2, 122, 28, 63, 71, 66, 120, 93, 124, -43, 49, 103, 31, + 90, -91, -22, -126, 26, -24, -21, 51, -126, 87, -103, -69, -10, -66, -23, 20, 97, 36, 25, -127, + 30, -20, -63, 30, 51, -116, 23, 40, -39, 36, -83, -77, -25, -50, 110, 14, 13, -109, 125, -65, + -55, -87, 124, -126, -32, -72, -108, 127, 127, -125, -124, 61, 121, 102, -128, -127, 16, 100, + 127, -124, -68, 72, -93, -128, 43, -93, -19, -125, -97, -113, -33, 83, 127, -44, 127, -75, 127, + 16, 44, 50, -122, 23, 118, 46, 19, 26, -128, 10, 4, 99, -14, -82, -13, 30, 125, 57, 65, 60, -71, + 35, 98, 28, 7, 1, 43, 89, 70, 75, 121, -59, 82, -126, -53, -16, -116, -65, 52, -52, 0, 80, 35, + 45, -61, 46, 8, 107, 27, -26, -118, 90, 57, -10, 7, -15, 0, -39, -4, 12, 29, -1, 116, 84, 79, + 119, 125, -59, 28, -6, -25, -43, 2, 90, 79, 67, 103, -82, 2, -6, 125, 19, 73, 0, -105, 112, -17, + 104, 107, 124, 106, 19, 56, -44, 55, -112, 6, -39, -83, 126, -93, -98, 57, -120, -23, -38, 2, + -31, -48, 106, 127, 127, 69, 16, 110, 71, 104, 62, -12, -22, 42, -37, -94, 34, -1, -32, -12, + -124, -47, -13, 60, -75, -66, 58, -127, -2, 64, 76, -106, 73, -49, -31, 127, 126, 31, 16, 127, + -110, 107, -16, -53, 20, 69, -14, -125, 59, -44, 15, 120, 125, 125, 43, 6, 19, -58, 127, 127, + 43, 16, 82, 97, -127, 127, -93, -41, 88, 0, 77, -15, 116, 16, -124, -31, -3, 95, -40, -126, -54, + -126, -83, -8, -59, 6, 67, -29, 4, 124, -10, 112, -28, -8, 85, -21, 45, 84, 6, -8, 11, 72, 32, + 84, -62, 77, 2, -36, 75, 31, -50, 116, 126, 119, -88, -55, -14, -37, 126, 40, -108, -6, -6, 57, + 64, -28, -76, 30, -117, -93, 31, -92, -44, -64, 94, 58, 65, 114, 41, 47, 71, 42, -26, 99, -126, + 57, -5, 74, -19, -113, -1, 67, -21, 126, 1, -3, 33, 60, -82, 37, -48, 89, 114, -38, 127, -114, + 35, 58, -5, 21, -46, 121, -123, -43, 127, 115, 123, 122, -101, 126, 127, 81, 52, 89, -127, 102, + 42, 117, -9, -2, 125, 127, 110, 96, 120, 66, 70, 124, 55, 84, -38, -58, 119, -127, -16, -79, + 123, 18, -127, -50, -38, 120, -85, 1, 7, -56, 108, -77, -2, 21, 37, 1, 13, -105, -69, 28, -87, + 33, -104, -51, 126, 41, 3, -121, 28, 71, 58, 86, -8, 127, 94, -55, 125, 40, -19, 127, -33, -87, + -23, 7, -111, -68, 9, 84, -119, 55, -82, 78, -37, -20, -9, -23, 53, -13, 15, -46, 116, 126, + -127, 56, -126, 125, -7, -1, 45, 26, 125, 121, 29, 47, -86, 30, 10, 76, -125, -7, 23, 92, -12, + -39, -18, 92, -97, -8, -85, -41, 49, -50, 123, -37, -126, -30, 14, 79, -49, -65, 9, -36, -38, + -96, 85, -24, -13, 37, -25, -5, -64, -127, 55, -60, -18, -61, -63, 127, 56, 67, 15, 124, 72, + 120, 127, 40, -10, 114, 24, -23, 46, 78, -53, 125, 86, 124, 86, 0, 38, 93, 21, 127, 123, 75, + -72, 13, 48, 33, 83, -51, 15, -32, -49, -33, 120, 64, 7, 9, 65, 60, 21, -21, -61, -53, -113, 84, + -97, 101, 37, -114, -27, 41, 73, 126, -10, 59, 61, -15, 70, -13, 82, -4, 69, 56, 94, -91, -50, + 92, -74, -48, 53, -7, -107, 127, 28, 30, -26, -21, -61, 77, 82, 64, -91, -125, 122, -104, 127, + 123, 122, 123, 76, -126, 127, -6, -80, 7, 40, -66, -65, 54, -2, 23, 96, -64, 74, 2, -53, -12, + -123, 39, 60, -20, 16, -17, -97, 23, -4, -53, -122, 32, -16, -54, -95, 43, 71, -1, -67, -33, 41, + 18, 72, 28, -83, 31, -100, -91, -27, 10, -128, -106, 2, 76, -13, 42, 34, 112, -19, 44, 40, -9, + -11, 65, 92, -43, -125, 2, 47, -32, 25, 122, -29, 12, 101, -8, -126, -23, 43, 7, 125, -20, -124, + 82, -2, 13, -73, -106, 115, 31, 116, -23, -44, -71, 84, 3, 47, 91, 127, 127, -15, 95, 7, 93, 5, + 113, -50, 54, 11, 13, -127, 17, 72, 43, -23, 5, -70, 20, 15, -27, 99, 69, -109, -122, -94, 16, + 127, 0, 116, 104, 45, 108, -34, 87, 72, -14, 118, 46, 42, 109, -26, 95, 93, 127, 60, 127, -93, + -54, -122, 34, -105, 56, 55, 103, 125, -71, -50, 95, -72, 127, 107, 21, 73, 126, 61, 127, 127, + 24, -62, 90, 73, 90, -46, -78, -124, 72, 123, -42, 50, -107, 17, -32, -62, -89, 124, 1, 80, -2, + 117, 119, -65, -127, -95, -121, -52, 103, 66, 75, -3, -62, -127, 127, -74, 124, 79, 49, 40, 105, + -67, -71, -70, 43, 127, 119, -4, 66, 43, 23, 91, -126, 15, 63, -119, 112, 103, 15, -99, 31, + -127, 69, 116, -46, -67, 2, -126, -29, 30, 30, -69, -98, -47, -87, -70, -127, 23, -73, 30, -7, + 94, -52, -65, 98, -45, 97, 53, 23, -9, -22, -52, -47, 6, -1, -85, -15, -61, -14, 68, 110, -10, + -121, -25, -35, -15, -94, -123, 27, 75, 48, -66, -56, -44, 93, 109, 67, -36, 24, 70, -126, 8, + -127, 126, 52, 11, -32, 120, -13, -26, -28, -125, 127, 106, -50, 124, 36, -126, -12, 0, -23, 76, + -71, -126, -12, -17, -82, 12, 124, 57, 33, 4, 77, -46, 71, -34, 72, 125, -128, 124, -24, -128, + 75, -120, 69, -45, 55, 33, 127, -33, 4, -105, -41, -59, -91, 123, 44, -127, 127, -67, 52, 25, + -125, -65, 100, -25, 123, 6, 11, -123, -92, -33, 126, -17, -4, 29, 33, 127, 96, 3, 87, -48, -18, + -70, 123, 58, -127, -3, -52, -1, -36, -41, 127, 51, -52, -27, 46, -83, 57, 9, 126, 127, 94, 79, + -37, -127, -40, 67, 52, 82, -66, 122, -13, -73, 127, -8, -80, 46, -48, 4, -54 + }; + + /** GRU1 bias, [gate][output] (3 x 24). */ + static final byte[] HIDDEN_GRU_BIAS = { + 124, 125, -57, -126, 53, 123, 127, -75, 68, 102, -2, 116, 124, 127, 124, 125, 126, 123, -16, 48, + 125, 126, 78, 85, 11, 126, -30, -30, -64, -3, -105, -29, -17, 69, 63, 2, -32, -10, -62, 113, + -52, 112, -109, 112, 7, -40, 73, 53, 62, 6, -2, 0, 0, 100, -16, 26, -24, 56, 26, -10, -33, 41, + 70, 109, -29, 127, 34, -66, 49, 53, 27, 62 + }; + + /** FC2 weights (24 x 1). */ + static final byte[] OUTPUT_DENSE_WEIGHTS = { + 127, 127, 127, 127, 127, 20, 127, -126, -126, -54, 14, 125, -126, -126, 127, -125, -126, 127, + -127, -127, -57, -30, 127, 80 + }; + + /** FC2 bias (1). */ + static final byte[] OUTPUT_DENSE_BIAS = { + -50 + }; + + private RnnVadWeights() { + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/SpectralFeatures.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/SpectralFeatures.java new file mode 100644 index 0000000..9c2a07c --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/SpectralFeatures.java @@ -0,0 +1,281 @@ +package eu.lixko.ts3j.client.audio.vad; + +import static eu.lixko.ts3j.client.audio.vad.VadConstants.CEPSTRAL_HISTORY; +import static eu.lixko.ts3j.client.audio.vad.VadConstants.FRAME_20MS_24K; +import static eu.lixko.ts3j.client.audio.vad.VadConstants.NUM_BANDS; +import static eu.lixko.ts3j.client.audio.vad.VadConstants.NUM_LOWER_BANDS; +import static eu.lixko.ts3j.client.audio.vad.VadConstants.OPUS_BANDS_24K; + +/** + * Band-wise spectral features for {@code rnn_vad}, ported from WebRTC's + * {@code rnn_vad/spectral_features.cc} and {@code spectral_features_internal.cc}. + * + *

    A 20 ms Vorbis-windowed FFT is folded into 22 Opus-scale bands, log-compressed + * and DCT'd into a cepstrum. The network is fed the higher cepstral coefficients, the + * running average and first two derivatives of the lower ones, the cepstrum of the + * band-wise correlation between the current frame and the frame one pitch period earlier, + * and a measure of how much the cepstrum has been varying. + */ +final class SpectralFeatures { + + /** Total band energy below which the frame is treated as silence. */ + private static final float SILENCE_THRESHOLD = 0.04f; + + /** FFT bins per Opus band at 24 kHz for a 20 ms frame. */ + private static final int[] OPUS_BAND_SIZES = + {4, 4, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8, 16, 16, 16, 24, 24, 32, 48}; + + /** sqrt(2 / NUM_BANDS), applied after the DCT. */ + private static final float DCT_SCALING_FACTOR = 0.301511345f; + + private final RealFft fft = new RealFft(FRAME_20MS_24K); + private final float[] halfWindow = new float[FRAME_20MS_24K / 2]; + private final float[] bandWeights = new float[FRAME_20MS_24K / 2]; + private final float[] dctTable = new float[NUM_BANDS * NUM_BANDS]; + + private final float[] windowed = new float[FRAME_20MS_24K]; + private final float[] referenceFft = new float[FRAME_20MS_24K]; + private final float[] laggedFft = new float[FRAME_20MS_24K]; + private final float[] referenceBandsEnergy = new float[OPUS_BANDS_24K]; + private final float[] laggedBandsEnergy = new float[OPUS_BANDS_24K]; + private final float[] bandsCrossCorr = new float[OPUS_BANDS_24K]; + private final float[] logBandsEnergy = new float[NUM_BANDS]; + private final float[] cepstrum = new float[NUM_BANDS]; + private final float[] crossCorrCepstrum = new float[NUM_LOWER_BANDS]; + + /** Ring buffer of the last {@link VadConstants#CEPSTRAL_HISTORY} cepstra. */ + private final float[][] cepstralHistory = new float[CEPSTRAL_HISTORY][NUM_BANDS]; + private int cepstralTail; + + /** + * Upper-right triangle of pairwise cepstral distances, stored as a square matrix so a + * new frame can be shifted in with a single array copy. + */ + private final float[] cepstralDiffs = new float[(CEPSTRAL_HISTORY - 1) * (CEPSTRAL_HISTORY - 1)]; + private final float[] newDistances = new float[CEPSTRAL_HISTORY - 1]; + + SpectralFeatures() { + int halfSize = FRAME_20MS_24K / 2; + float scaling = 1.0f / FRAME_20MS_24K; + for (int i = 0; i < halfSize; i++) { + double inner = Math.sin(0.5 * Math.PI * (i + 0.5) / halfSize); + halfWindow[i] = (float) (scaling * Math.sin(0.5 * Math.PI * inner * inner)); + } + // Each band overlaps its neighbour with a triangular response; the weight is the + // fractional position of the bin within its band. + int bin = 0; + for (int bandSize : OPUS_BAND_SIZES) { + for (int j = 0; j < bandSize; j++) { + bandWeights[bin++] = (float) j / bandSize; + } + } + double k = Math.sqrt(0.5); + for (int i = 0; i < NUM_BANDS; i++) { + for (int j = 0; j < NUM_BANDS; j++) { + dctTable[i * NUM_BANDS + j] = (float) Math.cos((i + 0.5) * j * Math.PI / NUM_BANDS); + } + dctTable[i * NUM_BANDS] *= (float) k; + } + } + + void reset() { + for (float[] row : cepstralHistory) { + java.util.Arrays.fill(row, 0.0f); + } + cepstralTail = 0; + java.util.Arrays.fill(cepstralDiffs, 0.0f); + } + + /** + * Writes the spectral part of the feature vector and returns {@code true} if the + * reference frame is silence, in which case the vector is only partially written. + * + * @param reference buffer holding the most recent 20 ms at 24 kHz + * @param referenceOffset offset of that frame within {@code reference} + * @param lagged buffer holding the 20 ms one pitch period earlier + * @param laggedOffset offset of that frame within {@code lagged} + */ + boolean checkSilenceComputeFeatures(float[] reference, int referenceOffset, + float[] lagged, int laggedOffset, + float[] featureVector) { + forwardFft(reference, referenceOffset, referenceFft); + crossCorrelation(referenceFft, referenceFft, referenceBandsEnergy); + + float totalEnergy = 0; + for (float e : referenceBandsEnergy) { + totalEnergy += e; + } + if (totalEnergy < SILENCE_THRESHOLD) { + return true; + } + + forwardFft(lagged, laggedOffset, laggedFft); + crossCorrelation(laggedFft, laggedFft, laggedBandsEnergy); + + smoothedLogMagnitudeSpectrum(referenceBandsEnergy, logBandsEnergy); + dct(logBandsEnergy, NUM_BANDS, cepstrum, NUM_BANDS); + // Ad-hoc correction terms for the first two cepstral coefficients. + cepstrum[0] -= 12.0f; + cepstrum[1] -= 4.0f; + + pushCepstrum(cepstrum); + + // Higher bands go in as-is; the lower ones are summarised over time instead. + System.arraycopy(cepstrum, NUM_LOWER_BANDS, featureVector, NUM_LOWER_BANDS, + NUM_BANDS - NUM_LOWER_BANDS); + computeAverageAndDerivatives(featureVector); + computeNormalizedCepstralCorrelation(featureVector); + featureVector[VadConstants.FEATURE_VECTOR_SIZE - 1] = computeVariability(); + return false; + } + + /** Windows a 20 ms frame and transforms it, zeroing the unused Nyquist coefficient. */ + private void forwardFft(float[] frame, int offset, float[] out) { + int halfSize = FRAME_20MS_24K / 2; + for (int i = 0, j = FRAME_20MS_24K - 1; i < halfSize; i++, j--) { + windowed[i] = frame[offset + i] * halfWindow[i]; + windowed[j] = frame[offset + j] * halfWindow[i]; + } + fft.forward(windowed, out); + out[1] = 0.0f; + } + + /** + * Folds the interleaved spectra into Opus bands. Each bin contributes to the band it + * sits in and to the next one, split by the triangular weight. + */ + private void crossCorrelation(float[] x, float[] y, float[] out) { + int k = 0; + out[0] = 0.0f; + for (int i = 0; i < OPUS_BANDS_24K - 1; i++) { + out[i + 1] = 0.0f; + for (int j = 0; j < OPUS_BAND_SIZES[i]; j++) { + float v = x[2 * k] * y[2 * k] + x[2 * k + 1] * y[2 * k + 1]; + float tmp = bandWeights[k] * v; + out[i] += v - tmp; + out[i + 1] += tmp; + k++; + } + } + out[0] *= 2.0f; // The first band only receives half a triangle. + } + + /** Log magnitude with smoothing over frequency and a decaying floor. */ + private static void smoothedLogMagnitudeSpectrum(float[] bandsEnergy, float[] out) { + final float logOneByHundred = -2.0f; + float logMax = logOneByHundred; + float follow = logOneByHundred; + for (int i = 0; i < out.length; i++) { + float x = (i < bandsEnergy.length) + ? (float) Math.log10(0.01f + bandsEnergy[i]) + : logOneByHundred; + x = Math.max(logMax - 7.0f, Math.max(follow - 1.5f, x)); + logMax = Math.max(logMax, x); + follow = Math.max(follow - 1.5f, x); + out[i] = x; + } + } + + /** DCT-II of the first {@code inSize} values of {@code in}, truncated to {@code outSize}. */ + private void dct(float[] in, int inSize, float[] out, int outSize) { + for (int i = 0; i < outSize; i++) { + float sum = 0; + for (int j = 0; j < inSize; j++) { + sum += in[j] * dctTable[j * NUM_BANDS + i]; + } + out[i] = sum * DCT_SCALING_FACTOR; + } + } + + private void pushCepstrum(float[] newCepstrum) { + // Distance from the new cepstrum to each older one, nearest first. + for (int i = 0; i < CEPSTRAL_HISTORY - 1; i++) { + float[] old = cepstralHistoryAt(i); + float sum = 0; + for (int k = 0; k < NUM_BANDS; k++) { + float c = newCepstrum[k] - old[k]; + sum += c * c; + } + newDistances[i] = sum; + } + System.arraycopy(newCepstrum, 0, cepstralHistory[cepstralTail], 0, NUM_BANDS); + cepstralTail = (cepstralTail + 1) % CEPSTRAL_HISTORY; + pushCepstralDistances(); + } + + /** Returns the cepstrum pushed {@code delay} frames ago (0 = most recent). */ + private float[] cepstralHistoryAt(int delay) { + int offset = cepstralTail - 1 - delay; + if (offset < 0) { + offset += CEPSTRAL_HISTORY; + } + return cepstralHistory[offset]; + } + + /** Shifts the distance matrix up-left by one and writes the new column. */ + private void pushCepstralDistances() { + final int s = CEPSTRAL_HISTORY; + System.arraycopy(cepstralDiffs, s, cepstralDiffs, 0, cepstralDiffs.length - s); + for (int i = 0; i < newDistances.length; i++) { + cepstralDiffs[(s - 1 - i) * (s - 1) - 1] = newDistances[i]; + } + } + + private float cepstralDistance(int delay1, int delay2) { + int row = CEPSTRAL_HISTORY - 1 - delay1; + int col = CEPSTRAL_HISTORY - 1 - delay2; + if (row > col) { // Only the upper-right triangle is stored. + int tmp = row; + row = col; + col = tmp; + } + return cepstralDiffs[row * (CEPSTRAL_HISTORY - 1) + (col - 1)]; + } + + private void computeAverageAndDerivatives(float[] featureVector) { + float[] curr = cepstralHistoryAt(0); + float[] prev1 = cepstralHistoryAt(1); + float[] prev2 = cepstralHistoryAt(2); + for (int i = 0; i < NUM_LOWER_BANDS; i++) { + featureVector[i] = curr[i] + prev1[i] + prev2[i]; // kernel [1, 1, 1] + featureVector[NUM_BANDS + i] = curr[i] - prev2[i]; // kernel [1, 0, -1] + featureVector[NUM_BANDS + NUM_LOWER_BANDS + i] = + curr[i] - 2 * prev1[i] + prev2[i]; // kernel [1, -2, 1] + } + } + + /** Band correlation between the current frame and the one a pitch period earlier. */ + private void computeNormalizedCepstralCorrelation(float[] featureVector) { + crossCorrelation(referenceFft, laggedFft, bandsCrossCorr); + for (int i = 0; i < bandsCrossCorr.length; i++) { + bandsCrossCorr[i] /= (float) Math.sqrt( + 0.001f + referenceBandsEnergy[i] * laggedBandsEnergy[i]); + } + dct(bandsCrossCorr, OPUS_BANDS_24K, crossCorrCepstrum, NUM_LOWER_BANDS); + // Ad-hoc correction terms, as for the frame cepstrum. + crossCorrCepstrum[0] -= 1.3f; + crossCorrCepstrum[1] -= 0.9f; + System.arraycopy(crossCorrCepstrum, 0, featureVector, + NUM_BANDS + 2 * NUM_LOWER_BANDS, NUM_LOWER_BANDS); + } + + /** + * How far the current cepstrum sits from its nearest neighbour in the recent history, + * averaged over the history. Steady tones score low, speech scores high. + */ + private float computeVariability() { + float variability = 0; + for (int delay1 = 0; delay1 < CEPSTRAL_HISTORY; delay1++) { + float minDist = Float.MAX_VALUE; + for (int delay2 = 0; delay2 < CEPSTRAL_HISTORY; delay2++) { + if (delay1 == delay2) { + continue; // The distance would be 0. + } + minDist = Math.min(minDist, cepstralDistance(delay1, delay2)); + } + variability += minDist; + } + // Normalised against training-set statistics. + return variability / CEPSTRAL_HISTORY - 2.1f; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/VadConstants.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/VadConstants.java new file mode 100644 index 0000000..7c40734 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/vad/VadConstants.java @@ -0,0 +1,54 @@ +package eu.lixko.ts3j.client.audio.vad; + +/** + * Sizes and pitch-search bounds of WebRTC's {@code rnn_vad}, mirroring + * {@code modules/audio_processing/agc2/rnn_vad/common.h}. + * + *

    The detector analyses 10 ms frames at 24 kHz. Spectral analysis uses the + * most recent 20 ms; pitch search additionally needs one maximum pitch period of + * history, hence the 864-sample buffer. + */ +final class VadConstants { + + static final int SAMPLE_RATE_24K = 24_000; + static final int FRAME_10MS_24K = SAMPLE_RATE_24K / 100; // 240 + static final int FRAME_20MS_24K = FRAME_10MS_24K * 2; // 480 + + /** Pitch range at 24 kHz: 0.00125 s to 0.016 s. */ + static final int MIN_PITCH_24K = SAMPLE_RATE_24K / 800; // 30 + static final int MAX_PITCH_24K = 384; // 24000 / 62.5 + static final int BUF_SIZE_24K = MAX_PITCH_24K + FRAME_20MS_24K; // 864 + + /** + * The coarse search skips very short periods; a refinement step recovers them, so the + * initial pass starts three minimum periods in. + */ + static final int INITIAL_MIN_PITCH_24K = 3 * MIN_PITCH_24K; // 90 + static final int INITIAL_NUM_LAGS_24K = MAX_PITCH_24K - INITIAL_MIN_PITCH_24K; // 294 + static final int REFINE_NUM_LAGS_24K = MAX_PITCH_24K + 1; // 385 + + // 12 kHz analysis, used for the coarse pitch search. + static final int FRAME_20MS_12K = 240; + static final int BUF_SIZE_12K = BUF_SIZE_24K / 2; // 432 + static final int INITIAL_MIN_PITCH_12K = INITIAL_MIN_PITCH_24K / 2; // 45 + static final int MAX_PITCH_12K = MAX_PITCH_24K / 2; // 192 + static final int NUM_LAGS_12K = MAX_PITCH_12K - INITIAL_MIN_PITCH_12K; // 147 + + // The pitch period fed to the network is expressed at 48 kHz. + static final int MIN_PITCH_48K = MIN_PITCH_24K * 2; // 60 + static final int MAX_PITCH_48K = MAX_PITCH_24K * 2; // 768 + + // Spectral features. + static final int NUM_BANDS = 22; + static final int NUM_LOWER_BANDS = 6; + static final int CEPSTRAL_HISTORY = 8; + /** Opus bands that fall below the 24 kHz Nyquist frequency. */ + static final int OPUS_BANDS_24K = 20; + + static final int NUM_LPC_COEFFICIENTS = 5; + + static final int FEATURE_VECTOR_SIZE = 42; + + private VadConstants() { + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/chatlog/ChatLogScope.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/chatlog/ChatLogScope.java new file mode 100644 index 0000000..106f9a6 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/chatlog/ChatLogScope.java @@ -0,0 +1,7 @@ +package eu.lixko.ts3j.client.chatlog; + +public enum ChatLogScope { + SERVER, + CHANNEL, + PRIVATE +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/chatlog/ChatLogStore.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/chatlog/ChatLogStore.java new file mode 100644 index 0000000..9ad91f8 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/chatlog/ChatLogStore.java @@ -0,0 +1,321 @@ +package eu.lixko.ts3j.client.chatlog; + +import eu.lixko.ts3j.client.config.AppDirs; +import eu.lixko.ts3j.client.text.BBCode; +import eu.lixko.ts3j.client.text.HtmlText; +import eu.lixko.ts3j.client.text.TextQuery; +import eu.lixko.ts3j.client.text.TsLink; + +import java.io.BufferedWriter; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collections; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Reads and writes TeamSpeak-compatible chat logs. The file layout and HTML + * records match the native client closely enough for both clients to consume + * each other's logs. + */ +public final class ChatLogStore { + public static final int HISTORY_LIMIT = 1000; + /** + * How much of the end of a log history is read from: far more than {@link #HISTORY_LIMIT} + * entries take, without reading years of log on every connect. + */ + private static final int HISTORY_TAIL_BYTES = 4 << 20; + + private static final DateTimeFormatter BEGIN = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("HH:mm:ss"); + private static final String HTML_HEADER = + "
    "; + private static final Pattern TEXT_MESSAGE = Pattern.compile("^<([0-9]{2}:[0-9]{2}:[0-9]{2})> ([^:]+): (.*)$"); + + private final Path serverDir; + + public ChatLogStore(String serverUniqueId) { + this(defaultRoot(), serverUniqueId); + } + + public ChatLogStore(Path root, String serverUniqueId) { + this.serverDir = root.resolve(encode(serverUniqueId == null || serverUniqueId.isBlank() + ? "unknown" : serverUniqueId)); + } + + public Path serverDir() { + return serverDir; + } + + public synchronized void begin() throws IOException { + LocalDateTime now = LocalDateTime.now(); + appendRaw(log(ChatLogScope.SERVER), "*** Log begins " + BEGIN.format(now), beginHtml("Log", now)); + appendRaw(log(ChatLogScope.CHANNEL), "*** Chat begins " + BEGIN.format(now), beginHtml("Chat", now)); + } + + public List serverHtmlHistory() throws IOException { + return last(readHtml(log(ChatLogScope.SERVER), HISTORY_TAIL_BYTES), HISTORY_LIMIT); + } + + public List channelHtmlHistory() throws IOException { + return last(readTextMessages(log(ChatLogScope.CHANNEL), ChatLogScope.CHANNEL, HISTORY_TAIL_BYTES), + HISTORY_LIMIT); + } + + public List privateHtmlHistory(String clientUniqueId) throws IOException { + return last(readTextMessages(privateLog(clientUniqueId), ChatLogScope.PRIVATE, HISTORY_TAIL_BYTES), + HISTORY_LIMIT); + } + + /** Entries of a whole log that match a query, in the order they were written. */ + public record SearchResult(List entries, int total) { + public boolean truncated() { + return total > entries.size(); + } + } + + /** + * Searches a whole log, not only the part {@link #HISTORY_LIMIT} loads into a chat. + * + * @param clientUniqueId the peer, for {@link ChatLogScope#PRIVATE}; ignored otherwise + * @param limit how many of the newest matches to return + */ + public SearchResult search(ChatLogScope scope, String clientUniqueId, TextQuery query, int limit) + throws IOException { + List all = scope == ChatLogScope.SERVER + ? readHtml(log(scope), Long.MAX_VALUE) + : readTextMessages(scope == ChatLogScope.PRIVATE ? privateLog(clientUniqueId) : log(scope), scope, + Long.MAX_VALUE); + List hits = new ArrayList<>(); + for (String entry : all) { + if (query.matches(HtmlText.plain(entry))) hits.add(entry); + } + return new SearchResult(last(hits, limit), hits.size()); + } + + /** Logs a message; a private one goes to the log of the client it came from. */ + public synchronized String appendMessage(ChatLogScope scope, boolean outgoing, int clientId, String uniqueId, + String nickname, String message) throws IOException { + LogFiles files = scope == ChatLogScope.PRIVATE ? privateLog(uniqueId) : log(scope); + return append(files, scope, outgoing, clientId, uniqueId, nickname, message); + } + + /** Logs a private message in the conversation with {@code peerUniqueId}, whoever wrote it. */ + public synchronized String appendPrivateMessage(String peerUniqueId, boolean outgoing, int clientId, + String uniqueId, String nickname, String message) + throws IOException { + return append(privateLog(peerUniqueId), ChatLogScope.PRIVATE, outgoing, clientId, uniqueId, nickname, + message); + } + + private String append(LogFiles files, ChatLogScope scope, boolean outgoing, int clientId, String uniqueId, + String nickname, String message) throws IOException { + LocalDateTime now = LocalDateTime.now(); + String text = "<" + TIME.format(now) + "> " + safe(nickname) + ": " + safe(message); + String html = messageHtml(scope, outgoing, now, clientId, uniqueId, nickname, message); + appendRaw(files, text, html); + return html; + } + + public synchronized String appendServerEvent(String message) throws IOException { + LocalDateTime now = LocalDateTime.now(); + String text = "<" + TIME.format(now) + "> " + safe(message); + String html = eventHtml(now, BBCode.linksToHtml(message)); + appendRaw(log(ChatLogScope.SERVER), text, html); + return html; + } + + public static Path defaultRoot() { + return AppDirs.chatLogs(); + } + + public static String decodePathComponent(String value) { + return new String(Base64.getDecoder().decode(value), StandardCharsets.UTF_8); + } + + private LogFiles log(ChatLogScope scope) { + return switch (scope) { + case SERVER -> new LogFiles(serverDir.resolve("server.txt"), serverDir.resolve("server.html")); + case CHANNEL -> new LogFiles(serverDir.resolve("channel.txt"), serverDir.resolve("channel.html")); + case PRIVATE -> throw new IllegalArgumentException("private log needs a client uid"); + }; + } + + private LogFiles privateLog(String clientUniqueId) { + return new LogFiles( + serverDir.resolve("clients").resolve(encode(safe(clientUniqueId)) + ".txt"), + serverDir.resolve("clients").resolve(encode(safe(clientUniqueId)) + ".html")); + } + + private void appendRaw(LogFiles files, String textLine, String htmlLine) throws IOException { + ensure(files); + try (BufferedWriter txt = Files.newBufferedWriter(files.txt, StandardCharsets.UTF_8, + StandardOpenOption.CREATE, StandardOpenOption.APPEND); + BufferedWriter html = Files.newBufferedWriter(files.html, StandardCharsets.UTF_8, + StandardOpenOption.CREATE, StandardOpenOption.APPEND)) { + txt.write(textLine); + txt.newLine(); + html.write(htmlLine); + html.newLine(); + } + } + + private static void ensure(LogFiles files) throws IOException { + Files.createDirectories(files.txt.getParent()); + Files.createDirectories(files.html.getParent()); + if (!Files.exists(files.html)) { + // Android < API 36.1 lacks Files.writeString; original: + // Files.writeString(files.html, HTML_HEADER + System.lineSeparator(), StandardCharsets.UTF_8, + // StandardOpenOption.CREATE, StandardOpenOption.APPEND); + Files.write(files.html, (HTML_HEADER + System.lineSeparator()).getBytes(StandardCharsets.UTF_8), + StandardOpenOption.CREATE, StandardOpenOption.APPEND); + } + if (!Files.exists(files.txt)) Files.createFile(files.txt); + } + + /** @param tailBytes how much of the end of the log to read */ + private static List readHtml(LogFiles files, long tailBytes) throws IOException { + if (!Files.isRegularFile(files.html)) return Collections.emptyList(); + List entries = new ArrayList<>(); + for (String line : readLines(files.html, tailBytes)) { + if (line.startsWith("

    readTextMessages(LogFiles files, ChatLogScope scope, long tailBytes) + throws IOException { + if (!Files.isRegularFile(files.txt)) return Collections.emptyList(); + List entries = new ArrayList<>(); + Matcher message = null; + StringBuilder text = new StringBuilder(); + for (String line : readLines(files.txt, tailBytes)) { + Matcher m = TEXT_MESSAGE.matcher(line); + boolean begin = line.startsWith("*** "); + if (!m.matches() && !begin) { + if (message != null) text.append('\n').append(line); + continue; + } + if (message != null) entries.add(messageLineHtml(message, text, scope)); + message = null; + if (begin) { + entries.add(beginLineHtml(line)); + } else { + message = m; + text.setLength(0); + text.append(m.group(3)); + } + } + if (message != null) entries.add(messageLineHtml(message, text, scope)); + return entries; + } + + /** The lines in the last {@code tailBytes} of a file, less the one that was cut into. */ + private static List readLines(Path file, long tailBytes) throws IOException { + try (SeekableByteChannel channel = Files.newByteChannel(file)) { + long size = channel.size(); + if (size <= tailBytes) return Files.readAllLines(file, StandardCharsets.UTF_8); + ByteBuffer tail = ByteBuffer.allocate((int) tailBytes); + channel.position(size - tailBytes); + int read = 0; + while (tail.hasRemaining() && read >= 0) read = channel.read(tail); + String text = new String(tail.array(), 0, tail.position(), StandardCharsets.UTF_8); + List lines = new ArrayList<>(List.of(text.split("\r?\n", -1))); + lines.remove(0); + return lines; + } + } + + private static List last(List entries, int limit) { + if (entries.size() <= limit) return entries; + return new ArrayList<>(entries.subList(entries.size() - limit, entries.size())); + } + + private static String beginLineHtml(String line) { + return "

    " + + BBCode.escape(line) + "
    "; + } + + private static String messageLineHtml(Matcher m, CharSequence text, ChatLogScope scope) { + String target = switch (scope) { + case PRIVATE -> "Private"; + case CHANNEL -> "Channel"; + case SERVER -> "Server"; + }; + return "
    " + + "<" + m.group(1) + "> " + + """ + BBCode.escape(m.group(2)) + "": " + + "" + BBCode.toHtml(text.toString().stripTrailing()) + + "
    "; + } + + private static String beginHtml(String kind, LocalDateTime timestamp) { + return "

    " + infoIcon() + + "*** " + kind + " begins " + BEGIN.format(timestamp) + "

    "; + } + + private static String messageHtml(ChatLogScope scope, boolean outgoing, LocalDateTime timestamp, + int clientId, String uniqueId, String nickname, String message) { + String target = switch (scope) { + case PRIVATE -> "Private"; + case CHANNEL -> "Channel"; + case SERVER -> "Server"; + }; + return "

    " + + (outgoing ? outgoingIcon() : incomingIcon()) + + "<" + TIME.format(timestamp) + "> " + + userLink(clientId, uniqueId, nickname) + + ": " + BBCode.toHtml(message) + "

    "; + } + + private static String eventHtml(LocalDateTime timestamp, String html) { + return "

    " + infoIcon() + + "<" + TIME.format(timestamp) + "> " + + "" + html + "

    "; + } + + private static String userLink(int clientId, String uniqueId, String nickname) { + if (clientId <= 0) return """ + BBCode.escape(nickname) + """; + return """ + + BBCode.escape(nickname) + """; + } + + private static String infoIcon() { + return ""; + } + + private static String incomingIcon() { + return ""; + } + + private static String outgoingIcon() { + return ""; + } + + private static String encode(String value) { + return Base64.getEncoder().encodeToString(safe(value).getBytes(StandardCharsets.UTF_8)); + } + + private static String safe(String value) { + return value == null ? "" : value; + } + + private record LogFiles(Path txt, Path html) { + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/AppDirs.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/AppDirs.java new file mode 100644 index 0000000..4f505c9 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/AppDirs.java @@ -0,0 +1,61 @@ +package eu.lixko.ts3j.client.config; + +import java.io.File; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * Where the client keeps its own state. On the desktop that is {@code ~/.ts3jclient}, with chat + * logs in the TeamSpeak 3 client's {@code ~/.ts3client/chats} so both clients share them. A + * platform without a meaningful home directory (Android) calls {@link #init} once at startup, + * before any store is loaded. + */ +public final class AppDirs { + + private static volatile File profile; + private static volatile Path chatLogs; + + private AppDirs() { + } + + public static void init(File profileDir, Path chatLogDir) { + profile = profileDir; + chatLogs = chatLogDir; + } + + /** The directory holding all persistent client state (settings, identities, caches). */ + public static File profile() { + File dir = profile; + if (dir == null) { + dir = new File(System.getProperty("user.home", "."), ".ts3jclient"); + profile = dir; + } + return dir; + } + + public static File file(String name) { + return new File(profile(), name); + } + + /** + * Creates the profile directory if it does not exist yet, readable by the user only; call + * before writing into it. + */ + public static void createProfile() { + File dir = profile(); + //noinspection ResultOfMethodCallIgnored + dir.mkdirs(); + ProfileFiles.makePrivate(dir); + } + + public static Path chatLogs() { + Path dir = chatLogs; + if (dir == null) { + // Android < API 34 lacks Path.of; original: + // dir = Path.of(System.getProperty("user.home", "."), ".ts3client", "chats"); + dir = Paths.get(System.getProperty("user.home", "."), ".ts3client", "chats"); + chatLogs = dir; + } + return dir; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/AwayMessages.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/AwayMessages.java new file mode 100644 index 0000000..cad20a6 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/AwayMessages.java @@ -0,0 +1,84 @@ +package eu.lixko.ts3j.client.config; + +import java.io.File; +import java.io.FileInputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +/** + * Persistent list of away-message presets, stored alongside the settings file. + * Frontend-agnostic: no UI dependencies. + */ +public final class AwayMessages { + + private static File file() { + return AppDirs.file("away.properties"); + } + + private final List entries = new ArrayList<>(); + + public List all() { + return entries; + } + + public void add(String message) { + entries.add(message == null ? "" : message); + } + + public void set(int index, String message) { + if (index >= 0 && index < entries.size()) entries.set(index, message == null ? "" : message); + } + + public void remove(int index) { + if (index >= 0 && index < entries.size()) entries.remove(index); + } + + public static AwayMessages load() { + AwayMessages m = new AwayMessages(); + if (!file().isFile()) return m.withDefaults(); + Properties p = new Properties(); + try (FileInputStream in = new FileInputStream(file())) { + p.load(in); + } catch (Exception e) { + return m.withDefaults(); + } + int count = parseInt(p.getProperty("count"), 0); + for (int i = 0; i < count; i++) { + String text = p.getProperty("message." + i); + if (text != null && !text.isBlank()) m.entries.add(text); + } + return m; + } + + public void save() { + Properties p = new Properties(); + p.setProperty("count", Integer.toString(entries.size())); + for (int i = 0; i < entries.size(); i++) { + p.setProperty("message." + i, entries.get(i)); + } + try { + AppDirs.createProfile(); + ProfileFiles.write(file(), out -> p.store(out, "TeamSpook TS3j away messages")); + } catch (Exception ignored) { + } + } + + /** First run: seed the presets a fresh client offers. */ + private AwayMessages withDefaults() { + entries.add("Away from keyboard"); + entries.add("Be right back"); + entries.add("Lunch"); + entries.add("Busy"); + return this; + } + + private static int parseInt(String v, int def) { + if (v == null) return def; + try { + return Integer.parseInt(v.trim()); + } catch (NumberFormatException e) { + return def; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/BanReasonPresets.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/BanReasonPresets.java new file mode 100644 index 0000000..35ac160 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/BanReasonPresets.java @@ -0,0 +1,75 @@ +package eu.lixko.ts3j.client.config; + +import java.io.File; +import java.io.FileInputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Properties; + +/** + * The reasons the ban dialogs offer as presets, stored alongside the settings file. + * Frontend-agnostic: no UI dependencies. + */ +public final class BanReasonPresets { + + private static File file() { + return AppDirs.file("banreasons.properties"); + } + + private final List entries = new ArrayList<>(); + + public List all() { + return Collections.unmodifiableList(entries); + } + + /** Remembers a reason, moving it to the front if it is already known. */ + public void add(String reason) { + if (reason == null || reason.isBlank()) return; + entries.remove(reason.trim()); + entries.add(0, reason.trim()); + } + + public void remove(String reason) { + entries.remove(reason); + } + + public static BanReasonPresets load() { + BanReasonPresets presets = new BanReasonPresets(); + if (!file().isFile()) return presets; + Properties p = new Properties(); + try (FileInputStream in = new FileInputStream(file())) { + p.load(in); + } catch (Exception e) { + return presets; + } + int count = parseInt(p.getProperty("count"), 0); + for (int i = 0; i < count; i++) { + String text = p.getProperty("reason." + i); + if (text != null && !text.isBlank()) presets.entries.add(text); + } + return presets; + } + + public void save() { + Properties p = new Properties(); + p.setProperty("count", Integer.toString(entries.size())); + for (int i = 0; i < entries.size(); i++) { + p.setProperty("reason." + i, entries.get(i)); + } + try { + AppDirs.createProfile(); + ProfileFiles.write(file(), out -> p.store(out, "TeamSpook TS3j ban reason presets")); + } catch (Exception ignored) { + } + } + + private static int parseInt(String v, int def) { + if (v == null) return def; + try { + return Integer.parseInt(v.trim()); + } catch (NumberFormatException e) { + return def; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/Bookmark.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/Bookmark.java new file mode 100644 index 0000000..d176762 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/Bookmark.java @@ -0,0 +1,66 @@ +package eu.lixko.ts3j.client.config; + +import java.util.UUID; + +/** A saved server for quick connect. */ +public final class Bookmark { + /** Stays the same through edits, for whatever refers to the bookmark from outside, like a launcher shortcut. */ + public String id = UUID.randomUUID().toString(); + public String label; + public String address; + public int port = 9987; + public String nickname; + public String password = ""; + /** Identity to connect with; empty means "use the default identity". */ + public String identityId = ""; + /** + * Channel to join on connect, as a "/"-separated path ("Lobby/Games") or + * "/<channelId>". Empty means the server's default channel. + */ + public String channel = ""; + /** Password for {@link #channel}, if it is protected. */ + public String channelPassword = ""; + /** Connect to this server automatically when the client starts. */ + public boolean connectOnStartup = false; + /** The server's icon as last seen there, 0 for none or not yet known. */ + public long iconId = 0; + + public Bookmark() { + } + + public Bookmark(String label, String address, int port, String nickname, String password) { + this.label = label; + this.address = address; + this.port = port; + this.nickname = nickname; + this.password = password == null ? "" : password; + } + + /** A bookmark of its own with the same fields, to change without touching this one. */ + public Bookmark copy() { + Bookmark b = new Bookmark(label, address, port, nickname, password); + b.id = id; + b.identityId = identityId; + b.channel = channel; + b.channelPassword = channelPassword; + b.connectOnStartup = connectOnStartup; + b.iconId = iconId; + return b; + } + + /** Whether this bookmark leads to the server at {@code address}:{@code port}. */ + public boolean pointsAt(String address, int port) { + return this.port == port && this.address != null && this.address.trim().equalsIgnoreCase(address.trim()); + } + + /** Display name, falling back to "address:port" when no label is set. */ + public String displayName() { + if (label != null && !label.isBlank()) return label; + return address + ":" + port; + } + + @Override + public String toString() { + return displayName(); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/Bookmarks.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/Bookmarks.java new file mode 100644 index 0000000..87d8a09 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/Bookmarks.java @@ -0,0 +1,143 @@ +package eu.lixko.ts3j.client.config; + +import java.io.File; +import java.io.FileInputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +/** + * Persistent list of {@link Bookmark}s, stored alongside the settings file. + * Frontend-agnostic: no UI dependencies. + */ +public final class Bookmarks { + + private static File file() { + return AppDirs.file("bookmarks.properties"); + } + + private final List entries = new ArrayList<>(); + + public List all() { + return entries; + } + + public void add(Bookmark b) { + entries.add(b); + } + + public void remove(int index) { + if (index >= 0 && index < entries.size()) entries.remove(index); + } + + /** + * Takes on the icon a server shows now for every bookmark leading to it. + * + * @return whether any bookmark changed, and so needs saving and redrawing + */ + public boolean rememberServerIcon(String address, int port, long iconId) { + if (address == null || address.isBlank()) return false; + boolean changed = false; + for (Bookmark b : entries) { + if (b.pointsAt(address, port) && b.iconId != iconId) { + b.iconId = iconId; + changed = true; + } + } + return changed; + } + + /** The bookmark with this {@link Bookmark#id}, or null. */ + public Bookmark find(String id) { + for (Bookmark b : entries) { + if (b.id.equals(id)) return b; + } + return null; + } + + /** Bookmarks flagged to connect at startup, each in its own tab. */ + public List startupBookmarks() { + List out = new ArrayList<>(); + for (Bookmark b : entries) { + if (b.connectOnStartup) out.add(b); + } + return out; + } + + public static Bookmarks load() { + Bookmarks b = new Bookmarks(); + if (!file().isFile()) return b; + Properties p = new Properties(); + try (FileInputStream in = new FileInputStream(file())) { + p.load(in); + } catch (Exception e) { + return b; + } + int count = parseInt(p.getProperty("count"), 0); + for (int i = 0; i < count; i++) { + String prefix = "bookmark." + i + "."; + Bookmark bm = new Bookmark(); + String id = p.getProperty(prefix + "id", ""); + if (!id.isBlank()) bm.id = id; + bm.label = p.getProperty(prefix + "label", ""); + bm.address = p.getProperty(prefix + "address", ""); + bm.port = parseInt(p.getProperty(prefix + "port"), 9987); + bm.nickname = p.getProperty(prefix + "nickname", ""); + bm.password = p.getProperty(prefix + "password", ""); + bm.identityId = p.getProperty(prefix + "identityId", ""); + bm.channel = p.getProperty(prefix + "channel", ""); + bm.channelPassword = p.getProperty(prefix + "channelPassword", ""); + bm.connectOnStartup = Boolean.parseBoolean(p.getProperty(prefix + "connectOnStartup", "false")); + bm.iconId = parseLong(p.getProperty(prefix + "iconId")); + if (bm.address != null && !bm.address.isBlank()) b.entries.add(bm); + } + return b; + } + + public void save() { + Properties p = new Properties(); + p.setProperty("count", Integer.toString(entries.size())); + for (int i = 0; i < entries.size(); i++) { + Bookmark bm = entries.get(i); + String prefix = "bookmark." + i + "."; + p.setProperty(prefix + "id", bm.id); + p.setProperty(prefix + "label", nullToEmpty(bm.label)); + p.setProperty(prefix + "address", nullToEmpty(bm.address)); + p.setProperty(prefix + "port", Integer.toString(bm.port)); + p.setProperty(prefix + "nickname", nullToEmpty(bm.nickname)); + p.setProperty(prefix + "password", nullToEmpty(bm.password)); + p.setProperty(prefix + "identityId", nullToEmpty(bm.identityId)); + p.setProperty(prefix + "channel", nullToEmpty(bm.channel)); + p.setProperty(prefix + "channelPassword", nullToEmpty(bm.channelPassword)); + p.setProperty(prefix + "connectOnStartup", Boolean.toString(bm.connectOnStartup)); + p.setProperty(prefix + "iconId", Long.toString(bm.iconId)); + } + try { + AppDirs.createProfile(); + ProfileFiles.write(file(), out -> p.store(out, "TeamSpook TS3j bookmarks")); + } catch (Exception ignored) { + } + } + + private static int parseInt(String v, int def) { + if (v == null) return def; + try { + return Integer.parseInt(v.trim()); + } catch (NumberFormatException e) { + return def; + } + } + + private static long parseLong(String v) { + if (v == null) return 0; + try { + return Long.parseLong(v.trim()); + } catch (NumberFormatException e) { + return 0; + } + } + + private static String nullToEmpty(String s) { + return s == null ? "" : s; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/ClientRowColors.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/ClientRowColors.java new file mode 100644 index 0000000..1ba1ea3 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/ClientRowColors.java @@ -0,0 +1,77 @@ +package eu.lixko.ts3j.client.config; + +import eu.lixko.ts3j.client.net.ClientStatus; + +import java.util.List; +import java.util.Properties; + +/** + * Background colours of client rows in the channel tree: one for every client, overridden + * by one while they talk and one while they are muted or away. Colours are ARGB; 0 is none. + */ +public final class ClientRowColors { + + public record Preset(String name, int argb) { + } + + /** See-through, so they tint the light and dark themes alike and the names stay readable. */ + public static final List PRESETS = List.of( + new Preset("Green", 0x594CAF50), + new Preset("Teal", 0x5926A69A), + new Preset("Blue", 0x5942A5F5), + new Preset("Purple", 0x59AB47BC), + new Preset("Pink", 0x59EC407A), + new Preset("Red", 0x59EF5350), + new Preset("Orange", 0x59FFA726), + new Preset("Yellow", 0x59FFEE58), + new Preset("Grey", 0x599E9E9E)); + + private static final String PREFIX = "clientRowColor."; + + public int any; + public int talking; + public int mutedAway; + + /** The colour of a row showing {@code status}; 0 for none. */ + public int of(ClientStatus status) { + int own = switch (status) { + case TALKING, COMMANDER_TALKING -> talking; + case SPEAKERS_DISABLED, SPEAKERS_MUTED, MIC_DISABLED, MIC_MUTED, AWAY -> mutedAway; + default -> 0; + }; + return own != 0 ? own : any; + } + + /** The preset named for {@code argb}, or {@code null} for a custom colour or none. */ + public static Preset presetOf(int argb) { + for (Preset p : PRESETS) { + if (p.argb() == argb) return p; + } + return null; + } + + void load(Properties p) { + any = parse(p.getProperty(PREFIX + "any")); + talking = parse(p.getProperty(PREFIX + "talking")); + mutedAway = parse(p.getProperty(PREFIX + "mutedAway")); + } + + void store(Properties p) { + p.setProperty(PREFIX + "any", format(any)); + p.setProperty(PREFIX + "talking", format(talking)); + p.setProperty(PREFIX + "mutedAway", format(mutedAway)); + } + + private static int parse(String v) { + if (v == null || v.isBlank()) return 0; + try { + return (int) Long.parseLong(v.trim().replace("#", ""), 16); + } catch (NumberFormatException e) { + return 0; + } + } + + private static String format(int argb) { + return argb == 0 ? "" : String.format("#%08X", argb); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/ClientVersion.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/ClientVersion.java new file mode 100644 index 0000000..2fafd07 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/ClientVersion.java @@ -0,0 +1,88 @@ +package eu.lixko.ts3j.client.config; + +import java.util.List; + +/** + * The version, platform and signature a client reports to the server in + * {@code clientinit}. Other clients see the version and platform in the info + * panel ("3.6.2 on Windows"). + * + *

    The signature is TeamSpeak's, over the version and platform strings + * together, so the three only work as a set. Servers answer "client is modified" + * for a version they do not accept — an invented one, or one older than their + * configured minimum — which is why {@link #PRESETS} holds genuine triples taken + * from released clients, newest first per platform. + * + * @param label human-readable name, e.g. "3.6.2 on Windows" + * @param version {@code client_version}, e.g. "3.6.2 [Build: 1695203293]" + * @param platform {@code client_platform}, e.g. "Windows" + * @param sign {@code client_version_sign}, base64 + */ +public record ClientVersion(String label, String version, String platform, String sign) { + + /** Platform names the official clients report. */ + public static final List PLATFORMS = + List.of("Windows", "Linux", "OS X", "Android", "iOS"); + + /** + * Signed triples from released TeamSpeak clients. "3.?.?" is the version the + * SDK-based clients report; it is signed for every platform and is what this + * client uses by default. + */ + public static final List PRESETS = List.of( + new ClientVersion("3.?.? on Windows", "3.?.? [Build: 5680278000]", "Windows", + "DX5NIYLvfJEUjuIbCidnoeozxIDRRkpq3I9vVMBmE9L2qnekOoBzSenkzsg2lC9CMv8K5hkEzhr2TYUYSwUXCg=="), + new ClientVersion("3.6.3 on Windows", "3.6.3 [Build: 1701166057]", "Windows", + "ML3yE6pV0QGyhc8o7k1bgqDSj+5gZIQFMjBNhWJ6L0FtJwniBq8l1wivx3DzgVVCvyRbzfg8MsdV/rjl5sHNCw=="), + new ClientVersion("3.6.2 on Windows", "3.6.2 [Build: 1695203293]", "Windows", + "4BdaZpdgUSMCuIs8qcloJPNxNlJ4o7QKnxMCRO60mSOTtJZyKjOrGLAmeAEtLIJjcjmdSpycMbQOIV92K2vXAw=="), + new ClientVersion("3.6.1 on Windows", "3.6.1 [Build: 1690872913]", "Windows", + "+YmPaYUBL4F9+TgxyFhlT8qIi1Ym+So4NNMcuohla/u4kfJCGabZ1vDF4cIOAghIqWfO+bQ0OkORZrCBdpi2Cw=="), + new ClientVersion("3.6.0 on Windows", "3.6.0 [Build: 1686749764]", "Windows", + "gfzG6CfwNYeqrjT68s7ahPd24A/XS0P8LLAB7hrE54MnrlO12RiflD2w69VZ7EYlqnd9GAiVzdGJHCmCFWtlAQ=="), + + new ClientVersion("3.?.? on Linux", "3.?.? [Build: 5680278000]", "Linux", + "Hjd+N58Gv3ENhoKmGYy2bNRBsNNgm5kpiaQWxOj5HN2DXttG6REjymSwJtpJ8muC2gSwRuZi0R+8Laan5ts5CQ=="), + new ClientVersion("3.6.2 on Linux", "3.6.2 [Build: 1695203293]", "Linux", + "p4iF1jZ3ZOz9MEkKSZ2bvnFtm9WmUcQy9mAP//erFE4PF1sB6K1CSANrr+3X4B0aZR0u+K2pjnv8kiKsWKQCBQ=="), + new ClientVersion("3.6.1 on Linux", "3.6.1 [Build: 1690193193]", "Linux", + "UAcE5h5FgPcdChWTtiO816HX8f2qdoDcDEw6crbJ96Yo7rp1Bt+qx/rkKK9bzlVWMhOd4fI7pr++1XaPkEBnAQ=="), + new ClientVersion("3.6.0 on Linux", "3.6.0 [Build: 1686749764]", "Linux", + "TccRBHwn5LSA0lfpa2B42QmfCOiG+MqqyhlOqy5RcuRQNUGPD0e47lUz+Z/8+Gsdc1TPG4+vYlRl8+v2v+26Aw=="), + new ClientVersion("3.5.8 on Linux", "3.5.8 [Build: 1644595825]", "Linux", + "CK+cWJQESZgUdw1AFHINMbwiLjFGSiupour0Dfj/j1/xwx4L3nW3G+alYtiQw/wQwlWm873HS6PvXUBarz/tCw=="), + + new ClientVersion("3.?.? on OS X", "3.?.? [Build: 5680278000]", "OS X", + "SttEnjoWE8jqIM6BOHSfiZP9DGjW0EP/ajU4bdKqgGMV4aYq/kzwVA9gxbmdIzV4lbaokvXBqrRjfBHrTVh8Cg=="), + new ClientVersion("3.6.2 on OS X", "3.6.2 [Build: 1695203293]", "OS X", + "SOCkLcsxINIGVc+3OQ5Vrmv2BVNNFA9LX5Jj9tqbIiYv2HU6Z5E8AL5+v5G2LDN0F+U55+uW43ezUoYAr1WuBA=="), + new ClientVersion("3.6.1 on OS X", "3.6.1 [Build: 1690193193]", "OS X", + "P+KOw42V8K0nN5FbGItCaJzrDuWcRgfE3MRzrtbYAhRMTXHzRxvwLkoLM7+vKTW135NtWZlKbZuDAvxgwhSLBg=="), + new ClientVersion("3.6.0 on OS X", "3.6.0 [Build: 1686749764]", "OS X", + "g8H7Op8eCrn0wHutuD/SlmUcZPmkSlFUBhvZpSgm9kuQl4dapzKJq2anI5jDwRs/ooBm/wrIlSiWI6HXuOPZDA=="), + + new ClientVersion("3.?.? on Android", "3.?.? [Build: 5680278000]", "Android", + "AWb948BY32Z7bpIyoAlQguSmxOGcmjESPceQe1DpW5IZ4+AW1KfTk2VUIYNfUPsxReDJMCtlhVKslzhR2lf0AA=="), + new ClientVersion("3.8.7 on Android", "3.8.7 [Build: 1785186501]", "Android", + "mbt0WPhXJ+YKJUix5b6t+ZOHTCfvRqhhhrpcS5koM9CUL0BAFQZRG5Di5rJrqipZdk+gEUtpAX9I5nkuL7V9Dw=="), + new ClientVersion("3.8.6 on Android", "3.8.6 [Build: 1774892004]", "Android", + "Hh0oEZupsq8f0BuUHhMKdkXsMmgZZ03dJL8qAwnlH2JAHuefaAZFS/buiH2MLwgdRkZ81ffYk5YOTfc/bJczDw=="), + + new ClientVersion("3.?.? on iOS", "3.?.? [Build: 5680278000]", "iOS", + "XrAf+Buq6Eb0ehEW/niFp06YX+nGGOS0Ke4MoUBzn+cX9q6G5C0A/d5XtgcNMe8r9jJgV/adIYVpsGS3pVlSAA=="), + new ClientVersion("3.8.2 on iOS", "3.8.2 [Build: 1764028963]", "iOS", + "Bc57xjumaioWkouTRqoS6XbSIXysrPH+gxynXgL4/nYr38l4OocUTpQaMMHevmgk/FZxJWFNEhU3Hpg5+M+MAA=="), + new ClientVersion("3.8.1 on iOS", "3.8.1 [Build: 1763403218]", "iOS", + "GM/7isPK6LDKTN3Hdelenbr99dnPyWTccLCOCFKK41321XMsdG02putu+NskCLddlDPu2CPYJ4YABRS2pJ88Ag==")); + + /** The triple used when the user has not chosen one; matches the library's built-in. */ + public static final ClientVersion DEFAULT = PRESETS.get(0); + + /** The preset carrying exactly these three values, or null when the user typed their own. */ + public static ClientVersion match(String version, String platform, String sign) { + return PRESETS.stream() + .filter(v -> v.version.equals(version) && v.platform.equals(platform) && v.sign.equals(sign)) + .findFirst() + .orElse(null); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/IdentityEntry.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/IdentityEntry.java new file mode 100644 index 0000000..695010d --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/IdentityEntry.java @@ -0,0 +1,76 @@ +package eu.lixko.ts3j.client.config; + +import com.github.manevolent.ts3j.identity.LocalIdentity; + +import java.io.File; + +/** + * One managed identity: a TS3 key pair plus the user-visible name it is filed + * under. Backed by a TeamSpeak-compatible identity INI file on disk. + */ +public final class IdentityEntry { + + private final String id; + private final File file; + private final LocalIdentity identity; + private String name; + private String nickname = ""; + private String phoneticNickname = ""; + + IdentityEntry(String id, String name, File file, LocalIdentity identity) { + this.id = id; + this.name = name; + this.file = file; + this.identity = identity; + } + + /** Stable key used to reference this identity from settings and bookmarks. */ + public String getId() { + return id; + } + + public String getName() { + return name; + } + + void setName(String name) { + this.name = name; + } + + /** Nickname to connect with, unless a bookmark names its own; empty for the global one. */ + public String getNickname() { + return nickname; + } + + public String getPhoneticNickname() { + return phoneticNickname; + } + + void setNicknames(String nickname, String phoneticNickname) { + this.nickname = nickname == null ? "" : nickname.trim(); + this.phoneticNickname = phoneticNickname == null ? "" : phoneticNickname.trim(); + } + + public File getFile() { + return file; + } + + public LocalIdentity getIdentity() { + return identity; + } + + /** The TeamSpeak unique ID (base64 SHA-1 of the public key). */ + public String getUniqueId() { + return identity.getUid().toBase64(); + } + + /** Current security level ("hash cash" leading-zero bits) of the identity. */ + public int getSecurityLevel() { + return identity.getSecurityLevel(); + } + + @Override + public String toString() { + return name; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/IdentityStore.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/IdentityStore.java new file mode 100644 index 0000000..a281d2d --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/IdentityStore.java @@ -0,0 +1,385 @@ +package eu.lixko.ts3j.client.config; + +import com.github.manevolent.ts3j.identity.LocalIdentity; +import org.ini4j.Ini; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +/** + * Manages the user's TeamSpeak identities, mirroring the official client: + * several identities may coexist, one is the default, and any of them can be + * imported from or exported to a TS3 identity INI file. + * + *

    Each identity lives in its own {@code ~/.ts3jclient/identities/<id>.ini} + * file in TeamSpeak's own format, so files can be exchanged with the official + * client verbatim. The display name is kept in the INI's {@code id} key, again + * as TeamSpeak does. + * + *

    Safe to share between threads: a connection resolves its identity on its own thread + * while the UI may be managing them. + */ +public final class IdentityStore { + + /** Security level new identities are generated with, matching the TS3 client's default. */ + public static final int DEFAULT_SECURITY_LEVEL = 8; + + /** Keys TeamSpeak keeps next to the key in an identity INI. */ + private static final String KEY_NAME = "id"; + private static final String KEY_NICKNAME = "nickname"; + private static final String KEY_PHONETIC_NICKNAME = "phonetic_nickname"; + + + private final List entries = new ArrayList<>(); + + /** + * Reports progress while improving an identity's security level. + * Returning {@code false} aborts the search, keeping the best result so far. + */ + public interface ImproveProgress { + boolean onProgress(int level, long offset); + } + + private IdentityStore() { + } + + /** Loads all identities from disk, migrating a legacy single-identity file if needed. */ + public static IdentityStore load(Settings settings) { + IdentityStore store = new IdentityStore(); + File[] files = directory().listFiles((d, n) -> n.toLowerCase(Locale.ROOT).endsWith(".ini")); + if (files != null) { + for (File f : files) { + IdentityEntry e = read(f); + if (e != null) store.entries.add(e); + } + } + if (store.entries.isEmpty()) store.migrateLegacy(settings); + store.sort(); + return store; + } + + /** Adopts the pre-multi-identity {@code identity.ini} as the first managed identity. */ + private void migrateLegacy(Settings settings) { + File legacy = settings.identityFile(); + if (legacy == null || !legacy.isFile()) return; + try { + LocalIdentity identity = LocalIdentity.read(legacy); + create("Default", identity); + } catch (Exception ignored) { + // Unreadable legacy identity: start fresh instead. + } + } + + /** A snapshot of the identities, sorted by name. */ + public synchronized List all() { + return new ArrayList<>(entries); + } + + public synchronized boolean isEmpty() { + return entries.isEmpty(); + } + + public synchronized IdentityEntry byId(String id) { + if (id == null || id.isBlank()) return null; + for (IdentityEntry e : entries) { + if (e.getId().equals(id)) return e; + } + return null; + } + + /** The identity with this TeamSpeak unique ID, or {@code null}. */ + public synchronized IdentityEntry byUniqueId(String uniqueId) { + if (uniqueId == null || uniqueId.isBlank()) return null; + for (IdentityEntry e : entries) { + if (e.getUniqueId().equals(uniqueId)) return e; + } + return null; + } + + /** + * Resolves the identity to connect with: the requested one, else the configured + * default, else the first available — generating one when the store is empty. + */ + public synchronized IdentityEntry resolve(Settings settings, String preferredId) throws Exception { + IdentityEntry e = byId(preferredId); + if (e != null) return e; + + e = byId(settings.defaultIdentityId); + if (e == null) { + e = entries.isEmpty() ? generate("Default", DEFAULT_SECURITY_LEVEL) : entries.get(0); + settings.defaultIdentityId = e.getId(); + settings.save(); + } + return e; + } + + /** Generates a brand-new identity. Blocking: key improvement takes time. */ + public IdentityEntry generate(String name, int securityLevel) throws Exception { + return create(name, LocalIdentity.generateNew(securityLevel)); + } + + /** Imports a TeamSpeak identity INI file, keeping its own name unless one is given. */ + public IdentityEntry importFile(File source, String name) throws IOException { + try (InputStream in = new FileInputStream(source)) { + return importStream(in, name, stripExtension(source.getName())); + } + } + + /** Imports a TeamSpeak identity INI from a stream, keeping its own name unless one is given. */ + public IdentityEntry importStream(InputStream in, String name) throws IOException { + return importStream(in, name, "Imported identity"); + } + + private IdentityEntry importStream(InputStream in, String name, String fallbackName) throws IOException { + byte[] ini = in.readAllBytes(); + LocalIdentity identity = LocalIdentity.read(new ByteArrayInputStream(ini)); + Map props = readProperties(new ByteArrayInputStream(ini)); + String label = (name == null || name.isBlank()) ? props.getOrDefault(KEY_NAME, "") : name; + return create(label.isBlank() ? fallbackName : label, identity, + props.getOrDefault(KEY_NICKNAME, ""), props.getOrDefault(KEY_PHONETIC_NICKNAME, "")); + } + + /** + * Parses an identity in the {@code V} form TeamSpeak keeps + * in its INI files and its settings database. + */ + public static LocalIdentity parseIdentityString(String identity) throws IOException { + String ini = "[Identity]\r\nidentity=\"" + identity + "\"\r\n"; + return LocalIdentity.read(new ByteArrayInputStream(ini.getBytes(StandardCharsets.US_ASCII))); + } + + /** Files an existing key pair as a managed identity under the given name. */ + public IdentityEntry add(String name, LocalIdentity identity, String nickname, String phoneticNickname) + throws IOException { + return create(name, identity, nickname, phoneticNickname); + } + + /** Writes an identity out in TeamSpeak's own format, ready to import elsewhere. */ + public void exportTo(IdentityEntry entry, File target) throws IOException { + write(entry, target); + } + + /** Writes an identity out in TeamSpeak's own format; closes {@code out}. */ + public void exportTo(IdentityEntry entry, OutputStream out) throws IOException { + entry.getIdentity().save(out, properties(entry)); + } + + public synchronized void rename(IdentityEntry entry, String name) throws IOException { + if (name == null || name.isBlank()) return; + entry.setName(name.trim()); + write(entry, entry.getFile()); + sort(); + } + + /** Sets the nicknames the identity connects with; empty ones fall back to the global nickname. */ + public synchronized void setNicknames(IdentityEntry entry, String nickname, String phoneticNickname) + throws IOException { + entry.setNicknames(nickname, phoneticNickname); + write(entry, entry.getFile()); + } + + /** Deletes an identity, clearing any settings or bookmarks that referenced it. */ + public synchronized void remove(IdentityEntry entry, Settings settings, Bookmarks bookmarks) { + entries.remove(entry); + //noinspection ResultOfMethodCallIgnored + entry.getFile().delete(); + + if (entry.getId().equals(settings.defaultIdentityId)) { + settings.defaultIdentityId = entries.isEmpty() ? "" : entries.get(0).getId(); + settings.save(); + } + if (bookmarks != null) { + boolean changed = false; + for (Bookmark b : bookmarks.all()) { + if (entry.getId().equals(b.identityId)) { + b.identityId = ""; + changed = true; + } + } + if (changed) bookmarks.save(); + } + } + + /** + * Raises an identity's security level towards {@code target} by searching for a + * better key offset, persisting the result. Returns the level reached. + * + * @param progress called periodically; return {@code false} from it to stop early + */ + public int improveSecurity(IdentityEntry entry, int target, ImproveProgress progress) throws IOException { + LocalIdentity identity = entry.getIdentity(); + byte[] publicKey = identity.getPublicKeyString().getBytes(StandardCharsets.US_ASCII); + MessageDigest sha1 = sha1(); + + int best = identity.getSecurityLevel(); + long offset = Math.max(identity.getKeyOffset(), identity.getLastCheckedKeyOffset()); + try { + while (best < target) { + int level = securityLevel(sha1, publicKey, offset); + if (level > best) { + best = level; + identity.setKeyOffset(offset); + } + offset++; + if ((offset & 0xFFFF) == 0 && progress != null && !progress.onProgress(best, offset)) break; + } + } finally { + identity.setLastCheckedKeyOffset(offset); + write(entry, entry.getFile()); + } + return best; + } + + // ---- persistence ---- + + private IdentityEntry create(String name, LocalIdentity identity) throws IOException { + return create(name, identity, "", ""); + } + + private synchronized IdentityEntry create(String name, LocalIdentity identity, String nickname, + String phoneticNickname) throws IOException { + String id = uniqueId(name); + IdentityEntry entry = new IdentityEntry(id, name, new File(directory(), id + ".ini"), identity); + entry.setNicknames(nickname, phoneticNickname); + write(entry, entry.getFile()); + entries.add(entry); + sort(); + return entry; + } + + private static void write(IdentityEntry entry, File file) throws IOException { + File dir = file.getParentFile(); + if (dir != null && !dir.isDirectory() && !dir.mkdirs()) { + throw new IOException("Cannot create " + dir); + } + ProfileFiles.write(file, out -> entry.getIdentity().save(out, properties(entry))); + } + + private static Map properties(IdentityEntry entry) { + Map props = new HashMap<>(); + props.put(KEY_NAME, entry.getName() == null ? "" : entry.getName()); + props.put(KEY_NICKNAME, entry.getNickname()); + props.put(KEY_PHONETIC_NICKNAME, entry.getPhoneticNickname()); + return props; + } + + private static IdentityEntry read(File file) { + try { + LocalIdentity identity = LocalIdentity.read(file); + String id = stripExtension(file.getName()); + Map props; + try (InputStream in = new FileInputStream(file)) { + props = readProperties(in); + } + String name = props.getOrDefault(KEY_NAME, ""); + IdentityEntry entry = new IdentityEntry(id, name.isBlank() ? id : name, file, identity); + entry.setNicknames(props.get(KEY_NICKNAME), props.get(KEY_PHONETIC_NICKNAME)); + return entry; + } catch (Exception e) { + return null; + } + } + + /** The name and nicknames an identity INI carries besides the key; missing ones are left out. */ + private static Map readProperties(InputStream in) { + Map props = new HashMap<>(); + try { + Ini ini = new Ini(in); + for (String key : new String[]{KEY_NAME, KEY_NICKNAME, KEY_PHONETIC_NICKNAME}) { + String value = unquote(ini.get("Identity", key)); + if (value != null) props.put(key, value); + } + } catch (Exception ignored) { + } + return props; + } + + /** TeamSpeak quotes INI values; ini4j hands them back verbatim. */ + private static String unquote(String value) { + if (value == null) return null; + String s = value.trim(); + if (s.length() >= 2 && s.startsWith("\"") && s.endsWith("\"")) { + s = s.substring(1, s.length() - 1); + } + return s.replace("\\\"", "\""); + } + + /** Derives a filesystem-safe, collision-free key from the display name. */ + private String uniqueId(String name) { + String base = (name == null ? "" : name).trim().toLowerCase(Locale.ROOT) + .replaceAll("[^a-z0-9]+", "-") + .replaceAll("(^-+|-+$)", ""); + if (base.isEmpty()) base = "identity"; + String candidate = base; + for (int i = 2; taken(candidate); i++) { + candidate = base + "-" + i; + } + return candidate; + } + + private boolean taken(String id) { + if (byId(id) != null) return true; + return new File(directory(), id + ".ini").exists(); + } + + private void sort() { + entries.sort(Comparator.comparing(e -> e.getName().toLowerCase(Locale.ROOT))); + } + + private static String stripExtension(String fileName) { + int dot = fileName.lastIndexOf('.'); + return dot > 0 ? fileName.substring(0, dot) : fileName; + } + + // ---- security level search ---- + + private static MessageDigest sha1() { + try { + return MessageDigest.getInstance("SHA-1"); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + /** Leading zero bits of SHA-1(publicKey + decimal offset) — TeamSpeak's proof of work. */ + private static int securityLevel(MessageDigest sha1, byte[] publicKey, long offset) { + sha1.reset(); + sha1.update(publicKey); + sha1.update(Long.toString(offset).getBytes(StandardCharsets.US_ASCII)); + return leadingZeroBits(sha1.digest()); + } + + private static int leadingZeroBits(byte[] data) { + int count = 0; + for (byte b : data) { + if (b == 0) { + count += 8; + continue; + } + for (int bit = 0; bit < 8; bit++) { + if ((b & (1 << bit)) == 0) count++; + else break; + } + break; + } + return count; + } + + /** Directory the managed identity files live in. */ + public static File directory() { + return AppDirs.file("identities"); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/InstallDirs.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/InstallDirs.java new file mode 100644 index 0000000..2c69518 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/InstallDirs.java @@ -0,0 +1,60 @@ +package eu.lixko.ts3j.client.config; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +/** + * Locates the folders add-ons (sound packs, icon packs) are loaded from: the + * client's own folder, a folder the user configured, and the matching folder of + * an installed TeamSpeak 3 client, whose add-ons are usable as they are. + */ +public final class InstallDirs { + + /** Overrides the TeamSpeak install location the add-ons are borrowed from. */ + private static final String CLIENT_DIR_PROPERTY = "ts3.client.dir"; + private static final String CLIENT_DIR_ENV = "TS3_CLIENT_DIR"; + + private InstallDirs() { + } + + /** + * @param subfolder the add-on folder inside a TeamSpeak installation ({@code sound}, {@code gfx}) + * @param userDirectory the client's own add-on folder (may not exist yet) + * @param extraDirectory an additional folder chosen by the user, or {@code null} + * @return the folders that exist, most specific first + */ + public static List searchRoots(String subfolder, File userDirectory, String extraDirectory) { + List roots = new ArrayList<>(); + if (userDirectory != null) roots.add(userDirectory); + if (extraDirectory != null && !extraDirectory.isBlank()) roots.add(new File(extraDirectory.trim())); + + String configured = System.getProperty(CLIENT_DIR_PROPERTY, System.getenv(CLIENT_DIR_ENV)); + if (configured != null && !configured.isBlank()) roots.add(new File(configured.trim(), subfolder)); + + String home = System.getProperty("user.home", "."); + for (String candidate : new String[]{ + "TeamSpeak3-Client-linux_amd64", "TeamSpeak3-Client-linux_x86", + ".local/share/TeamSpeak3-Client-linux_amd64", "Applications/TeamSpeak3-Client-linux_amd64"}) { + roots.add(new File(new File(home, candidate), subfolder)); + } + for (String candidate : new String[]{ + "/opt/teamspeak3-client", "/opt/teamspeak3", "/usr/share/teamspeak3", + "/usr/share/teamspeak3-client"}) { + roots.add(new File(candidate, subfolder)); + } + String programFiles = System.getenv("ProgramFiles"); + if (programFiles != null) { + roots.add(new File(programFiles, "TeamSpeak 3 Client" + File.separator + subfolder)); + } + // Running from a checkout that has the official client unpacked next to it. + roots.add(new File("TeamSpeak3-Client-linux_amd64/" + subfolder)); + roots.add(new File("../TeamSpeak3-Client-linux_amd64/" + subfolder)); + + List existing = new ArrayList<>(); + for (File root : roots) { + if (root.isDirectory()) existing.add(root); + } + return existing; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/ProfileFiles.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/ProfileFiles.java new file mode 100644 index 0000000..679aa1e --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/ProfileFiles.java @@ -0,0 +1,77 @@ +package eu.lixko.ts3j.client.config; + +import java.io.File; +import java.io.FilterOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.channels.Channels; +import java.nio.channels.FileChannel; +import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.PosixFilePermissions; + +/** + * Writes the files in the profile, which hold private keys and server passwords: only the + * user may read them, and a crash mid-write never leaves one cut short. + */ +public final class ProfileFiles { + + /** Produces a file's content. */ + public interface Content { + void writeTo(OutputStream out) throws IOException; + } + + private ProfileFiles() { + } + + /** + * Replaces {@code file} with {@code content} in one step: it is written to a private + * temporary file next to it, flushed to disk, then moved over the old one. + */ + public static void write(File file, Content content) throws IOException { + Path target = file.toPath().toAbsolutePath(); + Path dir = target.getParent(); + Files.createDirectories(dir); + // Created readable by the owner only, where the file system has permissions at all. + Path temp = Files.createTempFile(dir, "." + file.getName() + ".", ".tmp"); + try { + try (FileChannel channel = FileChannel.open(temp, StandardOpenOption.WRITE)) { + content.writeTo(unclosable(Channels.newOutputStream(channel))); + channel.force(true); + } + try { + Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } catch (AtomicMoveNotSupportedException e) { + Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING); + } + } finally { + Files.deleteIfExists(temp); + } + } + + /** Some writers close what they are given; the file still has to be synced after them. */ + private static OutputStream unclosable(OutputStream out) { + return new FilterOutputStream(out) { + @Override + public void write(byte[] b, int off, int len) throws IOException { + out.write(b, off, len); + } + + @Override + public void close() { + } + }; + } + + /** Makes a directory accessible to the user only, where the file system supports that. */ + static void makePrivate(File dir) { + try { + Files.setPosixFilePermissions(dir.toPath(), PosixFilePermissions.fromString("rwx------")); + } catch (UnsupportedOperationException | IOException ignored) { + // Not a POSIX file system (Windows): the user's profile folder is private already. + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/ServerLogSettings.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/ServerLogSettings.java new file mode 100644 index 0000000..4813239 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/ServerLogSettings.java @@ -0,0 +1,133 @@ +package eu.lixko.ts3j.client.config; + +import eu.lixko.ts3j.client.net.ServerLogEntry.Level; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Locale; +import java.util.Properties; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * How the Server Log window shows the log: which levels, in which time zone, which lines + * stand out in colour and which are left out — TeamSpeak's ServerLogView settings. + */ +public final class ServerLogSettings { + + /** + * Lines containing {@code keyword} (ignoring case) are drawn in these colours. + * + * @param foreground an RGB colour, or {@code null} for the usual text colour + * @param background an RGB colour, or {@code null} for none + */ + public record Highlight(String keyword, Integer foreground, Integer background) { + } + + private static final String PREFIX = "serverLog."; + + /** The levels the window offers to show; the server's debug levels never reach a virtual server log. */ + public static final List SHOWN_LEVELS = List.of(Level.CRITICAL, Level.ERROR, Level.WARNING, Level.INFO); + + public final Set levels = EnumSet.copyOf(SHOWN_LEVELS); + /** Show times in the local time zone rather than in UTC, as the server writes them. */ + public boolean localTime; + /** Checked in order; the first keyword a line contains decides its colours. */ + public final List highlights = new ArrayList<>(List.of( + new Highlight("Critical", 0xC00000, null), + new Highlight("Error", 0xE03030, null), + new Highlight("Warning", 0xC07000, null))); + /** Lines containing any of these (ignoring case) are not shown. */ + public final List excludes = new ArrayList<>(); + + /** Whether a line passes the level choice and the exclude filter. */ + public boolean shows(Level level, String line) { + if (!levels.contains(level) && SHOWN_LEVELS.contains(level)) return false; + String lower = line.toLowerCase(Locale.ROOT); + for (String term : excludes) { + if (!term.isEmpty() && lower.contains(term.toLowerCase(Locale.ROOT))) return false; + } + return true; + } + + /** The first highlight whose keyword {@code line} contains, or {@code null}. */ + public Highlight highlightFor(String line) { + String lower = line.toLowerCase(Locale.ROOT); + for (Highlight h : highlights) { + if (!h.keyword().isEmpty() && lower.contains(h.keyword().toLowerCase(Locale.ROOT))) return h; + } + return null; + } + + void load(Properties p) { + String lv = p.getProperty(PREFIX + "levels"); + if (lv != null) { + levels.clear(); + for (String name : lv.split(",")) { + try { + levels.add(Level.valueOf(name.trim())); + } catch (IllegalArgumentException ignored) { + // dropped level name + } + } + } + localTime = Boolean.parseBoolean(p.getProperty(PREFIX + "localTime", Boolean.toString(localTime))); + if (p.getProperty(PREFIX + "highlights") != null) { + highlights.clear(); + int n = parseCount(p.getProperty(PREFIX + "highlights")); + for (int i = 0; i < n; i++) { + String keyword = p.getProperty(PREFIX + "highlight." + i + ".keyword"); + if (keyword == null) continue; + highlights.add(new Highlight(keyword, parseColor(p.getProperty(PREFIX + "highlight." + i + ".fg")), + parseColor(p.getProperty(PREFIX + "highlight." + i + ".bg")))); + } + } + if (p.getProperty(PREFIX + "excludes") != null) { + excludes.clear(); + int n = parseCount(p.getProperty(PREFIX + "excludes")); + for (int i = 0; i < n; i++) { + String term = p.getProperty(PREFIX + "exclude." + i); + if (term != null) excludes.add(term); + } + } + } + + void store(Properties p) { + p.stringPropertyNames().stream() + .filter(k -> k.startsWith(PREFIX + "highlight.") || k.startsWith(PREFIX + "exclude.")) + .forEach(p::remove); + p.setProperty(PREFIX + "levels", levels.stream().map(Enum::name).collect(Collectors.joining(","))); + p.setProperty(PREFIX + "localTime", Boolean.toString(localTime)); + p.setProperty(PREFIX + "highlights", Integer.toString(highlights.size())); + for (int i = 0; i < highlights.size(); i++) { + Highlight h = highlights.get(i); + p.setProperty(PREFIX + "highlight." + i + ".keyword", h.keyword()); + p.setProperty(PREFIX + "highlight." + i + ".fg", formatColor(h.foreground())); + p.setProperty(PREFIX + "highlight." + i + ".bg", formatColor(h.background())); + } + p.setProperty(PREFIX + "excludes", Integer.toString(excludes.size())); + for (int i = 0; i < excludes.size(); i++) p.setProperty(PREFIX + "exclude." + i, excludes.get(i)); + } + + private static int parseCount(String v) { + try { + return Math.max(0, Integer.parseInt(v.trim())); + } catch (NumberFormatException e) { + return 0; + } + } + + private static Integer parseColor(String v) { + if (v == null || v.isBlank()) return null; + try { + return Integer.parseInt(v.trim().replace("#", ""), 16) & 0xFFFFFF; + } catch (NumberFormatException e) { + return null; + } + } + + private static String formatColor(Integer rgb) { + return rgb == null ? "" : String.format("#%06X", rgb); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/Settings.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/Settings.java new file mode 100644 index 0000000..a88a523 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/Settings.java @@ -0,0 +1,445 @@ +package eu.lixko.ts3j.client.config; + +import eu.lixko.ts3j.client.contacts.ContactDefaults; +import eu.lixko.ts3j.client.sound.NotificationSettings; + +import java.io.File; +import java.io.FileInputStream; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Properties; + +/** + * Simple persistent settings backed by a properties file in the user's home + * directory (~/.ts3jclient/settings.properties). + * + *

    Holds connection defaults, audio device selection and voice-activation + * parameters. Loaded once at startup and saved whenever the user changes + * something in the options dialog. + */ +public final class Settings { + + /** How the microphone decides when to transmit. */ + public enum InputMode { + /** Transmit whenever voice activation detects speech. */ + VOICE_ACTIVATION, + /** Transmit only while the push-to-talk key is held. */ + PUSH_TO_TALK, + /** Always transmit (continuous). */ + CONTINUOUS + } + + /** Which look-and-feel variant the window is painted with. */ + public enum Appearance { + LIGHT, + DARK + } + + /** Voice-activation strategy, mirroring the TS3 client's VAD modes. */ + public enum VadMode { + /** Speech-probability detector only. */ + AUTOMATIC, + /** Volume gate (RMS threshold) only. */ + VOLUME_GATE, + /** Volume gate combined with speech probability. */ + HYBRID + } + + /** Who may whisper to us, the way TeamSpeak's whisper options put it. */ + public enum WhisperPolicy { + /** Use individual settings in contacts, else allow. */ + ALLOW_UNLESS_DENIED("Use individual settings in contacts, else allow"), + /** Use individual settings in contacts, else deny. */ + DENY_UNLESS_ALLOWED("Use individual settings in contacts, else deny"), + /** Nobody is allowed to whisper to you; individual contact settings are ignored. */ + NOBODY("Nobody"); + + private final String label; + + WhisperPolicy(String label) { + this.label = label; + } + + public String label() { + return label; + } + } + + private static File file() { + return AppDirs.file("settings.properties"); + } + + private final Properties props = new Properties(); + + // ---- connection ---- + public String lastAddress = "localhost"; + public String nickname = System.getProperty("user.name", "TS3j User"); + public String serverPassword = ""; + /** Legacy single-identity file; only used to migrate into the identity store. */ + public String identityFile = AppDirs.file("identity.ini").getAbsolutePath(); + /** Id of the identity used when a server doesn't select one of its own. */ + public String defaultIdentityId = ""; + + // ---- reported client version ---- + /** Report {@link #clientVersion}/{@link #clientPlatform} instead of the built-in ones. */ + public boolean customVersion = false; + /** Version string other clients see, e.g. "3.5.6 [Build: 1603963200]". */ + public String clientVersion = ClientVersion.DEFAULT.version(); + /** Operating system other clients see, e.g. "Windows". */ + public String clientPlatform = ClientVersion.DEFAULT.platform(); + /** TeamSpeak's signature over the version and platform; servers may verify it. */ + public String clientVersionSign = ClientVersion.DEFAULT.sign(); + + // ---- audio devices (mixer names; empty = system default) ---- + public String inputDevice = ""; + public String outputDevice = ""; + + // ---- voice ---- + public InputMode inputMode = InputMode.VOICE_ACTIVATION; + /** Voice-activation strategy used when {@link #inputMode} is VOICE_ACTIVATION. */ + public VadMode vadMode = VadMode.HYBRID; + /** + * Volume-gate threshold on {@link eu.lixko.ts3j.client.audio.InputLevel}'s scale, the same one + * the TS3 client's slider uses: -50 (most sensitive) .. +50, defaulting to -40. + */ + public double vadThresholdDb = -40.0; + /** + * Speech-probability threshold (0..1) for Automatic/Hybrid modes. TS3 calls this + * {@code vad_likelihood} and also defaults it to 0.5. + */ + public double speechThreshold = 0.5; + /** Keep voice activation running while in push-to-talk mode. */ + public boolean vadOverPtt = false; + /** Opus target bitrate in bits/sec. */ + public int bitrate = 48000; + /** Opus complexity 0..10. */ + public int complexity = 10; + /** Opus variable bitrate. */ + public boolean vbr = true; + /** Opus in-band forward error correction. */ + public boolean fec = true; + /** Expected packet loss percent (drives FEC). */ + public int packetLoss = 5; + /** Encode as music (OPUS_MUSIC) rather than voice (OPUS_VOICE). */ + public boolean music = false; + /** + * Milliseconds between a voice packet and each of its {@link #redundancyCopies}, 0 for off. + * Listeners' jitter buffers grow to wait for the last copy, so it buys loss resilience with + * about {@code redundancyDelay * redundancyCopies} of latency. + */ + public int redundancyDelay = 0; + /** The {@link #redundancyDelay} choices the settings offer; whole 20 ms voice frames. */ + public static final int[] REDUNDANCY_DELAYS = {0, 20, 40, 60, 80, 120, 200}; + /** How many times every voice packet is sent again. */ + public int redundancyCopies = 1; + public static final int MAX_REDUNDANCY_COPIES = 4; + /** + * Milliseconds of playback delay held on top of what the jitter buffer measures it needs, + * so late packets and error correction copies still make it on a bad connection. + */ + public int receiveBuffer = 0; + /** The {@link #receiveBuffer} choices the settings offer; whole 20 ms voice frames. */ + public static final int[] RECEIVE_BUFFERS = {0, 20, 40, 60, 80, 120, 200, 300, 500}; + /** Master playback gain, 0..1 (may exceed 1 for boost up to 2). */ + public double outputVolume = 1.0; + /** + * Global multiplier on top of {@link #outputVolume} and {@link #soundVolume}, + * controlled from the toolbar's Master Volume slider so both can be ridden + * with one control. 0..2, same boost headroom as the other volumes. + */ + public double masterVolume = 1.0; + /** Microphone input gain multiplier applied before VAD/encode. */ + public double inputVolume = 1.0; + /** Remove steady background noise from the microphone (WebRTC noise suppression). */ + public boolean denoise = true; + /** TS3's {@code denoiser_level}: 0..3 for 6, 12, 18 or 21 dB of suppression. */ + public int denoiserLevel = 1; + /** Attenuate keyboard clicks while typing. */ + public boolean typingAttenuation = true; + /** Automatic gain control: normalise microphone loudness to a target level. */ + public boolean agc = true; + public static final int MAX_AGC_BOOST_DB = 20; + /** How many dB louder AGC may make the background noise to bring up a quiet or distant voice. */ + public int agcBoostDb = 0; + /** Beep when speech is picked up while the microphone is muted. */ + public boolean mutedTalkWarning = true; + + // ---- notification sounds ---- + /** Directory name of the active sound pack; empty picks the first one found. */ + public String soundPack = "default"; + /** Notification sound volume, 0..1. */ + public double soundVolume = 1.0; + /** Extra folder to look for sound packs in, on top of the well-known locations. */ + public String soundPackDir = ""; + /** Whether pokes and private messages show a desktop notification while the window is in the background. */ + public boolean desktopNotifications = true; + // ---- icons ---- + /** File name of the active icon pack; empty uses the built-in icons. */ + public String iconPack = "default_colored_2014.zip"; + /** + * Whether the channel tree shows each client's country flag, as TeamSpeak's EnableCountryFlags; + * their details show it beside their name either way. + */ + public boolean countryFlags = false; + /** Background colours of client rows in the channel tree. */ + public final ClientRowColors clientRowColors = new ClientRowColors(); + /** Extra folder to look for icon packs in, on top of the well-known locations. */ + public String iconPackDir = ""; + + /** Look-and-feel variant; see {@link Appearance}. */ + public Appearance appearance = Appearance.LIGHT; + /** Interface scale factor, 1.0 being 100 %; 0 follows the desktop. Read at startup. */ + public double uiScale = 0; + + // ---- window chrome ---- + /** Whether the status bar at the bottom of the window is shown. */ + public boolean showStatusBar = true; + /** Whether the Master Volume slider is shown on the toolbar. */ + public boolean showMasterVolumeSlider = true; + /** Share of the tree/info column the tree takes, i.e. where their divider sits. */ + public double infoSplitRatio = 0.68; + /** Whether the ban list shows the bans we created ourselves in bold. */ + public boolean banHighlightOwn = true; + /** The ban list columns the user shows, comma-separated column names; empty for the default set. */ + public String banListColumns = ""; + + /** What the Server Log window shows and how. */ + public final ServerLogSettings serverLog = new ServerLogSettings(); + + /** Which actions make a sound, and which ones are important enough to survive muting. */ + public final NotificationSettings notifications = new NotificationSettings(); + + // ---- contacts ---- + /** What a client starts out with when added to the contacts as a friend, blocked or neutral. */ + public final ContactDefaults contactDefaults = new ContactDefaults(); + /** Colour friends and blocked clients in the server tree, as the TeamSpeak client does. */ + public boolean colorContacts = true; + /** Whose whispers are played. */ + public WhisperPolicy whisperPolicy = WhisperPolicy.ALLOW_UNLESS_DENIED; + + /** Keep chat logs, and show their history when a chat opens. */ + public boolean chatLogs = true; + /** Where chat logs go; empty for the TeamSpeak 3 client's own folder, so both share them. */ + public String chatLogDir = ""; + /** The folder recordings were last saved to; empty for {@code ~/Recordings}. */ + public String recordingDir = ""; + /** Whether descriptions show their pictures, fetched from the web, or only links to them. */ + public boolean descriptionPictures = true; + /** Ctrl+wheel zoom of the chat's text and pictures, 1.0 being 100 %. */ + public double chatZoom = 1.0; + /** Ctrl+wheel zoom of the info panel's text and pictures, 1.0 being 100 %. */ + public double infoZoom = 1.0; + + public static Settings load() { + Settings s = new Settings(); + try { + if (file().isFile()) { + try (FileInputStream in = new FileInputStream(file())) { + s.props.load(in); + } + s.applyFromProps(); + } + } catch (Exception ignored) { + // Corrupt/unreadable settings -> fall back to defaults. + } + return s; + } + + public void save() { + try { + AppDirs.createProfile(); + writeToProps(); + ProfileFiles.write(file(), out -> props.store(out, "TeamSpook TS3j settings")); + } catch (Exception ignored) { + } + } + + public File identityFile() { + return new File(identityFile); + } + + public Path recordingFolder() { + return recordingDir.isBlank() + ? Paths.get(System.getProperty("user.home", "."), "Recordings") + : Paths.get(recordingDir); + } + + /** {@link #outputVolume} scaled by the Master Volume slider. */ + public double effectiveOutputVolume() { + return outputVolume * masterVolume; + } + + /** {@link #soundVolume} scaled by the Master Volume slider. */ + public double effectiveSoundVolume() { + return soundVolume * masterVolume; + } + + private void applyFromProps() { + lastAddress = props.getProperty("lastAddress", lastAddress); + nickname = props.getProperty("nickname", nickname); + serverPassword = props.getProperty("serverPassword", serverPassword); + identityFile = props.getProperty("identityFile", identityFile); + defaultIdentityId = props.getProperty("defaultIdentityId", defaultIdentityId); + customVersion = parseB(props.getProperty("customVersion"), customVersion); + clientVersion = props.getProperty("clientVersion", clientVersion); + clientPlatform = props.getProperty("clientPlatform", clientPlatform); + clientVersionSign = props.getProperty("clientVersionSign", clientVersionSign); + inputDevice = props.getProperty("inputDevice", inputDevice); + outputDevice = props.getProperty("outputDevice", outputDevice); + inputMode = parseEnum(InputMode.class, props.getProperty("inputMode"), inputMode); + vadMode = parseEnum(VadMode.class, props.getProperty("vadMode"), vadMode); + vadThresholdDb = parseD(props.getProperty("vadLevelDb"), + migrateThreshold(props.getProperty("vadThresholdDb"), vadThresholdDb)); + speechThreshold = parseD(props.getProperty("speechThreshold"), speechThreshold); + vadOverPtt = parseB(props.getProperty("vadOverPtt"), vadOverPtt); + bitrate = parseI(props.getProperty("bitrate"), bitrate); + complexity = parseI(props.getProperty("complexity"), complexity); + vbr = parseB(props.getProperty("vbr"), vbr); + fec = parseB(props.getProperty("fec"), fec); + packetLoss = parseI(props.getProperty("packetLoss"), packetLoss); + music = parseB(props.getProperty("music"), music); + redundancyDelay = parseI(props.getProperty("redundancyDelay"), redundancyDelay); + redundancyCopies = parseI(props.getProperty("redundancyCopies"), redundancyCopies); + receiveBuffer = parseI(props.getProperty("receiveBuffer"), receiveBuffer); + outputVolume = parseD(props.getProperty("outputVolume"), outputVolume); + masterVolume = parseD(props.getProperty("masterVolume"), masterVolume); + inputVolume = parseD(props.getProperty("inputVolume"), inputVolume); + denoise = parseB(props.getProperty("denoise"), denoise); + denoiserLevel = parseI(props.getProperty("denoiserLevel"), denoiserLevel); + typingAttenuation = parseB(props.getProperty("typingAttenuation"), typingAttenuation); + mutedTalkWarning = parseB(props.getProperty("mutedTalkWarning"), mutedTalkWarning); + agc = parseB(props.getProperty("agc"), agc); + agcBoostDb = Math.max(0, Math.min(MAX_AGC_BOOST_DB, parseI(props.getProperty("agcBoostDb"), agcBoostDb))); + soundPack = props.getProperty("soundPack", soundPack); + soundVolume = parseD(props.getProperty("soundVolume"), soundVolume); + soundPackDir = props.getProperty("soundPackDir", soundPackDir); + desktopNotifications = parseB(props.getProperty("desktopNotifications"), desktopNotifications); + iconPack = props.getProperty("iconPack", iconPack); + countryFlags = parseB(props.getProperty("countryFlags"), countryFlags); + clientRowColors.load(props); + iconPackDir = props.getProperty("iconPackDir", iconPackDir); + appearance = parseEnum(Appearance.class, props.getProperty("appearance"), appearance); + uiScale = parseD(props.getProperty("uiScale"), uiScale); + showStatusBar = parseB(props.getProperty("showStatusBar"), showStatusBar); + showMasterVolumeSlider = parseB(props.getProperty("showMasterVolumeSlider"), showMasterVolumeSlider); + infoSplitRatio = parseD(props.getProperty("infoSplitRatio"), infoSplitRatio); + banHighlightOwn = parseB(props.getProperty("banHighlightOwn"), banHighlightOwn); + banListColumns = props.getProperty("banListColumns", banListColumns); + notifications.load(props); + serverLog.load(props); + contactDefaults.load(props); + colorContacts = parseB(props.getProperty("colorContacts"), colorContacts); + descriptionPictures = parseB(props.getProperty("descriptionPictures"), descriptionPictures); + whisperPolicy = parseEnum(WhisperPolicy.class, props.getProperty("whisperPolicy"), whisperPolicy); + chatLogs = parseB(props.getProperty("chatLogs"), chatLogs); + chatLogDir = props.getProperty("chatLogDir", chatLogDir); + recordingDir = props.getProperty("recordingDir", recordingDir); + } + + private void writeToProps() { + props.setProperty("lastAddress", lastAddress); + props.setProperty("nickname", nickname); + props.setProperty("serverPassword", serverPassword); + props.setProperty("identityFile", identityFile); + props.setProperty("defaultIdentityId", defaultIdentityId); + props.setProperty("customVersion", Boolean.toString(customVersion)); + props.setProperty("clientVersion", clientVersion); + props.setProperty("clientPlatform", clientPlatform); + props.setProperty("clientVersionSign", clientVersionSign); + props.setProperty("inputDevice", inputDevice); + props.setProperty("outputDevice", outputDevice); + props.setProperty("inputMode", inputMode.name()); + props.setProperty("vadMode", vadMode.name()); + props.setProperty("vadLevelDb", Double.toString(vadThresholdDb)); + props.remove("vadThresholdDb"); + props.setProperty("speechThreshold", Double.toString(speechThreshold)); + props.setProperty("vadOverPtt", Boolean.toString(vadOverPtt)); + props.setProperty("bitrate", Integer.toString(bitrate)); + props.setProperty("complexity", Integer.toString(complexity)); + props.setProperty("vbr", Boolean.toString(vbr)); + props.setProperty("fec", Boolean.toString(fec)); + props.setProperty("packetLoss", Integer.toString(packetLoss)); + props.setProperty("music", Boolean.toString(music)); + props.setProperty("redundancyDelay", Integer.toString(redundancyDelay)); + props.setProperty("redundancyCopies", Integer.toString(redundancyCopies)); + props.setProperty("receiveBuffer", Integer.toString(receiveBuffer)); + props.setProperty("outputVolume", Double.toString(outputVolume)); + props.setProperty("masterVolume", Double.toString(masterVolume)); + props.setProperty("inputVolume", Double.toString(inputVolume)); + props.setProperty("denoise", Boolean.toString(denoise)); + props.setProperty("denoiserLevel", Integer.toString(denoiserLevel)); + props.setProperty("typingAttenuation", Boolean.toString(typingAttenuation)); + props.setProperty("mutedTalkWarning", Boolean.toString(mutedTalkWarning)); + props.setProperty("agc", Boolean.toString(agc)); + props.setProperty("agcBoostDb", Integer.toString(agcBoostDb)); + props.setProperty("soundPack", soundPack); + props.setProperty("soundVolume", Double.toString(soundVolume)); + props.setProperty("soundPackDir", soundPackDir); + props.setProperty("desktopNotifications", Boolean.toString(desktopNotifications)); + props.setProperty("iconPack", iconPack); + props.setProperty("countryFlags", Boolean.toString(countryFlags)); + clientRowColors.store(props); + props.setProperty("iconPackDir", iconPackDir); + props.setProperty("appearance", appearance.name()); + props.setProperty("uiScale", Double.toString(uiScale)); + props.setProperty("showStatusBar", Boolean.toString(showStatusBar)); + props.setProperty("showMasterVolumeSlider", Boolean.toString(showMasterVolumeSlider)); + props.setProperty("infoSplitRatio", Double.toString(infoSplitRatio)); + props.setProperty("banHighlightOwn", Boolean.toString(banHighlightOwn)); + props.setProperty("banListColumns", banListColumns); + notifications.store(props); + serverLog.store(props); + contactDefaults.store(props); + props.setProperty("colorContacts", Boolean.toString(colorContacts)); + props.setProperty("descriptionPictures", Boolean.toString(descriptionPictures)); + props.setProperty("whisperPolicy", whisperPolicy.name()); + props.setProperty("chatLogs", Boolean.toString(chatLogs)); + props.setProperty("chatLogDir", chatLogDir); + props.setProperty("recordingDir", recordingDir); + } + + private static > E parseEnum(Class type, String v, E def) { + if (v == null) return def; + try { + return Enum.valueOf(type, v.trim()); + } catch (IllegalArgumentException e) { + return def; + } + } + + /** + * Converts a threshold saved under the old {@code vadThresholdDb} key, which was in + * dBFS ({@code 20*log10(rms)}), to {@link eu.lixko.ts3j.client.audio.InputLevel}'s scale, so + * upgrading doesn't silently change how sensitive the gate is. + */ + private static double migrateThreshold(String legacy, double def) { + double dbfs = parseD(legacy, Double.NaN); + if (Double.isNaN(dbfs)) { + return def; + } + double converted = eu.lixko.ts3j.client.audio.InputLevel.powerToDb(Math.pow(10.0, dbfs / 10.0)); + return Math.min(eu.lixko.ts3j.client.audio.InputLevel.MAX_DB, converted); + } + + private static double parseD(String v, double def) { + if (v == null) return def; + try { + return Double.parseDouble(v); + } catch (NumberFormatException e) { + return def; + } + } + + private static int parseI(String v, int def) { + if (v == null) return def; + try { + return Integer.parseInt(v); + } catch (NumberFormatException e) { + return def; + } + } + + private static boolean parseB(String v, boolean def) { + return v == null ? def : Boolean.parseBoolean(v); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/WhisperList.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/WhisperList.java new file mode 100644 index 0000000..16b4706 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/WhisperList.java @@ -0,0 +1,40 @@ +package eu.lixko.ts3j.client.config; + +import java.util.ArrayList; +import java.util.List; + +/** A saved set of channels and clients to whisper to, wherever they are on the server we are on. */ +public final class WhisperList { + + /** A client by unique id, so the list finds them under any client id; the nickname is for showing. */ + public record Client(String uniqueId, String nickname) { + } + + public String name = ""; + /** Channel references as {@link Bookmark#channel} holds them: "/"-separated paths or "/<id>". */ + public final List channels = new ArrayList<>(); + public final List clients = new ArrayList<>(); + + public WhisperList() { + } + + public WhisperList(String name) { + this.name = name; + } + + public WhisperList copy() { + WhisperList c = new WhisperList(name); + c.channels.addAll(channels); + c.clients.addAll(clients); + return c; + } + + public boolean isEmpty() { + return channels.isEmpty() && clients.isEmpty(); + } + + @Override + public String toString() { + return name; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/WhisperLists.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/WhisperLists.java new file mode 100644 index 0000000..55f7c5f --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/WhisperLists.java @@ -0,0 +1,93 @@ +package eu.lixko.ts3j.client.config; + +import java.io.File; +import java.io.FileInputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +/** The saved {@link WhisperList}s, shared by every server. */ +public final class WhisperLists { + + private static File file() { + return AppDirs.file("whisperlists.properties"); + } + + private final List entries = new ArrayList<>(); + + public List all() { + return entries; + } + + /** The list with this name, ignoring case, or null. */ + public WhisperList find(String name) { + for (WhisperList l : entries) { + if (l.name.equalsIgnoreCase(name)) return l; + } + return null; + } + + public static WhisperLists load() { + WhisperLists lists = new WhisperLists(); + if (!file().isFile()) return lists; + Properties p = new Properties(); + try (FileInputStream in = new FileInputStream(file())) { + p.load(in); + } catch (Exception e) { + return lists; + } + int count = parseInt(p.getProperty("count")); + for (int i = 0; i < count; i++) { + String prefix = "list." + i + "."; + WhisperList list = new WhisperList(p.getProperty(prefix + "name", "")); + int channels = parseInt(p.getProperty(prefix + "channels")); + for (int j = 0; j < channels; j++) { + String channel = p.getProperty(prefix + "channel." + j, ""); + if (!channel.isBlank()) list.channels.add(channel); + } + int clients = parseInt(p.getProperty(prefix + "clients")); + for (int j = 0; j < clients; j++) { + String uid = p.getProperty(prefix + "client." + j + ".uid", ""); + if (!uid.isBlank()) { + list.clients.add(new WhisperList.Client(uid, p.getProperty(prefix + "client." + j + ".name", ""))); + } + } + lists.entries.add(list); + } + return lists; + } + + public void save() { + Properties p = new Properties(); + p.setProperty("count", Integer.toString(entries.size())); + for (int i = 0; i < entries.size(); i++) { + WhisperList list = entries.get(i); + String prefix = "list." + i + "."; + p.setProperty(prefix + "name", list.name); + p.setProperty(prefix + "channels", Integer.toString(list.channels.size())); + for (int j = 0; j < list.channels.size(); j++) { + p.setProperty(prefix + "channel." + j, list.channels.get(j)); + } + p.setProperty(prefix + "clients", Integer.toString(list.clients.size())); + for (int j = 0; j < list.clients.size(); j++) { + WhisperList.Client c = list.clients.get(j); + p.setProperty(prefix + "client." + j + ".uid", c.uniqueId()); + p.setProperty(prefix + "client." + j + ".name", c.nickname() == null ? "" : c.nickname()); + } + } + try { + AppDirs.createProfile(); + ProfileFiles.write(file(), out -> p.store(out, "TeamSpook TS3j whisper lists")); + } catch (Exception ignored) { + } + } + + private static int parseInt(String v) { + if (v == null) return 0; + try { + return Integer.parseInt(v.trim()); + } catch (NumberFormatException e) { + return 0; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/contacts/Contact.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/contacts/Contact.java new file mode 100644 index 0000000..bfbab93 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/contacts/Contact.java @@ -0,0 +1,199 @@ +package eu.lixko.ts3j.client.contacts; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Map; + +/** + * One entry of the contact list, keyed by the client's unique id. + * + *

    The fields are exactly the ones the TeamSpeak 3 client keeps for a contact, + * and {@link #toRecord()} / {@link #parseRecord} use its own {@code Key=Value} + * serialisation (the {@code value} column of its {@code Contacts} table), so + * records can be exchanged with it as they are. + */ +public final class Contact { + + /** TeamSpeak writes {@code LastSeen} as an ISO local date-time without zone. */ + private static final DateTimeFormatter LAST_SEEN = DateTimeFormatter.ISO_LOCAL_DATE_TIME; + + public final String uniqueId; + /** Custom name; TeamSpeak seeds it with the nickname the client had when added. */ + public String nickname = ""; + public String phoneticNickname = ""; + public ContactType type = ContactType.NEUTRAL; + public boolean automute; + public boolean ignorePublicMessages; + public boolean ignorePrivateMessages; + public boolean ignorePokes; + public boolean ignoreAvatar; + public boolean ignoreAwayMessage; + public NicknameDisplay nicknameDisplay = NicknameDisplay.BOTH; + public boolean hasVolumeModifier; + /** Playback gain for this client in dB, applied when {@link #hasVolumeModifier} is set. */ + public double volumeModifier; + public boolean whisperAllowed = true; + /** When the contact was last seen online, or {@code null} for never. */ + public LocalDateTime lastSeen; + public String lastSeenServerName = ""; + public String lastSeenServerAddress = ""; + + public Contact(String uniqueId) { + this.uniqueId = uniqueId == null ? "" : uniqueId; + } + + /** The name the contact is shown under, given the nickname it currently carries. */ + public String displayName(String currentNickname) { + return nicknameDisplay.render(nickname, currentNickname); + } + + /** Playback gain as a linear multiplier, 1.0 when no modifier is set. */ + public double volumeGain() { + return hasVolumeModifier ? Math.pow(10.0, volumeModifier / 20.0) : 1.0; + } + + public Contact copy() { + Contact c = new Contact(uniqueId); + c.copyFrom(this); + return c; + } + + /** Takes over every field but the unique id. */ + public void copyFrom(Contact other) { + nickname = other.nickname; + phoneticNickname = other.phoneticNickname; + type = other.type; + automute = other.automute; + ignorePublicMessages = other.ignorePublicMessages; + ignorePrivateMessages = other.ignorePrivateMessages; + ignorePokes = other.ignorePokes; + ignoreAvatar = other.ignoreAvatar; + ignoreAwayMessage = other.ignoreAwayMessage; + nicknameDisplay = other.nicknameDisplay; + hasVolumeModifier = other.hasVolumeModifier; + volumeModifier = other.volumeModifier; + whisperAllowed = other.whisperAllowed; + lastSeen = other.lastSeen; + lastSeenServerName = other.lastSeenServerName; + lastSeenServerAddress = other.lastSeenServerAddress; + } + + /** Applies the per-type defaults, as done when a client is first added. */ + public void applyDefaults(ContactDefaults.Entry defaults) { + nicknameDisplay = defaults.nicknameDisplay; + automute = defaults.automute; + ignorePublicMessages = defaults.ignorePublicMessages; + ignorePrivateMessages = defaults.ignorePrivateMessages; + ignorePokes = defaults.ignorePokes; + ignoreAvatar = defaults.ignoreAvatar; + ignoreAwayMessage = defaults.ignoreAwayMessage; + whisperAllowed = !defaults.ignoreWhisper; + } + + // ---- TeamSpeak record format ---- + + /** The contact as TeamSpeak's {@code Key=Value} lines, in the order it writes them. */ + public String toRecord() { + StringBuilder sb = new StringBuilder(); + line(sb, "IDS", uniqueId); + line(sb, "Nickname", nickname); + line(sb, "Friend", Integer.toString(type.code())); + line(sb, "Automute", flag(automute)); + line(sb, "IgnorePublicMessages", flag(ignorePublicMessages)); + line(sb, "IgnorePrivateMessages", flag(ignorePrivateMessages)); + line(sb, "IgnorePokes", flag(ignorePokes)); + line(sb, "IgnoreAvatar", flag(ignoreAvatar)); + line(sb, "IgnoreAwayMessage", flag(ignoreAwayMessage)); + line(sb, "NickShowType", Integer.toString(nicknameDisplay.code())); + line(sb, "HaveVolumeModifier", flag(hasVolumeModifier)); + line(sb, "VolumeModifier", formatVolume(volumeModifier)); + line(sb, "WhisperAllow", flag(whisperAllowed)); + line(sb, "PhoneticNickname", phoneticNickname); + line(sb, "LastSeen", lastSeen == null ? "" : LAST_SEEN.format(lastSeen)); + line(sb, "LastSeenServerName", lastSeenServerName); + line(sb, "LastSeenServerAddress", lastSeenServerAddress); + return sb.toString(); + } + + /** Parses a TeamSpeak contact record, or returns {@code null} when it carries no unique id. */ + public static Contact parseRecord(String record) { + if (record == null) return null; + Map fields = new LinkedHashMap<>(); + for (String line : record.split("\r?\n")) { + int eq = line.indexOf('='); + if (eq > 0) fields.put(line.substring(0, eq).trim(), line.substring(eq + 1)); + } + String uid = fields.getOrDefault("IDS", "").trim(); + if (uid.isEmpty()) return null; + + Contact c = new Contact(uid); + c.nickname = fields.getOrDefault("Nickname", ""); + c.type = ContactType.fromCode(parseInt(fields.get("Friend"), ContactType.NEUTRAL.code())); + c.automute = parseFlag(fields.get("Automute")); + c.ignorePublicMessages = parseFlag(fields.get("IgnorePublicMessages")); + c.ignorePrivateMessages = parseFlag(fields.get("IgnorePrivateMessages")); + c.ignorePokes = parseFlag(fields.get("IgnorePokes")); + c.ignoreAvatar = parseFlag(fields.get("IgnoreAvatar")); + c.ignoreAwayMessage = parseFlag(fields.get("IgnoreAwayMessage")); + c.nicknameDisplay = NicknameDisplay.fromCode(parseInt(fields.get("NickShowType"), 0)); + c.hasVolumeModifier = parseFlag(fields.get("HaveVolumeModifier")); + c.volumeModifier = parseDouble(fields.get("VolumeModifier"), 0); + c.whisperAllowed = !fields.containsKey("WhisperAllow") || parseFlag(fields.get("WhisperAllow")); + c.phoneticNickname = fields.getOrDefault("PhoneticNickname", ""); + c.lastSeen = parseLastSeen(fields.get("LastSeen")); + c.lastSeenServerName = fields.getOrDefault("LastSeenServerName", ""); + // TeamSpeak's own writer misspells the key in one of its code paths. + c.lastSeenServerAddress = fields.getOrDefault("LastSeenServerAddress", + fields.getOrDefault("LastSeenServerAddres", "")); + return c; + } + + private static void line(StringBuilder sb, String key, String value) { + sb.append(key).append('=').append(value == null ? "" : value.replace("\n", " ")).append('\n'); + } + + private static String flag(boolean b) { + return b ? "1" : "0"; + } + + private static String formatVolume(double db) { + if (db == Math.rint(db)) return Integer.toString((int) db); + return String.format(Locale.ROOT, "%.2f", db); + } + + private static boolean parseFlag(String v) { + if (v == null) return false; + String t = v.trim(); + return t.equals("1") || t.equalsIgnoreCase("true"); + } + + private static int parseInt(String v, int def) { + if (v == null) return def; + try { + return Integer.parseInt(v.trim()); + } catch (NumberFormatException e) { + return def; + } + } + + private static double parseDouble(String v, double def) { + if (v == null) return def; + try { + return Double.parseDouble(v.trim()); + } catch (NumberFormatException e) { + return def; + } + } + + private static LocalDateTime parseLastSeen(String v) { + if (v == null || v.isBlank()) return null; + try { + return LocalDateTime.parse(v.trim(), LAST_SEEN); + } catch (DateTimeParseException e) { + return null; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/contacts/ContactDefaults.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/contacts/ContactDefaults.java new file mode 100644 index 0000000..c1df656 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/contacts/ContactDefaults.java @@ -0,0 +1,99 @@ +package eu.lixko.ts3j.client.contacts; + +import java.util.Properties; + +/** + * What a newly added contact starts out with, kept separately for friends, blocked + * and neutral clients — TeamSpeak's "Contact Manager Default Settings". + */ +public final class ContactDefaults { + + /** The defaults for one contact type. */ + public static final class Entry { + public NicknameDisplay nicknameDisplay = NicknameDisplay.BOTH; + public boolean automute; + public boolean ignorePublicMessages; + public boolean ignorePrivateMessages; + public boolean ignorePokes; + public boolean ignoreAvatar; + public boolean ignoreAwayMessage; + public boolean ignoreWhisper; + + public void copyFrom(Entry other) { + nicknameDisplay = other.nicknameDisplay; + automute = other.automute; + ignorePublicMessages = other.ignorePublicMessages; + ignorePrivateMessages = other.ignorePrivateMessages; + ignorePokes = other.ignorePokes; + ignoreAvatar = other.ignoreAvatar; + ignoreAwayMessage = other.ignoreAwayMessage; + ignoreWhisper = other.ignoreWhisper; + } + + private void load(Properties p, String prefix) { + nicknameDisplay = parseDisplay(p.getProperty(prefix + "nicknameDisplay"), nicknameDisplay); + automute = parseB(p.getProperty(prefix + "automute"), automute); + ignorePublicMessages = parseB(p.getProperty(prefix + "ignorePublicMessages"), ignorePublicMessages); + ignorePrivateMessages = parseB(p.getProperty(prefix + "ignorePrivateMessages"), ignorePrivateMessages); + ignorePokes = parseB(p.getProperty(prefix + "ignorePokes"), ignorePokes); + ignoreAvatar = parseB(p.getProperty(prefix + "ignoreAvatar"), ignoreAvatar); + ignoreAwayMessage = parseB(p.getProperty(prefix + "ignoreAwayMessage"), ignoreAwayMessage); + ignoreWhisper = parseB(p.getProperty(prefix + "ignoreWhisper"), ignoreWhisper); + } + + private void store(Properties p, String prefix) { + p.setProperty(prefix + "nicknameDisplay", nicknameDisplay.name()); + p.setProperty(prefix + "automute", Boolean.toString(automute)); + p.setProperty(prefix + "ignorePublicMessages", Boolean.toString(ignorePublicMessages)); + p.setProperty(prefix + "ignorePrivateMessages", Boolean.toString(ignorePrivateMessages)); + p.setProperty(prefix + "ignorePokes", Boolean.toString(ignorePokes)); + p.setProperty(prefix + "ignoreAvatar", Boolean.toString(ignoreAvatar)); + p.setProperty(prefix + "ignoreAwayMessage", Boolean.toString(ignoreAwayMessage)); + p.setProperty(prefix + "ignoreWhisper", Boolean.toString(ignoreWhisper)); + } + } + + private static final String PREFIX = "contacts.defaults."; + + private final Entry friend = new Entry(); + private final Entry blocked = new Entry(); + private final Entry neutral = new Entry(); + + public Entry of(ContactType type) { + switch (type) { + case FRIEND: + return friend; + case BLOCKED: + return blocked; + default: + return neutral; + } + } + + public void copyFrom(ContactDefaults other) { + friend.copyFrom(other.friend); + blocked.copyFrom(other.blocked); + neutral.copyFrom(other.neutral); + } + + public void load(Properties p) { + for (ContactType t : ContactType.values()) of(t).load(p, PREFIX + t.name().toLowerCase() + "."); + } + + public void store(Properties p) { + for (ContactType t : ContactType.values()) of(t).store(p, PREFIX + t.name().toLowerCase() + "."); + } + + private static boolean parseB(String v, boolean def) { + return v == null ? def : Boolean.parseBoolean(v.trim()); + } + + private static NicknameDisplay parseDisplay(String v, NicknameDisplay def) { + if (v == null) return def; + try { + return NicknameDisplay.valueOf(v.trim()); + } catch (IllegalArgumentException e) { + return def; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/contacts/ContactStore.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/contacts/ContactStore.java new file mode 100644 index 0000000..c79356c --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/contacts/ContactStore.java @@ -0,0 +1,267 @@ +package eu.lixko.ts3j.client.contacts; + +import eu.lixko.ts3j.client.config.AppDirs; +import eu.lixko.ts3j.client.config.ProfileFiles; +import eu.lixko.ts3j.client.teamspeak.TeamSpeakSettingsDb; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * The contact list (TeamSpeak's "Friend/Foe manager"): who is a friend, who is + * blocked, and how each of them is displayed and filtered. + * + *

    Persisted in {@code ~/.ts3jclient/contacts.txt} as TeamSpeak's own contact + * records separated by blank lines — the same text the official client keeps in + * the {@code Contacts} table of its {@code settings.db}, so entries can be moved + * between the two verbatim. On first run the list is seeded from an installed + * TeamSpeak client's database, when one is found. + * + *

    Safe to use from any thread: lookups are lock-free on a snapshot, and + * mutations are serialised and announced to listeners on the calling thread. + */ +public final class ContactStore { + + /** How long a sighting may wait before it is written. */ + static final long SEEN_SAVE_DELAY_S = 30; + + /** Told after the list changed in any way; called on whatever thread made the change. */ + public interface Listener { + void onContactsChanged(); + } + + private static File file() { + return AppDirs.file("contacts.txt"); + } + + private final File file; + private final Map byUid = new LinkedHashMap<>(); + /** Immutable snapshot for readers, replaced under the lock after every change. */ + private volatile List snapshot = List.of(); + private final List listeners = new CopyOnWriteArrayList<>(); + /** Set while a sighting waits for {@link #flush()}; any save takes it along. */ + private final AtomicBoolean savePending = new AtomicBoolean(); + private final ScheduledExecutorService saver = Executors.newSingleThreadScheduledExecutor(r -> { + Thread t = new Thread(r, "contacts-save"); + t.setDaemon(true); + return t; + }); + + ContactStore(File file) { + this.file = file; + } + + /** Loads the list, seeding it from the TeamSpeak 3 client's database the first time round. */ + public static ContactStore load() { + File file = file(); + ContactStore store = new ContactStore(file); + if (file.isFile()) { + store.readFile(); + } else { + List imported = TeamSpeakSettingsDb.readContacts(); + if (!imported.isEmpty()) { + store.replaceAll(imported); + store.save(); + } + } + return store; + } + + void readFile() { + String text; + try { + // Android < API 36.1 lacks Files.readString; original: + // text = Files.readString(file.toPath(), StandardCharsets.UTF_8); + text = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); + } catch (IOException e) { + return; + } + List parsed = new ArrayList<>(); + for (String record : text.split("\\r?\\n\\s*\\r?\\n")) { + Contact c = Contact.parseRecord(record); + if (c != null) parsed.add(c); + } + synchronized (this) { + byUid.clear(); + for (Contact c : parsed) byUid.put(c.uniqueId, c); + snapshot = List.copyOf(byUid.values()); + } + } + + public void save() { + savePending.set(false); + List all = snapshot; + StringBuilder sb = new StringBuilder(); + for (Contact c : all) { + if (sb.length() > 0) sb.append('\n'); + sb.append(c.toRecord()); + } + try { + AppDirs.createProfile(); + ProfileFiles.write(file, out -> out.write(sb.toString().getBytes(StandardCharsets.UTF_8))); + } catch (IOException ignored) { + } + } + + public void addListener(Listener l) { + listeners.add(l); + } + + public void removeListener(Listener l) { + listeners.remove(l); + } + + // ---- lookups ---- + + /** Every contact, in list order. */ + public List all() { + return snapshot; + } + + public Contact find(String uniqueId) { + if (uniqueId == null || uniqueId.isEmpty()) return null; + for (Contact c : snapshot) { + if (c.uniqueId.equals(uniqueId)) return c; + } + return null; + } + + /** The type a client is filed under, {@code null} when it is not a contact. */ + public ContactType typeOf(String uniqueId) { + Contact c = find(uniqueId); + return c == null ? null : c.type; + } + + /** The name a client should be shown under: its contact's custom name, else the nickname. */ + public String displayName(String uniqueId, String nickname) { + Contact c = find(uniqueId); + return c == null ? nickname : c.displayName(nickname); + } + + // ---- mutations ---- + + /** + * Files a client as a contact of the given type, applying the type's defaults to + * a new entry and only re-typing an existing one. + * + * @return the resulting contact + */ + public Contact add(String uniqueId, String nickname, ContactType type, ContactDefaults defaults) { + Contact contact; + synchronized (this) { + contact = byUid.get(uniqueId); + if (contact == null) { + contact = new Contact(uniqueId); + contact.nickname = nickname == null ? "" : nickname; + contact.applyDefaults(defaults.of(type)); + byUid.put(uniqueId, contact); + } + contact.type = type; + snapshot = List.copyOf(byUid.values()); + } + changed(); + return contact; + } + + /** Stores an edited contact, replacing any entry with the same unique id. */ + public void put(Contact contact) { + synchronized (this) { + Contact existing = byUid.get(contact.uniqueId); + if (existing != null && existing != contact) existing.copyFrom(contact); + else byUid.put(contact.uniqueId, contact); + snapshot = List.copyOf(byUid.values()); + } + changed(); + } + + public void remove(String uniqueId) { + synchronized (this) { + if (byUid.remove(uniqueId) == null) return; + snapshot = List.copyOf(byUid.values()); + } + changed(); + } + + /** Takes over a whole list, e.g. one read from the TeamSpeak client. */ + public void replaceAll(Collection contacts) { + synchronized (this) { + byUid.clear(); + for (Contact c : contacts) byUid.put(c.uniqueId, c); + snapshot = List.copyOf(byUid.values()); + } + changed(); + } + + /** + * Merges contacts read from elsewhere: entries for clients not on the list yet are + * added, existing ones are overwritten. + * + * @return how many entries were new + */ + public int merge(Collection contacts) { + int added = 0; + synchronized (this) { + for (Contact c : contacts) { + if (byUid.put(c.uniqueId, c) == null) added++; + } + snapshot = List.copyOf(byUid.values()); + } + changed(); + return added; + } + + /** + * Notes that a contact is online right now. A sighting within the same minute on the + * same server changes nothing. Sightings reach the file in one go, {@link + * #SEEN_SAVE_DELAY_S} later or with the next save, so a busy server does not rewrite it + * per event. + */ + public void markSeen(String uniqueId, String serverName, String serverAddress) { + Contact c = find(uniqueId); + if (c == null) return; + LocalDateTime now = LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS); + synchronized (this) { + if (c.lastSeen != null && ChronoUnit.MINUTES.between(c.lastSeen, now) < 1 + && c.lastSeenServerAddress.equals(orEmpty(serverAddress))) { + return; + } + c.lastSeen = now; + c.lastSeenServerName = orEmpty(serverName); + c.lastSeenServerAddress = orEmpty(serverAddress); + } + if (savePending.compareAndSet(false, true)) saver.schedule(this::flush, SEEN_SAVE_DELAY_S, TimeUnit.SECONDS); + announce(); + } + + /** Writes sightings still waiting to be saved; for when the client goes away. */ + public void flush() { + if (savePending.get()) save(); + } + + private void changed() { + save(); + announce(); + } + + private void announce() { + for (Listener l : listeners) l.onContactsChanged(); + } + + private static String orEmpty(String s) { + return s == null ? "" : s; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/contacts/ContactType.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/contacts/ContactType.java new file mode 100644 index 0000000..fbc6291 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/contacts/ContactType.java @@ -0,0 +1,29 @@ +package eu.lixko.ts3j.client.contacts; + +/** How a contact is classed; the codes are the ones TeamSpeak stores in {@code Friend=}. */ +public enum ContactType { + FRIEND(0, "Friend"), + BLOCKED(1, "Blocked"), + NEUTRAL(2, "Neutral"); + + private final int code; + private final String label; + + ContactType(int code, String label) { + this.code = code; + this.label = label; + } + + public int code() { + return code; + } + + public String label() { + return label; + } + + public static ContactType fromCode(int code) { + for (ContactType t : values()) if (t.code == code) return t; + return NEUTRAL; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/contacts/NicknameDisplay.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/contacts/NicknameDisplay.java new file mode 100644 index 0000000..8b3b094 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/contacts/NicknameDisplay.java @@ -0,0 +1,43 @@ +package eu.lixko.ts3j.client.contacts; + +/** Which name a contact is shown under; the codes are TeamSpeak's {@code NickShowType=}. */ +public enum NicknameDisplay { + /** "Custom name and nickname": the custom name with the live nickname in brackets. */ + BOTH(0, "Custom name and nickname"), + ONLY_CUSTOM(1, "Only custom name"), + ONLY_NICKNAME(2, "Only nickname"); + + private final int code; + private final String label; + + NicknameDisplay(int code, String label) { + this.code = code; + this.label = label; + } + + public int code() { + return code; + } + + public String label() { + return label; + } + + public static NicknameDisplay fromCode(int code) { + for (NicknameDisplay d : values()) if (d.code == code) return d; + return BOTH; + } + + /** Renders a nickname the way this mode asks for it; a blank custom name always yields the nickname. */ + public String render(String customName, String nickname) { + if (customName == null || customName.isBlank()) return nickname; + switch (this) { + case ONLY_CUSTOM: + return customName; + case ONLY_NICKNAME: + return nickname; + default: + return customName.equals(nickname) ? nickname : customName + " (" + nickname + ")"; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/gfx/CountryFlags.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/gfx/CountryFlags.java new file mode 100644 index 0000000..f44f60d --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/gfx/CountryFlags.java @@ -0,0 +1,86 @@ +package eu.lixko.ts3j.client.gfx; + +import eu.lixko.ts3j.client.config.InstallDirs; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.IllformedLocaleException; +import java.util.Locale; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +/** + * The flags TeamSpeak shows for the country the server places a client in: the + * {@code .png} files of its {@code countries.zip}, the one the build shipped, else + * a TeamSpeak 3 install's. + */ +public final class CountryFlags { + + private static final String RESOURCE = "/gfx/teamspeak/countries.zip"; + private static final String FILE = "countries.zip"; + + private static volatile Map flags; + + private CountryFlags() { + } + + /** @return the flag's PNG bytes, or {@code null} for an unknown or empty code */ + public static byte[] png(String code) { + if (code == null || code.isEmpty()) return null; + return flags().get(code.toLowerCase(Locale.ROOT)); + } + + /** @return the country's English name, or the code itself when it names none */ + public static String name(String code) { + try { + String name = new Locale.Builder().setRegion(code).build().getDisplayCountry(Locale.ENGLISH); + return name.isEmpty() ? code : name; + } catch (IllformedLocaleException e) { + return code; + } + } + + private static Map flags() { + Map loaded = flags; + if (loaded != null) return loaded; + synchronized (CountryFlags.class) { + if (flags == null) flags = load(); + return flags; + } + } + + private static Map load() { + try (InputStream in = CountryFlags.class.getResourceAsStream(RESOURCE)) { + if (in != null) return read(in); + } catch (IOException ignored) { + // try an install's + } + for (File root : InstallDirs.searchRoots("gfx", null, null)) { + File zip = new File(root, FILE); + if (!zip.isFile()) continue; + try (InputStream in = new FileInputStream(zip)) { + return read(in); + } catch (IOException ignored) { + // try the next + } + } + return Map.of(); + } + + private static Map read(InputStream in) throws IOException { + Map out = new HashMap<>(); + try (ZipInputStream zip = new ZipInputStream(in)) { + for (ZipEntry e; (e = zip.getNextEntry()) != null; ) { + String name = e.getName().toLowerCase(Locale.ROOT); + if (!e.isDirectory() && name.endsWith(".png")) { + out.put(name.substring(name.lastIndexOf('/') + 1, name.length() - 4), zip.readAllBytes()); + } + } + } + return out; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/gfx/IconKeys.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/gfx/IconKeys.java new file mode 100644 index 0000000..1297793 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/gfx/IconKeys.java @@ -0,0 +1,37 @@ +package eu.lixko.ts3j.client.gfx; + +import eu.lixko.ts3j.client.net.ClientStatus; + +/** + * The TeamSpeak icon keys the channel tree is drawn with, so every frontend asks + * the packs for the same icons. + */ +public final class IconKeys { + + private IconKeys() { + } + + /** + * @return the keys to try for a channel, most specific first — packs need not ship + * every variant (none of TeamSpeak's own has a subscribed password channel) + */ + public static String[] channel(boolean password, boolean full, boolean subscribed) { + String base = password ? "CHANNEL_PRIVATE" : full ? "CHANNEL_RED" : "CHANNEL_GREEN"; + return subscribed ? new String[]{base + "_SUBSCRIBED", base} : new String[]{base}; + } + + public static String client(ClientStatus status) { + return switch (status) { + case QUERY -> "SERVER_QUERY"; + case SPEAKERS_DISABLED -> "HARDWARE_OUTPUT_MUTED"; + case SPEAKERS_MUTED -> "OUTPUT_MUTED"; + case MIC_DISABLED -> "HARDWARE_INPUT_MUTED"; + case MIC_MUTED -> "INPUT_MUTED"; + case AWAY -> "AWAY"; + case COMMANDER_TALKING -> "PLAYER_COMMANDER_ON"; + case COMMANDER -> "PLAYER_COMMANDER_OFF"; + case TALKING -> "PLAYER_ON"; + case IDLE -> "PLAYER_OFF"; + }; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/gfx/IconPack.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/gfx/IconPack.java new file mode 100644 index 0000000..a5511fa --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/gfx/IconPack.java @@ -0,0 +1,388 @@ +package eu.lixko.ts3j.client.gfx; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import java.util.zip.ZipInputStream; + +/** + * A TeamSpeak icon pack: a zip (or unpacked directory) of images plus an optional + * {@code settings.ini} naming the file behind every icon of the user interface. + * The format is TeamSpeak's, so the packs shipped with the official client and the + * ones from its add-on site can be used as they are: + * + *

    + * [options]
    + * FALLBACK=true
    + *
    + * [gfxfiles]
    + * CHANNEL_GREEN = channel_green.svg
    + * CONNECT       = connect.svg
    + * 
    + * + *

    Packs without a {@code settings.ini} are the legacy ones (TeamSpeak's own + * {@code default.zip}), whose files are named after the icon key directly, each + * prefixed with the size it was drawn for: {@code 16x16_connect.png}. Those are + * resolved by convention, picking the size closest to the one that is asked for. + * + *

    Icon data is returned as bytes; rasterising it (the packs from 2014 on are + * vector art) is the frontend's job. Vector art may paint with {@code currentColor}, + * which the frontend sets to its text colour ({@link #withCurrentColor}). + */ +public final class IconPack { + + private static final String INI = "settings.ini"; + /** Legacy file names: {@code x_.}. */ + private static final Pattern SIZED = Pattern.compile("(\\d+)x(\\d+)_(.+)"); + + /** One image inside a pack, with the size it was authored at (0 when unknown). */ + private record Entry(String path, int size) { + } + + /** Where a pack's files are read from: a zip, a directory or the classpath. */ + private interface Storage { + /** @return the file's bytes, or {@code null} when there is no such file */ + byte[] read(String path) throws IOException; + } + + private final String id; + private final File source; + private final String name; + private final Storage storage; + private final boolean fallback; + /** Icon key to the images that can serve it, smallest first. */ + private final Map> entries; + + private IconPack(String id, File source, String name, Storage storage, boolean fallback, + Map> entries) { + this.id = id; + this.source = source; + this.name = name; + this.storage = storage; + this.fallback = fallback; + this.entries = entries; + } + + /** Stable identifier used in the settings: the file (or directory) name. */ + public String id() { + return id; + } + + public String name() { + return name; + } + + /** @return the pack's zip or directory, or {@code null} for one shipped with the client */ + public File source() { + return source; + } + + /** Whether missing icons should be looked up in the default pack, as the pack asks. */ + public boolean fallsBack() { + return fallback; + } + + /** All icon keys this pack can draw, sorted. */ + public List keys() { + return new ArrayList<>(new TreeSet<>(entries.keySet())); + } + + public boolean has(String key) { + return entries.containsKey(normalizeKey(key)); + } + + /** + * Reads the image for an icon. + * + * @param key a TeamSpeak icon key, e.g. {@code CHANNEL_GREEN} + * @param preferredSize the size it will be drawn at, so packs holding several + * resolutions can pick the closest one + * @return the image bytes (PNG or SVG), or {@code null} if the pack has no such icon + */ + public byte[] icon(String key, int preferredSize) { + Entry entry = select(entries.get(normalizeKey(key)), preferredSize); + if (entry == null) return null; + try { + return storage.read(entry.path()); + } catch (IOException e) { + return null; + } + } + + /** @return whether the icon's image is vector art the frontend has to rasterise */ + public boolean isVector(String key, int preferredSize) { + Entry entry = select(entries.get(normalizeKey(key)), preferredSize); + return entry != null && entry.path().toLowerCase(Locale.ROOT).endsWith(".svg"); + } + + @Override + public String toString() { + return name; + } + + /** The smallest image that still covers the wanted size, else the largest one. */ + private static Entry select(List candidates, int preferredSize) { + if (candidates == null || candidates.isEmpty()) return null; + for (Entry e : candidates) { + if (e.size() == 0 || e.size() >= preferredSize) return e; + } + return candidates.get(candidates.size() - 1); + } + + /** + * Sets the colour vector art paints with {@code currentColor}, as a stylesheet's + * {@code color} would. + * + * @param rgb the colour as {@code 0xRRGGBB} + */ + public static byte[] withCurrentColor(byte[] svg, int rgb) { + String text = new String(svg, StandardCharsets.UTF_8); + if (!text.contains("currentColor")) return svg; + return text.replace("currentColor", String.format("#%06X", rgb & 0xFFFFFF)).getBytes(StandardCharsets.UTF_8); + } + + private static String normalizeKey(String key) { + return key == null ? "" : key.trim().toUpperCase(Locale.ROOT); + } + + // ---- loading ---- + + /** + * Reads a pack from a {@code .zip} file or from a directory holding its contents. + * + * @return the pack, or {@code null} when it holds no icons + */ + public static IconPack load(File source) { + if (source == null) return null; + boolean zipped = source.isFile(); + if (!zipped && !source.isDirectory()) return null; + + Map files = zipped ? listZip(source) : listDirectory(source); + if (files == null || files.isEmpty()) return null; + Storage storage = zipped ? path -> readFromZip(source, path) : path -> readFromDirectory(source, path); + return create(source.getName(), source, files, storage); + } + + /** + * Reads a pack's {@code .zip} shipped on the classpath, held in memory as it cannot be + * opened as a file there. + * + * @param resource the zip, e.g. {@code /gfx/teamspeak/default.zip} + * @return the pack, or {@code null} when it is not there or holds no icons + */ + public static IconPack loadZipResource(String resource) { + Map contents = new LinkedHashMap<>(); + try (InputStream in = IconPack.class.getResourceAsStream(resource)) { + if (in == null) return null; + try (ZipInputStream zip = new ZipInputStream(in)) { + for (ZipEntry e; (e = zip.getNextEntry()) != null; ) { + if (!e.isDirectory()) contents.put(e.getName(), zip.readAllBytes()); + } + } + } catch (IOException e) { + return null; + } + Map files = new LinkedHashMap<>(); + contents.forEach((path, data) -> files.put(path, (long) data.length)); + return create(resource.substring(resource.lastIndexOf('/') + 1), null, files, contents::get); + } + + private static IconPack create(String id, File source, Map files, Storage storage) { + String iniPath = files.keySet().stream() + .filter(p -> p.equalsIgnoreCase(INI)) + .findFirst().orElse(null); + Map mapping = new LinkedHashMap<>(); + Map info = new LinkedHashMap<>(); + boolean fallback = true; + if (iniPath != null) { + byte[] ini = read(storage, iniPath); + if (ini != null) fallback = parseIni(ini, mapping, info); + } + + Map> entries = iniPath != null + ? fromMapping(mapping, files) + : byConvention(files); + if (entries.isEmpty()) return null; + + String name = info.getOrDefault("name", displayName(id)); + return new IconPack(id, source, name, storage, fallback, entries); + } + + /** + * Reads a pack shipped on the classpath. As a classpath folder cannot be listed, + * the pack needs a {@code settings.ini}, whose file names must match exactly. + * + * @param id the pack's identifier in the settings + * @param resource the folder holding it, e.g. {@code /gfx/material} + * @return the pack, or {@code null} when it is not there + */ + public static IconPack loadResource(String id, String resource) { + Storage storage = path -> { + try (InputStream in = IconPack.class.getResourceAsStream(resource + '/' + path)) { + return in == null ? null : in.readAllBytes(); + } + }; + byte[] ini = read(storage, INI); + if (ini == null) return null; + Map mapping = new LinkedHashMap<>(); + Map info = new LinkedHashMap<>(); + boolean fallback = parseIni(ini, mapping, info); + + Map> entries = new LinkedHashMap<>(); + for (Map.Entry e : mapping.entrySet()) { + entries.put(e.getKey(), List.of(new Entry(e.getValue(), 0))); + } + if (entries.isEmpty()) return null; + return new IconPack(id, null, info.getOrDefault("name", displayName(id)), storage, fallback, entries); + } + + /** Turns {@code default_colored_2014.zip} into {@code Default Colored 2014}. */ + private static String displayName(String fileName) { + String base = fileName.toLowerCase(Locale.ROOT).endsWith(".zip") + ? fileName.substring(0, fileName.length() - 4) : fileName; + StringBuilder out = new StringBuilder(); + for (String word : base.split("[_\\-\\s]+")) { + if (word.isEmpty()) continue; + if (out.length() > 0) out.append(' '); + out.append(Character.toUpperCase(word.charAt(0))).append(word.substring(1)); + } + return out.length() == 0 ? fileName : out.toString(); + } + + /** @return the pack's FALLBACK option */ + private static boolean parseIni(byte[] data, Map mapping, Map info) { + boolean fallback = true; + try (BufferedReader in = new BufferedReader( + new InputStreamReader(new java.io.ByteArrayInputStream(data), StandardCharsets.UTF_8))) { + String section = ""; + String line; + while ((line = in.readLine()) != null) { + String trimmed = line.trim(); + if (trimmed.isEmpty() || trimmed.startsWith("#") || trimmed.startsWith(";")) continue; + if (trimmed.startsWith("[") && trimmed.endsWith("]")) { + section = trimmed.substring(1, trimmed.length() - 1).trim().toLowerCase(Locale.ROOT); + continue; + } + int eq = trimmed.indexOf('='); + if (eq < 0) continue; + String key = trimmed.substring(0, eq).trim(); + String value = trimmed.substring(eq + 1).trim(); + switch (section) { + case "gfxfiles" -> { + if (!value.isEmpty()) mapping.put(normalizeKey(key), value); + } + case "info" -> info.put(key.toLowerCase(Locale.ROOT), value); + case "options" -> { + if (key.equalsIgnoreCase("FALLBACK")) fallback = !value.equalsIgnoreCase("false"); + } + default -> { + } + } + } + } catch (IOException ignored) { + } + return fallback; + } + + private static Map> fromMapping(Map mapping, Map files) { + Map> entries = new LinkedHashMap<>(); + for (Map.Entry e : mapping.entrySet()) { + String path = resolve(e.getValue(), files); + if (path != null) entries.put(e.getKey(), List.of(new Entry(path, 0))); + } + return entries; + } + + /** + * Legacy packs (and the extra files of newer ones) are keyed by their name: + * {@code 16x16_connect.png} serves {@code CONNECT}, as does {@code 32x32_connect.png} + * when no smaller one exists. + */ + private static Map> byConvention(Map files) { + Map> entries = new LinkedHashMap<>(); + for (String path : files.keySet()) { + int dot = path.lastIndexOf('.'); + if (dot < 0 || path.indexOf('/') >= 0) continue; + String ext = path.substring(dot + 1).toLowerCase(Locale.ROOT); + if (!ext.equals("png") && !ext.equals("svg")) continue; + + String base = path.substring(0, dot); + int size = 0; + Matcher m = SIZED.matcher(base); + if (m.matches()) { + size = Integer.parseInt(m.group(1)); + base = m.group(3); + } + entries.computeIfAbsent(normalizeKey(base), k -> new ArrayList<>()).add(new Entry(path, size)); + } + for (List candidates : entries.values()) { + candidates.sort((a, b) -> Integer.compare(a.size(), b.size())); + } + return entries; + } + + /** Pack authors write file names as they see them, so a mismatched case is retried. */ + private static String resolve(String fileName, Map files) { + if (files.containsKey(fileName)) return fileName; + for (String path : files.keySet()) { + if (path.equalsIgnoreCase(fileName)) return path; + } + return null; + } + + private static byte[] read(Storage storage, String path) { + try { + return storage.read(path); + } catch (IOException e) { + return null; + } + } + + private static byte[] readFromZip(File zipFile, String path) throws IOException { + try (ZipFile zip = new ZipFile(zipFile)) { + ZipEntry entry = zip.getEntry(path); + if (entry == null) return null; + try (InputStream in = zip.getInputStream(entry)) { + return in.readAllBytes(); + } + } + } + + private static byte[] readFromDirectory(File dir, String path) throws IOException { + File file = new File(dir, path); + return file.isFile() ? Files.readAllBytes(file.toPath()) : null; + } + + private static Map listZip(File file) { + if (!file.getName().toLowerCase(Locale.ROOT).endsWith(".zip")) return null; + Map files = new LinkedHashMap<>(); + try (ZipFile zip = new ZipFile(file)) { + zip.stream().filter(e -> !e.isDirectory()).forEach(e -> files.put(e.getName(), e.getSize())); + } catch (IOException e) { + return null; + } + return files; + } + + private static Map listDirectory(File dir) { + Map files = new LinkedHashMap<>(); + File[] children = dir.listFiles(File::isFile); + if (children == null) return files; + for (File f : children) files.put(f.getName(), f.length()); + return files; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/gfx/IconPacks.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/gfx/IconPacks.java new file mode 100644 index 0000000..4e1507d --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/gfx/IconPacks.java @@ -0,0 +1,108 @@ +package eu.lixko.ts3j.client.gfx; + +import eu.lixko.ts3j.client.config.InstallDirs; + +import java.io.File; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +/** + * Finds the icon packs installed on this machine: the client's own {@code gfx/} + * folder, an extra folder the user configured, and the {@code gfx/} folder of an + * installed TeamSpeak 3 client (whose packs are usable as they are, see + * {@link IconPack}) — plus the Material pack the client ships. + */ +public final class IconPacks { + + /** The pack every other one falls back to, as TeamSpeak does. */ + public static final String DEFAULT_ID = "default.zip"; + /** The pack shipped with the client, drawn from Google's Material icons. */ + public static final String MATERIAL_ID = "material"; + + /** TeamSpeak's own packs, which the build ships when it finds a TeamSpeak 3 client to take them from. */ + private static final List TEAMSPEAK_IDS = + List.of(DEFAULT_ID, "default_colored_2014.zip", "default_mono_2014.zip"); + private static final String TEAMSPEAK_RESOURCE = "/gfx/teamspeak/"; + + private static volatile IconPack material; + private static volatile List teamspeak; + + private IconPacks() { + } + + /** + * Loads every pack found under {@code extraDirectory} and the well-known + * locations, the first search root winning on a name clash, then the shipped + * ones the folders did not have. + * + * @param userDirectory the client's own pack folder (may not exist yet) + * @param extraDirectory an additional folder chosen by the user, or {@code null} + * @return the packs, ordered by display name + */ + public static List findAll(File userDirectory, String extraDirectory) { + Map byId = new LinkedHashMap<>(); + for (File root : InstallDirs.searchRoots("gfx", userDirectory, extraDirectory)) { + File[] children = root.listFiles(); + if (children == null) continue; + for (File child : children) { + if (child.isFile() && !child.getName().toLowerCase(Locale.ROOT).endsWith(".zip")) continue; + if (byId.containsKey(child.getName())) continue; + IconPack pack = IconPack.load(child); + if (pack != null) byId.put(pack.id(), pack); + } + } + for (IconPack shipped : teamspeak()) byId.putIfAbsent(shipped.id(), shipped); + IconPack shipped = material(); + if (shipped != null) byId.putIfAbsent(shipped.id(), shipped); + List packs = new ArrayList<>(byId.values()); + packs.sort(Comparator.comparing(p -> p.name().toLowerCase(Locale.ROOT))); + return packs; + } + + /** @return the Material pack, or {@code null} if the build left it out */ + public static IconPack material() { + if (material == null) material = IconPack.loadResource(MATERIAL_ID, "/gfx/material"); + return material; + } + + /** @return TeamSpeak's packs the build shipped, which a pack of the same name found on disk replaces */ + public static List teamspeak() { + if (teamspeak == null) { + List packs = new ArrayList<>(); + for (String id : TEAMSPEAK_IDS) { + IconPack pack = IconPack.loadZipResource(TEAMSPEAK_RESOURCE + id); + if (pack != null) packs.add(pack); + } + teamspeak = List.copyOf(packs); + } + return teamspeak; + } + + /** @return the pack with this id, or {@code null} when it is not installed */ + public static IconPack select(List packs, String id) { + for (IconPack p : packs) { + if (p.id().equals(id)) return p; + } + return null; + } + + /** + * The packs to look an icon up in, in turn: the active one, TeamSpeak's + * {@code default.zip} if the active pack asks for it, then {@code lastResort}. + * + * @param active the chosen pack, or {@code null} for none + * @param lastResort the pack for whatever is still missing, or {@code null} + */ + public static List lookupOrder(IconPack active, List packs, IconPack lastResort) { + List order = new ArrayList<>(3); + if (active != null) order.add(active); + IconPack fallback = select(packs, DEFAULT_ID); + if (active != null && active.fallsBack() && fallback != null && !order.contains(fallback)) order.add(fallback); + if (lastResort != null && !order.contains(lastResort)) order.add(lastResort); + return order; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/GlobalInputHook.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/GlobalInputHook.java new file mode 100644 index 0000000..05ffd2f --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/GlobalInputHook.java @@ -0,0 +1,38 @@ +package eu.lixko.ts3j.client.hotkey; + +/** + * A system-wide source of key and mouse-button events: it reports every press and + * release on the machine, whether or not the client has focus, and without swallowing + * the event on its way to the focused application. + * + *

    Implementations are platform code and live outside the core; the core only ever + * sees this interface. + */ +public interface GlobalInputHook extends AutoCloseable { + + interface Listener { + /** + * @param key the key or button + * @param pressed {@code true} for a press, {@code false} for a release + */ + void onInput(HotkeyKey key, boolean pressed); + } + + /** Starts delivering events on a background thread. */ + void start(Listener listener); + + /** Whether events are actually being delivered; false when the platform refused. */ + boolean isRunning(); + + /** Why the hook is not running, for the options dialog to show; empty when it is. */ + String unavailableReason(); + + /** + * The name this system's layout gives a key, or {@code null} to let the caller fall + * back to {@link HotkeyKey#fallbackName()}. + */ + String keyName(HotkeyKey key); + + @Override + void close(); +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/Hotkey.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/Hotkey.java new file mode 100644 index 0000000..82f3a18 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/Hotkey.java @@ -0,0 +1,74 @@ +package eu.lixko.ts3j.client.hotkey; + +/** + * A single binding: which combination triggers which action, on which edge of the + * keypress, and whether it reaches only the active server or every connected one. + */ +public final class Hotkey { + + /** Which edge of the key press runs the action, as TS3's hotkey mode combo box offers. */ + public enum Trigger { + /** Action triggers when the key is pressed down. */ + KEY_DOWN("On key down"), + /** Action triggers when the key is released. */ + KEY_UP("On key up"); + + private final String label; + + Trigger(String label) { + this.label = label; + } + + public String label() { + return label; + } + } + + public HotkeyAction action; + public HotkeyCombo combo; + public Trigger trigger = Trigger.KEY_DOWN; + /** Apply to the active server only; when false the action reaches every connection. */ + public boolean activeServerOnly = true; + /** Meaning depends on {@link HotkeyAction#argument()}; empty when the action takes none. */ + public String argument = ""; + public boolean enabled = true; + + public Hotkey() { + } + + public Hotkey(HotkeyAction action, HotkeyCombo combo) { + this.action = action; + this.combo = combo; + } + + /** + * The binding's place in the action tree, as TS3 spells it out: + * {@code Sounds / Activate Soundpack / Default Sound Pack (Male)}. + */ + public String path() { + if (action == null) return ""; + StringBuilder sb = new StringBuilder(); + if (!action.group().isEmpty()) sb.append(action.group()).append(" / "); + sb.append(action.label()); + if (argument != null && !argument.isBlank()) sb.append(" / ").append(argument.trim()); + return sb.toString(); + } + + public boolean isValid() { + return action != null && combo != null && !combo.isEmpty(); + } + + /** Whether the action is a per-server one, for which {@link #activeServerOnly} matters. */ + public boolean isServerScoped() { + return action != null && action.category() != HotkeyAction.Category.MISC; + } + + public Hotkey copy() { + Hotkey h = new Hotkey(action, combo); + h.trigger = trigger; + h.activeServerOnly = activeServerOnly; + h.argument = argument; + h.enabled = enabled; + return h; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/HotkeyAction.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/HotkeyAction.java new file mode 100644 index 0000000..23c3b03 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/HotkeyAction.java @@ -0,0 +1,366 @@ +package eu.lixko.ts3j.client.hotkey; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * The catalogue of hotkey actions, reverse-engineered from the official TeamSpeak 3 + * client (its hotkey dialog builds exactly this list, in this order). + * + *

    Every entry keeps the identifiers TS3 itself uses — a numeric action type and a + * parameter keyword — so bindings stay recognisable and could be imported from, or + * exported to, the original client. {@link #supported()} tells whether this client + * can actually carry the action out; the rest are listed but greyed out. + * + *

    {@link #advanced()} mirrors the dialog's "Show Advanced Actions" checkbox: TS3 + * hides all but a handful of everyday actions until it is ticked. + */ +public enum HotkeyAction { + + // ----- Server ----- + CONNECT_CURRENT_TAB(Category.SERVER, 0x0010, "Server (current tab)", + "Connect to Server on Current Tab", false, Argument.BOOKMARK, true), + CONNECT_NEW_TAB(Category.SERVER, 0x0010, "Server (new tab)", + "Connect to Server in a New Tab", false, Argument.BOOKMARK, true), + DISCONNECT_CURRENT(Category.SERVER, 0x0020, "Current Server", + "Disconnect from Current Server", false, Argument.NONE, true), + DISCONNECT_ALL(Category.SERVER, 0x0020, "All Servers", + "Disconnect from All Servers", false, Argument.NONE, true), + + MIC_ACTIVATE(Category.SERVER, 0x0030, "Activate", + "Activate Microphone (current tab)", true, Argument.NONE, true), + MIC_MUTE(Category.SERVER, 0x0030, "Mute", + "Mute Microphone", true, Argument.NONE, true), + MIC_UNMUTE(Category.SERVER, 0x0030, "Unmute", + "Unmute Microphone", true, Argument.NONE, true), + MIC_TOGGLE(Category.SERVER, 0x0030, "Toggle", + "Toggle Microphone Mute", false, Argument.NONE, true), + /** + * TS3's "local" mute silences capture without publishing a mute status, or playing + * a mute/unmute sound — unlike {@link #MIC_MUTE}. + */ + MIC_LOCAL_UNMUTE(Category.SERVER, 0x0030, "ActivateLocalMute", + "Disable Local Mic Mute", true, Argument.NONE, true), + MIC_LOCAL_MUTE(Category.SERVER, 0x0030, "DeactivateLocalMute", + "Enable Local Mic Mute", true, Argument.NONE, true), + MIC_LOCAL_TOGGLE(Category.SERVER, 0x0030, "ToggleLocalMute", + "Toggle Local Mic Mute", true, Argument.NONE, true), + + SPEAKER_MUTE(Category.SERVER, 0x0040, "Mute", + "Mute Speaker", true, Argument.NONE, true), + SPEAKER_UNMUTE(Category.SERVER, 0x0040, "Unmute", + "Unmute Speaker", true, Argument.NONE, true), + SPEAKER_TOGGLE(Category.SERVER, 0x0040, "Toggle", + "Toggle Speaker Mute", false, Argument.NONE, true), + + AWAY_SET(Category.SERVER, 0x0050, "SetAway", + "Set Away", true, Argument.NONE, true), + AWAY_ONLINE(Category.SERVER, 0x0050, "SetOnline", + "Set Online", true, Argument.NONE, true), + AWAY_TOGGLE(Category.SERVER, 0x0050, "Toggle", + "Toggle Away Status", false, Argument.NONE, true), + AWAY_TOGGLE_WITH_MESSAGE(Category.SERVER, 0x0050, "Toggle With Message", + "Toggle Away Status with Message", true, Argument.TEXT, true), + + COMMANDER_ACTIVATE(Category.SERVER, 0x0100, "Activate", + "Activate Channel Commander", true, Argument.NONE, true), + COMMANDER_DEACTIVATE(Category.SERVER, 0x0100, "Deactivate", + "Deactivate Channel Commander", true, Argument.NONE, true), + COMMANDER_TOGGLE(Category.SERVER, 0x0100, "Toggle", + "Toggle Channel Commander", true, Argument.NONE, true), + + // ----- Self ----- + CAPTURE_PROFILE_ACTIVATE(Category.SELF, 0x0110, "Activate", + "Activate Capture Profile", true, Argument.PROFILE, false), + CAPTURE_PROFILE_DEACTIVATE(Category.SELF, 0x0110, "Deactivate", + "Deactivate Capture Profile", true, Argument.PROFILE, false), + CAPTURE_PROFILE_TOGGLE(Category.SELF, 0x0110, "Toggle", + "Toggle Capture Profile", true, Argument.PROFILE, false), + PLAYBACK_PROFILE_ACTIVATE(Category.SELF, 0x0120, "Activate", + "Activate Playback Profile", true, Argument.PROFILE, false), + PLAYBACK_PROFILE_DEACTIVATE(Category.SELF, 0x0120, "Deactivate", + "Deactivate Playback Profile", true, Argument.PROFILE, false), + PLAYBACK_PROFILE_TOGGLE(Category.SELF, 0x0120, "Toggle", + "Toggle Playback Profile", true, Argument.PROFILE, false), + HOTKEY_PROFILE_ACTIVATE(Category.SELF, 0x0130, "Activate", + "Activate Hotkey Profile", true, Argument.PROFILE, false), + HOTKEY_PROFILE_DEACTIVATE(Category.SELF, 0x0130, "Deactivate", + "Deactivate Hotkey Profile", true, Argument.PROFILE, false), + + PTT_ACTIVATE(Category.SELF, 0x0140, "Activate", + "Activate Push-to-Talk", false, Argument.NONE, true, true), + PTT_DEACTIVATE(Category.SELF, 0x0140, "Deactivate", + "Deactivate Push-to-Talk", true, Argument.NONE, true), + PTT_TOGGLE(Category.SELF, 0x0140, "Toggle", + "Toggle Push-to-Talk", true, Argument.NONE, true), + + CHANNEL_SWITCH(Category.SELF, 0x0150, "Strict Channel", + "Switch to Channel", true, Argument.CHANNEL, true), + CHANNEL_NEXT(Category.SELF, 0x0150, "Next Channel", + "Switch to Next Channel (Global)", true, Argument.NONE, false), + CHANNEL_PREVIOUS(Category.SELF, 0x0150, "Previous Channel", + "Switch to Previous Channel (Global)", true, Argument.NONE, false), + CHANNEL_LAST_VISITED(Category.SELF, 0x0150, "Last Visited Channel", + "Switch to Last Visited Channel", true, Argument.NONE, false), + CHANNEL_NEXT_FAMILY(Category.SELF, 0x0150, "Next Channel Family", + "Switch to Next Channel (Channel Family)", true, Argument.NONE, false), + CHANNEL_PREVIOUS_FAMILY(Category.SELF, 0x0150, "Previous Channel Family", + "Switch to Previous Channel (Channel Family)", true, Argument.NONE, false), + CHANNEL_NEXT_LEVEL(Category.SELF, 0x0150, "Next Channel Level", + "Switch to Next Channel (Same Level)", true, Argument.NONE, false), + CHANNEL_PREVIOUS_LEVEL(Category.SELF, 0x0150, "Previous Channel Level", + "Switch to Previous Channel (Same Level)", true, Argument.NONE, false), + + SERVER_TAB_SELECT(Category.SELF, 0x0160, "Strict Server", + "Select Server Tab", true, Argument.TEXT, true), + SERVER_TAB_NEXT(Category.SELF, 0x0160, "Next Server", + "Select Next Server Tab", true, Argument.NONE, true), + SERVER_TAB_PREVIOUS(Category.SELF, 0x0160, "Previous Server", + "Select Previous Server Tab", true, Argument.NONE, true), + + SOUNDPACK_ACTIVATE(Category.SELF, 0x0170, "Activate", + "Activate Soundpack", true, Argument.PROFILE, false), + SOUND_MUTE(Category.SELF, 0x0170, "Mute", + "Mute Sounds", true, Argument.NONE, true), + SOUND_UNMUTE(Category.SELF, 0x0170, "Unmute", + "Unmute Sounds", true, Argument.NONE, true), + SOUND_TOGGLE(Category.SELF, 0x0170, "Toggle", + "Toggle Sound Mute", true, Argument.NONE, true), + + WHISPER_PUSH_ACTIVATE(Category.SELF, 0x0180, "ActivatePushToWhisper", + "Activate Push-To-Whisper", true, Argument.TEXT, false, true), + WHISPER_PUSH_DEACTIVATE(Category.SELF, 0x0180, "DeactivatePushToWhisper", + "Deactivate Push-To-Whisper", true, Argument.TEXT, false), + WHISPER_REPLY_PUSH_ACTIVATE(Category.SELF, 0x0180, "ActivateReplyPushToWhisper", + "Activate Push-To-Reply to a Whisper", true, Argument.NONE, false, true), + WHISPER_REPLY_PUSH_DEACTIVATE(Category.SELF, 0x0180, "DeactivateReplyPushToWhisper", + "Deactivate Push-To-Reply to a Whisper", true, Argument.NONE, false), + WHISPERLIST_ACTIVATE(Category.SELF, 0x0180, "Activate", + "Activate Whisperlist", true, Argument.TEXT, false), + WHISPERLIST_DEACTIVATE(Category.SELF, 0x0180, "Deactivate", + "Deactivate Whisperlist", true, Argument.TEXT, false), + WHISPER_REPLY_ACTIVATE(Category.SELF, 0x0180, "ActivateReply", + "Activate Reply to a Whisper", true, Argument.NONE, false), + WHISPER_REPLY_DEACTIVATE(Category.SELF, 0x0180, "DeactivateReply", + "Deactivate Reply to a Whisper", true, Argument.NONE, false), + WHISPER_BLOCK_ACTIVATE(Category.SELF, 0x0180, "ActivateBlock", + "Activate Block Incoming Whispers", true, Argument.NONE, false), + WHISPER_BLOCK_DEACTIVATE(Category.SELF, 0x0180, "DeactivateBlock", + "Deactivate Block Incoming Whispers", true, Argument.NONE, false), + WHISPER_BLOCK_TOGGLE(Category.SELF, 0x0180, "ToggleBlock", + "Toggle Block Incoming Whispers", true, Argument.NONE, false), + + RECORDING_START(Category.SELF, 0x01c0, "Activate", + "Start Recording", true, Argument.NONE, false), + RECORDING_START_MULTITRACK(Category.SELF, 0x01c0, "ActivateMT", + "Start Multitrack Recording", true, Argument.NONE, false), + RECORDING_STOP(Category.SELF, 0x01c0, "Deactivate", + "Stop Recording", true, Argument.NONE, false), + + VOLUME_INCREASE(Category.SELF, 0x01e0, "Increase", + "Increase Master Volume", true, Argument.NONE, true), + VOLUME_DECREASE(Category.SELF, 0x01e0, "Decrease", + "Decrease Master Volume", true, Argument.NONE, true), + + PLUGIN_ACTIVATE(Category.SELF, 0x01f0, "Activate", + "Activate Plugin", true, Argument.TEXT, false), + PLUGIN_DEACTIVATE(Category.SELF, 0x01f0, "Deactivate", + "Deactivate Plugin", true, Argument.TEXT, false), + PLUGIN_TOGGLE(Category.SELF, 0x01f0, "Toggle", + "Toggle Plugin", true, Argument.TEXT, false), + PLUGIN_COMMAND(Category.SELF, 0x01f0, "Run", + "Run Plugin Command", true, Argument.TEXT, false), + PLUGIN_HOTKEY(Category.SELF, 0x01f0, "Hotkey", + "Plugin Hotkey", true, Argument.TEXT, false), + + SERVER_GROUP_ASSIGN(Category.SELF, 0x0270, "AssignSG", + "Assign Server Group", true, Argument.TEXT, false), + SERVER_GROUP_REVOKE(Category.SELF, 0x0270, "RevokeSG", + "Revoke Server Group", true, Argument.TEXT, false), + SERVER_GROUP_TOGGLE(Category.SELF, 0x0270, "ToggleSG", + "Toggle Server Group", true, Argument.TEXT, false), + + STYLESHEET_HELPER_ON(Category.SELF, 0x0240, "Activate", + "Stylesheet Helper (on)", true, Argument.NONE, false), + STYLESHEET_HELPER_OFF(Category.SELF, 0x0240, "Deactivate", + "Stylesheet Helper (off)", true, Argument.NONE, false), + + SOUND_3D_ACTIVATE(Category.SELF, 0x0250, "Activate", + "Activate 3D Sound", true, Argument.NONE, false), + SOUND_3D_DEACTIVATE(Category.SELF, 0x0250, "Deactivate", + "Deactivate 3D Sound", true, Argument.NONE, false), + SOUND_3D_TOGGLE(Category.SELF, 0x0250, "Toggle", + "Toggle 3D Sound", true, Argument.NONE, false), + + NICKNAME_CHANGE(Category.SELF, 0x01a0, "Rename", + "Change Nickname", true, Argument.TEXT, true), + + // ----- Misc ----- + TALK_POWER_GRANT_NEXT(Category.MISC, 0x01b0, "GrantNextTalkPower", + "Grant Next User Talk Power", true, Argument.NONE, false), + TALK_POWER_REQUEST(Category.MISC, 0x01b0, "RequestTalkPower", + "Request Talk Power", true, Argument.NONE, false), + TALK_POWER_REVOKE_ALL_GRANT_NEXT(Category.MISC, 0x01b0, "RevokeAllAndGrantNext", + "Revoke All And Grant Next User Talk Power", true, Argument.NONE, false), + + FILEBROWSER(Category.MISC, 0x01d0, "Filebrowser", + "Open Filebrowser on Channel", true, Argument.NONE, true), + AUTOCONNECT_DISABLE(Category.MISC, 0x0200, "Autoconnect", + "Disable Autoconnect", true, Argument.NONE, false), + SKIN_RELOAD(Category.MISC, 0x0210, "SkinReload", + "Reload Skin", true, Argument.NONE, true), + BRING_TO_FRONT(Category.MISC, 0x0220, "Bring2Front", + "Bring Client to Front", true, Argument.NONE, true), + SEND_TO_BACK(Category.MISC, 0x0230, "Send2Back", + "Send Client to Background", true, Argument.NONE, true); + + /** The three groups the TS3 hotkey dialog separates its list into. */ + public enum Category { + SERVER("Server"), + SELF("Self"), + MISC("Misc"); + + private final String label; + + Category(String label) { + this.label = label; + } + + public String label() { + return label; + } + } + + /** + * The group an action's type belongs to in TeamSpeak's hotkey tree, taken from the + * table its dialog builds. Types absent here are ungrouped: TS3 shows them as a + * single item directly under their category. + */ + private static final Map GROUPS = Map.ofEntries( + Map.entry(0x0010, "Connect to Server"), + Map.entry(0x0020, "Disconnect from Server"), + Map.entry(0x0030, "Microphone"), + Map.entry(0x0040, "Speaker"), + Map.entry(0x0050, "Away Status"), + Map.entry(0x0100, "Channel Commander"), + Map.entry(0x0110, "Capture Profile"), + Map.entry(0x0120, "Playback Profile"), + Map.entry(0x0130, "Hotkey Profile"), + Map.entry(0x0140, "Push-to-Talk"), + Map.entry(0x0150, "Switch to Channel"), + Map.entry(0x0160, "Select Server Tab"), + Map.entry(0x0170, "Sounds"), + Map.entry(0x0180, "Whisper"), + Map.entry(0x01b0, "Talk Power"), + Map.entry(0x01c0, "Recording"), + Map.entry(0x01e0, "Master Volume"), + Map.entry(0x01f0, "Plugins"), + Map.entry(0x0250, "3D Sound"), + Map.entry(0x0270, "Permissions")); + + /** What the action's free-text parameter means, when it takes one. */ + public enum Argument { + NONE, + /** Label of a bookmark to connect to. */ + BOOKMARK, + /** Channel path, "/"-separated. */ + CHANNEL, + /** Name of a capture/playback/hotkey profile or sound pack. */ + PROFILE, + /** Anything else: nickname, away message, tab number, plugin command. */ + TEXT + } + + private final Category category; + private final int type; + private final String parameter; + private final String label; + private final boolean advanced; + private final Argument argument; + private final boolean supported; + private final boolean momentary; + + HotkeyAction(Category category, int type, String parameter, String label, + boolean advanced, Argument argument, boolean supported) { + this(category, type, parameter, label, advanced, argument, supported, false); + } + + HotkeyAction(Category category, int type, String parameter, String label, + boolean advanced, Argument argument, boolean supported, boolean momentary) { + this.category = category; + this.type = type; + this.parameter = parameter; + this.label = label; + this.advanced = advanced; + this.argument = argument; + this.supported = supported; + this.momentary = momentary; + } + + public Category category() { + return category; + } + + /** TS3's numeric action type; actions sharing one differ only by {@link #parameter()}. */ + public int type() { + return type; + } + + /** + * The node this action hangs under in the hotkey tree ("Sounds", "Microphone", …), + * or an empty string for the actions TS3 lists on their own. + */ + public String group() { + return GROUPS.getOrDefault(type, ""); + } + + /** TS3's parameter keyword, e.g. {@code Toggle} or {@code ActivateReply}. */ + public String parameter() { + return parameter; + } + + /** The name shown in the hotkey list. */ + public String label() { + return label; + } + + /** Hidden until "Show advanced actions" is ticked, as in TS3. */ + public boolean advanced() { + return advanced; + } + + public Argument argument() { + return argument; + } + + /** Whether this client implements the action; unsupported ones cannot be bound. */ + public boolean supported() { + return supported; + } + + /** + * Whether the action lasts only while the hotkey is held (push-to-talk and the + * push-to-whisper variants), in which case the trigger setting does not apply and + * the release is reported as well. + */ + public boolean momentary() { + return momentary; + } + + public static List of(Category category, boolean includeAdvanced) { + List out = new ArrayList<>(); + for (HotkeyAction a : values()) { + if (a.category == category && (includeAdvanced || !a.advanced)) out.add(a); + } + return out; + } + + /** Looks an action up by its enum name, falling back to {@code null}. */ + public static HotkeyAction byName(String name) { + for (HotkeyAction a : values()) { + if (a.name().equals(name)) return a; + } + return null; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/HotkeyCombo.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/HotkeyCombo.java new file mode 100644 index 0000000..82061a4 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/HotkeyCombo.java @@ -0,0 +1,94 @@ +package eu.lixko.ts3j.client.hotkey; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.function.Function; + +/** + * A key combination: one key or button, or several that have to be held together. + * There is no distinguished modifier — as in TS3, any key can take that role, and the + * combination fires once every one of its keys is down. + */ +public final class HotkeyCombo { + + /** Recording order, which is also the order the combination is displayed in. */ + private final List keys; + + public HotkeyCombo(Collection keys) { + List copy = new ArrayList<>(); + for (HotkeyKey k : keys) { + if (k != null && !copy.contains(k)) copy.add(k); + } + this.keys = Collections.unmodifiableList(copy); + } + + public List keys() { + return keys; + } + + public boolean isEmpty() { + return keys.isEmpty(); + } + + public boolean contains(HotkeyKey key) { + return keys.contains(key); + } + + /** Whether every key of the combination is currently held down. */ + public boolean isSatisfiedBy(Set pressed) { + return !keys.isEmpty() && pressed.containsAll(keys); + } + + /** Serialised form, e.g. {@code Keyboard:37+Keyboard:45}. */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + for (HotkeyKey k : keys) { + if (sb.length() > 0) sb.append('+'); + sb.append(k); + } + return sb.toString(); + } + + public static HotkeyCombo parse(String text) { + List keys = new ArrayList<>(); + if (text != null && !text.isBlank()) { + for (String part : text.split("\\+")) { + HotkeyKey k = HotkeyKey.parse(part); + if (k != null) keys.add(k); + } + } + return new HotkeyCombo(keys); + } + + /** + * Renders the combination for the user, e.g. {@code Ctrl+Mouse 4}. + * + * @param namer resolves a key to its name on this system, typically from the + * keyboard layout; may return {@code null} to fall back + */ + public String display(Function namer) { + if (keys.isEmpty()) return "No hotkey assigned"; + StringBuilder sb = new StringBuilder(); + for (HotkeyKey k : keys) { + String name = namer == null ? null : namer.apply(k); + if (name == null || name.isBlank()) name = k.fallbackName(); + if (sb.length() > 0) sb.append(" + "); + sb.append(name); + } + return sb.toString(); + } + + @Override + public boolean equals(Object o) { + return o instanceof HotkeyCombo other && keys.equals(other.keys); + } + + @Override + public int hashCode() { + return keys.hashCode(); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/HotkeyEngine.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/HotkeyEngine.java new file mode 100644 index 0000000..b977349 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/HotkeyEngine.java @@ -0,0 +1,152 @@ +package eu.lixko.ts3j.client.hotkey; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +/** + * Turns the raw stream of global key events into hotkey activations: it tracks which + * keys are down, decides when a binding's combination becomes (or stops being) + * satisfied, and reports that on the configured edge. + * + *

    While a {@link Recorder} is installed the engine records combinations instead of + * firing them, which is how the hotkey dialog captures a new binding without the old + * ones going off. + */ +public final class HotkeyEngine implements GlobalInputHook.Listener { + + /** Receives activations; called on the input hook's thread. */ + public interface Handler { + /** + * @param hotkey the binding that fired + * @param active {@code true} on activation; a {@code false} call follows on release + * for {@link HotkeyAction#momentary()} actions only + */ + void onHotkey(Hotkey hotkey, boolean active); + } + + /** Collects a combination as the user presses it, for the "set hotkey" button. */ + public interface Recorder { + /** The keys held so far, in press order; called on every change. */ + void onRecording(HotkeyCombo combo); + + /** The user let go of everything: this is the final combination. */ + void onRecorded(HotkeyCombo combo); + } + + private final Hotkeys hotkeys; + private final Handler handler; + + private final Set pressed = new LinkedHashSet<>(); + /** Bindings whose combination is currently held, so a release can end them. */ + private final Set active = new HashSet<>(); + + private volatile Recorder recorder; + private final Set recording = new LinkedHashSet<>(); + + public HotkeyEngine(Hotkeys hotkeys, Handler handler) { + this.hotkeys = hotkeys; + this.handler = handler; + } + + /** + * Diverts every event into {@code recorder} until {@link #stopRecording()}; the + * bindings themselves stay silent meanwhile. + */ + public void record(Recorder recorder) { + synchronized (this) { + recording.clear(); + releaseActive(); + pressed.clear(); + } + this.recorder = recorder; + } + + public void stopRecording() { + recorder = null; + synchronized (this) { + recording.clear(); + pressed.clear(); + } + } + + @Override + public void onInput(HotkeyKey key, boolean down) { + Recorder rec = recorder; + if (rec != null) { + recordKey(rec, key, down); + return; + } + + List fired = new ArrayList<>(); + synchronized (this) { + if (down) { + if (!pressed.add(key)) return; + } else if (!pressed.remove(key)) { + return; + } + + for (Hotkey h : hotkeys.all()) { + if (!h.enabled || !h.isValid() || !h.action.supported()) continue; + if (!h.combo.contains(key)) continue; + + boolean satisfied = h.combo.isSatisfiedBy(pressed); + if (satisfied && active.add(h)) { + if (h.action.momentary() || h.trigger == Hotkey.Trigger.KEY_DOWN) { + fired.add(() -> handler.onHotkey(h, true)); + } + } else if (!satisfied && active.remove(h)) { + if (h.action.momentary()) { + fired.add(() -> handler.onHotkey(h, false)); + } else if (h.trigger == Hotkey.Trigger.KEY_UP) { + fired.add(() -> handler.onHotkey(h, true)); + } + } + } + } + for (Runnable r : fired) r.run(); + } + + private void recordKey(Recorder rec, HotkeyKey key, boolean down) { + HotkeyCombo combo; + boolean finished; + synchronized (this) { + if (down) { + recording.add(key); + pressed.add(key); + } else { + pressed.remove(key); + } + combo = new HotkeyCombo(recording); + finished = !down && pressed.isEmpty() && !recording.isEmpty(); + if (finished) recording.clear(); + } + if (finished) { + rec.onRecorded(combo); + } else { + rec.onRecording(combo); + } + } + + /** Ends every held binding, so nothing stays stuck when the hook stops. */ + public void releaseAll() { + List fired = new ArrayList<>(); + synchronized (this) { + for (Hotkey h : active) { + if (h.action.momentary()) fired.add(() -> handler.onHotkey(h, false)); + } + active.clear(); + pressed.clear(); + } + for (Runnable r : fired) r.run(); + } + + private void releaseActive() { + for (Hotkey h : new ArrayList<>(active)) { + if (h.action.momentary()) handler.onHotkey(h, false); + } + active.clear(); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/HotkeyKey.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/HotkeyKey.java new file mode 100644 index 0000000..8558982 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/HotkeyKey.java @@ -0,0 +1,88 @@ +package eu.lixko.ts3j.client.hotkey; + +/** + * One physical key or mouse button. Keys are identified by their position rather than by + * the character they produce, so a binding is independent of the keyboard layout in force + * when it was recorded. + * + *

    The keyboard numbering is whatever the platform's own is — X keycodes (Linux evdev + * code + 8) on X11, set-1 scan codes with the {@code E0}/{@code E1} escape in the high + * byte on Windows — because that is what its input API reports and its key-naming call + * expects. Bindings are therefore per-machine, which is also how TeamSpeak stores them. + * Mouse buttons are unified on the X numbering everywhere, side buttons included. + * + * @param device which input device the code belongs to + * @param code the platform's key code for {@link Device#KEYBOARD}, an X-style button + * number for {@link Device#MOUSE} + */ +public record HotkeyKey(HotkeyKey.Device device, int code) { + + public enum Device { + KEYBOARD("Keyboard"), + MOUSE("Mouse"); + + private final String prefix; + + Device(String prefix) { + this.prefix = prefix; + } + + String prefix() { + return prefix; + } + } + + public static HotkeyKey keyboard(int keycode) { + return new HotkeyKey(Device.KEYBOARD, keycode); + } + + public static HotkeyKey mouse(int button) { + return new HotkeyKey(Device.MOUSE, button); + } + + /** Serialised form, matching TS3's {@code Keyboard:9} / {@code Mouse:9} notation. */ + @Override + public String toString() { + return device.prefix() + ":" + code; + } + + public static HotkeyKey parse(String text) { + if (text == null) return null; + int colon = text.indexOf(':'); + if (colon <= 0) return null; + String prefix = text.substring(0, colon).trim(); + int code; + try { + code = Integer.parseInt(text.substring(colon + 1).trim()); + } catch (NumberFormatException e) { + return null; + } + for (Device d : Device.values()) { + if (d.prefix().equalsIgnoreCase(prefix)) return new HotkeyKey(d, code); + } + return null; + } + + /** + * A readable name that needs no help from the platform: mouse buttons carry the + * numbering users know them by, keys fall back to their raw code. + */ + public String fallbackName() { + if (device == Device.MOUSE) { + return switch (code) { + case 1 -> "Mouse Left"; + case 2 -> "Mouse Middle"; + case 3 -> "Mouse Right"; + case 4 -> "Wheel Up"; + case 5 -> "Wheel Down"; + case 6 -> "Wheel Left"; + case 7 -> "Wheel Right"; + // X hands the side buttons out as 8 and 9; everyone else calls them 4 and 5. + case 8 -> "Mouse 4"; + case 9 -> "Mouse 5"; + default -> "Mouse " + code; + }; + } + return "Key " + code; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/Hotkeys.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/Hotkeys.java new file mode 100644 index 0000000..09c8bf1 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/hotkey/Hotkeys.java @@ -0,0 +1,109 @@ +package eu.lixko.ts3j.client.hotkey; + +import eu.lixko.ts3j.client.config.AppDirs; +import eu.lixko.ts3j.client.config.ProfileFiles; + +import java.io.File; +import java.io.FileInputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Properties; + +/** + * The user's hotkey bindings, stored alongside the settings file. + * Frontend-agnostic: no UI dependencies. + */ +public final class Hotkeys { + + private static File file() { + return AppDirs.file("hotkeys.properties"); + } + + private final List entries = Collections.synchronizedList(new ArrayList<>()); + + /** The bindings as they are now; later changes do not show up in the returned list. */ + public List all() { + synchronized (entries) { + return List.copyOf(entries); + } + } + + public void add(Hotkey hotkey) { + entries.add(hotkey); + } + + public void set(int index, Hotkey hotkey) { + if (index >= 0 && index < entries.size()) entries.set(index, hotkey); + } + + public void remove(int index) { + if (index >= 0 && index < entries.size()) entries.remove(index); + } + + /** Replaces every binding at once, e.g. when the options dialog is applied. */ + public void replaceAll(List hotkeys) { + synchronized (entries) { + entries.clear(); + for (Hotkey h : hotkeys) { + if (h != null && h.isValid()) entries.add(h); + } + } + } + + public static Hotkeys load() { + Hotkeys h = new Hotkeys(); + if (!file().isFile()) return h; + Properties p = new Properties(); + try (FileInputStream in = new FileInputStream(file())) { + p.load(in); + } catch (Exception e) { + return h; + } + int count = parseInt(p.getProperty("count"), 0); + for (int i = 0; i < count; i++) { + String prefix = "hotkey." + i + "."; + HotkeyAction action = HotkeyAction.byName(p.getProperty(prefix + "action", "")); + if (action == null) continue; + Hotkey entry = new Hotkey(action, HotkeyCombo.parse(p.getProperty(prefix + "keys", ""))); + entry.trigger = "KEY_UP".equals(p.getProperty(prefix + "trigger")) + ? Hotkey.Trigger.KEY_UP : Hotkey.Trigger.KEY_DOWN; + entry.activeServerOnly = !"false".equals(p.getProperty(prefix + "activeServerOnly")); + entry.argument = p.getProperty(prefix + "argument", ""); + entry.enabled = !"false".equals(p.getProperty(prefix + "enabled")); + if (entry.isValid()) h.entries.add(entry); + } + return h; + } + + public void save() { + Properties p = new Properties(); + synchronized (entries) { + p.setProperty("count", Integer.toString(entries.size())); + for (int i = 0; i < entries.size(); i++) { + Hotkey e = entries.get(i); + String prefix = "hotkey." + i + "."; + p.setProperty(prefix + "action", e.action.name()); + p.setProperty(prefix + "keys", e.combo.toString()); + p.setProperty(prefix + "trigger", e.trigger.name()); + p.setProperty(prefix + "activeServerOnly", Boolean.toString(e.activeServerOnly)); + p.setProperty(prefix + "argument", e.argument == null ? "" : e.argument); + p.setProperty(prefix + "enabled", Boolean.toString(e.enabled)); + } + } + try { + AppDirs.createProfile(); + ProfileFiles.write(file(), out -> p.store(out, "TeamSpook TS3j hotkeys")); + } catch (Exception ignored) { + } + } + + private static int parseInt(String v, int def) { + if (v == null) return def; + try { + return Integer.parseInt(v.trim()); + } catch (NumberFormatException e) { + return def; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/AccountInfo.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/AccountInfo.java new file mode 100644 index 0000000..a8df446 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/AccountInfo.java @@ -0,0 +1,38 @@ +package eu.lixko.ts3j.client.myts; + +import java.time.Instant; + +/** + * Who a myTeamSpeak account is, as its sign-in reply says. The {@code userId} is the + * account's myTeamSpeak ID: also the localpart of its TeamSpeak chat ID and the user the + * file API addresses. + * + * @param userId empty when the reply carried none + * @param created null when the reply carried none + */ +public record AccountInfo(String username, String userId, String uuid, Instant created) { + + private static final String BASE32 = "abcdefghijklmnopqrstuvwxyz234567"; + + static AccountInfo of(String username, String uuid, byte[] userId, long createdSeconds) { + return new AccountInfo(username, userId == null ? "" : base32(userId), uuid, + createdSeconds > 0 ? Instant.ofEpochSecond(createdSeconds) : null); + } + + /** RFC 4648 base32, lowercase and unpadded. */ + static String base32(byte[] data) { + StringBuilder out = new StringBuilder((data.length * 8 + 4) / 5); + int buffer = 0, bits = 0; + for (byte b : data) { + buffer = (buffer << 8) | (b & 0xff); + bits += 8; + while (bits >= 5) { + out.append(BASE32.charAt((buffer >> (bits - 5)) & 31)); + bits -= 5; + } + buffer &= (1 << bits) - 1; + } + if (bits > 0) out.append(BASE32.charAt((buffer << (5 - bits)) & 31)); + return out.toString(); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/ChatAttachment.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/ChatAttachment.java new file mode 100644 index 0000000..b93758a --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/ChatAttachment.java @@ -0,0 +1,137 @@ +package eu.lixko.ts3j.client.myts; + +import eu.lixko.ts3j.client.text.Json; + +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Locale; +import java.util.Map; + +/** + * A file shared in chat the way TeamSpeak 6 shares one with a server that has no chat of + * its own: the file sits in the sender's myTeamSpeak cloud storage, and an ordinary text + * message carries this JSON pointer to it. TeamSpeak 6 shows such a message as the file and + * hides the text; other clients show the text. + * + *

    The file lies under the sender's myTeamSpeak ID and the room it was shared in, the + * server's unique identifier, which the message does not carry: the reader supplies it. + * + * @param senderChatId the sender's TeamSpeak chat ID, {@code @:} + * @param description the text TeamSpeak 6 shows with the file; its name unless the sender wrote one + */ +public record ChatAttachment(String fileId, String senderChatId, String fileName, long fileSize, + String description) { + + private static final String TYPE = "ts.file.myts"; + /** The home server TeamSpeak 6 accounts are on; readers use only the ID before it. */ + private static final String CHAT_HOST = "chat-1.tmspk.net"; + /** What {@link #href} addresses start with. */ + public static final String SCHEME = "tsattach:"; + /** What TeamSpeak 6 shows as a picture, by the file name. */ + private static final String[] IMAGE_SUFFIXES = {".png", ".jpeg", ".jpg", ".jpe", ".svg", ".svgz", ".webp", + ".tif", ".tiff", ".gif", ".ico", ".bmp"}; + + /** A file this account shares, under the name it is shown with. */ + public static ChatAttachment of(String fileId, String senderUserId, String fileName, long fileSize) { + return new ChatAttachment(fileId, chatId(senderUserId), fileName, fileSize, fileName); + } + + /** @return the attachment {@code message} points to, or {@code null} for any other message */ + public static ChatAttachment parse(String message) { + if (message == null || !message.startsWith("{") || !message.contains(TYPE)) return null; + Map json = Json.parseObject(message); + if (json == null || !TYPE.equals(json.get("msg_type")) + || !(json.get("file_id") instanceof String fileId) || fileId.isEmpty() + || !(json.get("chat_user_id") instanceof String sender) || sender.isEmpty()) { + return null; + } + String name = json.get("file_name") instanceof String s ? s : ""; + long size = json.get("file_size") instanceof Double d ? d.longValue() : -1; + String body = json.get("body") instanceof String s ? s : ""; + return new ChatAttachment(fileId, sender, name, size, body); + } + + /** The text message to send, written as TeamSpeak 6 writes it. */ + public String toMessage() { + return "{\"msg_type\":" + Json.quote(TYPE) + + ",\"file_id\":" + Json.quote(fileId) + + ",\"chat_user_id\":" + Json.quote(senderChatId) + + ",\"file_name\":" + Json.quote(fileName) + + ",\"file_size\":" + fileSize + + ",\"body\":" + Json.quote(description) + + ",\"v2\":true}"; + } + + /** The myTeamSpeak ID the file lies under: the chat ID's local part. */ + public String senderUserId() { + int colon = senderChatId.indexOf(':'); + int from = senderChatId.startsWith("@") ? 1 : 0; + return senderChatId.substring(from, colon > from ? colon : senderChatId.length()); + } + + public boolean isImage() { + return isImageName(fileName); + } + + /** The description, when the sender wrote one rather than leaving the file name. */ + public String caption() { + return description.isBlank() || description.equals(fileName) ? "" : description; + } + + /** The address chat views link the file with, naming everything needed to fetch it. */ + public String href(String room) { + return SCHEME + encode(room) + "/" + encode(senderUserId()) + "/" + encode(fileId) + "/" + encode(fileName); + } + + /** A file as named by {@link #href}. */ + public record Ref(String room, String owner, String fileId, String fileName) { + + /** @return the file {@code href} names, or {@code null} for any other address */ + public static Ref parse(String href) { + if (href == null || !href.startsWith(SCHEME)) return null; + String[] parts = href.substring(SCHEME.length()).split("/", -1); + if (parts.length != 4) return null; + return new Ref(decode(parts[0]), decode(parts[1]), decode(parts[2]), decode(parts[3])); + } + + public boolean isImage() { + return isImageName(fileName); + } + } + + public static boolean isHref(String href) { + return href != null && href.startsWith(SCHEME); + } + + private static boolean isImageName(String fileName) { + String name = fileName.toLowerCase(Locale.ROOT); + for (String suffix : IMAGE_SUFFIXES) { + if (name.endsWith(suffix)) return true; + } + return false; + } + + /** The chat ID TeamSpeak 6 writes for a myTeamSpeak ID. */ + static String chatId(String userId) { + return "@" + padded(userId) + ":" + CHAT_HOST; + } + + /** + * A myTeamSpeak ID padded as in TeamSpeak 6's chat IDs. Files lie under the ID exactly as + * it was given when they were stored, and TeamSpeak 6 gives it padded. + */ + static String padded(String userId) { + StringBuilder id = new StringBuilder(userId); + while (id.length() % 8 != 0) id.append('='); + return id.toString(); + } + + private static String encode(String s) { + return URLEncoder.encode(s, StandardCharsets.UTF_8).replace("+", "%20"); + } + + private static String decode(String s) { + return URLDecoder.decode(s, StandardCharsets.UTF_8); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/ChatAttachments.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/ChatAttachments.java new file mode 100644 index 0000000..2cc229d --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/ChatAttachments.java @@ -0,0 +1,67 @@ +package eu.lixko.ts3j.client.myts; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Shares files in chat as TeamSpeak 6 does with servers that have no chat of their own: + * into the sender's myTeamSpeak cloud storage, pointed to by a {@link ChatAttachment} + * message. Everything here blocks on the network; call it off the UI thread. + */ +public final class ChatAttachments { + + /** Larger files are not shared: they are sent from memory-starved phones too. */ + public static final long MAX_UPLOAD_BYTES = 100L << 20; + /** Pictures larger than this are offered as files rather than shown, as TeamSpeak 6 does. */ + public static final long MAX_PREVIEW_BYTES = 5L << 20; + + private final MyTsFiles files; + + public ChatAttachments(MyTeamSpeakLogin login) { + this(new MyTsFiles(login)); + } + + ChatAttachments(MyTsFiles files) { + this.files = files; + } + + /** + * Stores a file for sharing in {@code room}, the server's unique identifier. + * + * @return the message to send in its place + */ + public ChatAttachment upload(InputStream data, long size, String fileName, String room) + throws IOException, MyTsException { + if (size > MAX_UPLOAD_BYTES) { + throw new MyTsException("Files over " + (MAX_UPLOAD_BYTES >> 20) + " MB cannot be shared", 0); + } + MyTsFiles.Upload upload = files.requestUpload(room); + MyTsFiles.put(upload.url(), data, size); + return ChatAttachment.of(upload.fileId(), upload.senderUserId(), fileName, size); + } + + /** Fetches a shared file whole. */ + public byte[] download(ChatAttachment.Ref ref, long maxBytes) throws IOException, MyTsException { + return MyTsFiles.get(files.requestDownload(ref.owner(), ref.room(), ref.fileId()), maxBytes); + } + + /** + * Fetches the file an {@link ChatAttachment#href} names, for picture caches. + * + * @return {@code null} when it cannot be had, e.g. while signed out + */ + public byte[] fetchPicture(String href, long maxBytes) throws IOException { + ChatAttachment.Ref ref = ChatAttachment.Ref.parse(href); + if (ref == null) return null; + try { + return download(ref, maxBytes); + } catch (MyTsException e) { + return null; + } + } + + /** Ends the myTeamSpeak session kept for sharing, e.g. on exit or sign-out. */ + public void close() { + files.close(); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTeamSpeak.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTeamSpeak.java new file mode 100644 index 0000000..1cc7265 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTeamSpeak.java @@ -0,0 +1,244 @@ +package eu.lixko.ts3j.client.myts; + +import eu.lixko.ts3j.client.proto.ProtobufReader; +import eu.lixko.ts3j.client.proto.ProtobufWriter; +import eu.lixko.ts3j.client.teamspeak.SyncItem; +import eu.lixko.ts3j.client.teamspeak.SyncItemDecoder; +import eu.lixko.ts3j.client.teamspeak.SyncOrder; + +import java.io.IOException; +import java.net.URI; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.List; + +/** + * Reads the bookmarks and identities a myTeamSpeak account synchronises, the way + * the official client pulls them on a fresh install: sign in, ask for every item + * of the wanted classes against an empty local state, decrypt them, and sign out. + * Nothing is ever written to the account. Staying signed in is {@link MyTeamSpeakLogin}'s. + * + *

    The protocol is described in {@code docs/myteamspeak/PROTOCOL.md}. + */ +public final class MyTeamSpeak { + + public static final URI API = URI.create("https://clientapi.myteamspeak.com/"); + + /** What the account holds, in the same form as a local TeamSpeak 3 client's store. */ + public record Account(AccountInfo info, List items) { + public Account { + items = List.copyOf(items); + } + + public String username() { + return info.username(); + } + + public long identities() { + return items.stream().filter(SyncItem.Identity.class::isInstance).count(); + } + + public long bookmarks() { + return items.stream().filter(SyncItem.Bookmark.class::isInstance).count(); + } + } + + private static final String NO_VERSION = "00000000-0000-0000-0000-000000000000"; + private static final int SYNC_VERSION_1_1 = 1; + private static final int[] ITEM_CLASSES = {0 /* BOOKMARK */, 1 /* IDENTITY */, 6 /* ITEM_FOLDER */}; + + private static final int LOGIN_OK = 200; + private static final int LOGIN_OFFLINE = 201; + private static final int LOGIN_EMAIL_PENDING = 203; + private static final int IN_SYNC = 300; + private static final int NOT_IN_DB = 302; + + private final MyTsTransport transport; + + public MyTeamSpeak() { + this(MyTsTransport.https(API)); + } + + /** For the other services, which share the sign-in. */ + MyTsTransport transport() { + return transport; + } + + MyTeamSpeak(MyTsTransport transport) { + this.transport = transport; + } + + /** + * What it takes to sign in again, and all the client keeps of a sign-in — the same as + * the official client's {@code Account_Data}: the login token stands in for the + * password with the server, and the account key opens the item key it returns. The + * password itself is not needed again. + */ + public record Credentials(String email, String loginToken, byte[] accountKey) { + public Credentials { + accountKey = accountKey.clone(); + } + + @Override + public byte[] accountKey() { + return accountKey.clone(); + } + + /** Runs the key derivation, deliberately slow; call it off the UI thread. */ + public static Credentials derive(String email, String password) throws MyTsException { + try { + return new Credentials(email, MyTsCrypto.loginToken(email, password), + MyTsCrypto.accountKey(email, password)); + } catch (GeneralSecurityException e) { + throw new MyTsException("This platform lacks the ciphers myTeamSpeak needs", e); + } + } + } + + /** Signs in, reads the account and signs out again: a few requests, so call it off the UI thread. */ + public Account download(Credentials credentials) throws IOException, MyTsException { + Session session = signIn(credentials); + try { + if (session.keyPackage == null) throw new MyTsException("The account has no synchronisation key", 0); + byte[] itemKey; + try { + itemKey = MyTsCrypto.unwrapItemKey(credentials.accountKey(), session.keyPackage); + } catch (GeneralSecurityException e) { + throw new MyTsException("Could not unlock the account's encrypted data", e); + } + return new Account(session.info, pull(session.id, itemKey)); + } finally { + signOut(session.id); + } + } + + /** A signed-in session: the bearer token later requests carry, and who it belongs to. */ + record Session(String id, AccountInfo info, byte[] keyPackage) { + } + + /** Signs in; the caller ends the session with {@link #signOut}. */ + Session signIn(Credentials credentials) throws IOException, MyTsException { + ProtobufReader reply = new ProtobufReader(transport.call("authentication", "login", + new ProtobufWriter().string(1, credentials.email()).string(2, credentials.loginToken()).toByteArray())); + + byte[] keyPackage = null; + String session = "", username = "", uuid = ""; + byte[] userId = null; + long createdAt = 0; + int error = 0; + while (reply.next()) { + switch (reply.fieldNumber()) { + case 1 -> keyPackage = reply.readBytes(); + case 2 -> session = reply.readString(); + case 5 -> error = (int) reply.readVarint(); + case 4 -> uuid = reply.readString(); + case 8 -> username = reply.readString(); + case 9 -> { + ProtobufReader identity = reply.readMessage(); + while (identity.next()) { + switch (identity.fieldNumber()) { + case 3 -> createdAt = identity.readVarint(); + case 4 -> userId = identity.readBytes(); + default -> identity.skip(); + } + } + } + default -> reply.skip(); + } + } + if (error != LOGIN_OK) throw loginError(error); + return new Session(session, AccountInfo.of(username, uuid, userId, createdAt), keyPackage); + } + + private List pull(String session, byte[] itemKey) throws IOException, MyTsException { + ProtobufWriter request = new ProtobufWriter().string(1, session); + for (int itemClass : ITEM_CLASSES) { + request.message(2, new ProtobufWriter().varint(1, itemClass).string(2, NO_VERSION)); + } + request.string(3, NO_VERSION).varint(4, SYNC_VERSION_1_1); + ProtobufReader reply = new ProtobufReader( + transport.call("synchronization", "requestServerItems", request.toByteArray())); + + List frames = new ArrayList<>(); + int status = 0; + while (reply.next()) { + switch (reply.fieldNumber()) { + case 1 -> status = (int) reply.readVarint(); + case 2 -> collectFrames(reply.readMessage(), frames); + default -> reply.skip(); + } + } + if (status < IN_SYNC || status > NOT_IN_DB) { + throw new MyTsException("myTeamSpeak refused to synchronise (status " + status + ")", status); + } + + List items = new ArrayList<>(); + for (byte[] frame : frames) { + SyncItem item; + try { + item = SyncItemDecoder.decode(MyTsCrypto.decryptItem(frame, itemKey)); + } catch (GeneralSecurityException e) { + throw new MyTsException("Could not decrypt the account's items", e); + } + if (item != null) items.add(item); + } + return SyncOrder.sorted(items); + } + + /** + * The encrypted items of one {@code Sync_ItemClasses_Data}; tombstones carry none. + * The server answers with every class the account holds, whatever was asked for, + * and not all of them are encrypted (add-on flags come in the clear), so only the + * wanted classes are kept. + */ + private static void collectFrames(ProtobufReader itemClass, List frames) throws IOException { + int classId = 0; + List blobs = new ArrayList<>(); + while (itemClass.next()) { + switch (itemClass.fieldNumber()) { + case 1 -> classId = (int) itemClass.readVarint(); + case 3 -> { + byte[] blob = itemBlob(itemClass.readMessage()); + if (blob != null) blobs.add(blob); + } + default -> itemClass.skip(); + } + } + for (int wanted : ITEM_CLASSES) { + if (wanted == classId) frames.addAll(blobs); + } + } + + private static byte[] itemBlob(ProtobufReader detail) throws IOException { + byte[] blob = null; + boolean deleted = false; + while (detail.next()) { + switch (detail.fieldNumber()) { + case 3 -> blob = detail.readBytes(); + case 4 -> deleted = detail.readBool(); + default -> detail.skip(); + } + } + return !deleted && blob != null && blob.length > 0 ? blob : null; + } + + /** Ends the session rather than leave it for the server to expire; nothing to do if that fails. */ + void signOut(String session) { + if (session.isEmpty()) return; + try { + transport.call("authentication", "deleteSession", new ProtobufWriter().string(1, session).toByteArray()); + } catch (IOException | MyTsException ignored) { + // The session expires on its own. + } + } + + private static MyTsException loginError(int error) { + String message = switch (error) { + case MyTsException.LOGIN_FAILED -> "Wrong email address or password"; + case LOGIN_EMAIL_PENDING -> "Confirm your email address before signing in"; + case LOGIN_OFFLINE -> "myTeamSpeak is offline, try again later"; + default -> "myTeamSpeak refused the sign-in (error " + error + ")"; + }; + return new MyTsException(message, error); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTeamSpeakLogin.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTeamSpeakLogin.java new file mode 100644 index 0000000..e5a914e --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTeamSpeakLogin.java @@ -0,0 +1,143 @@ +package eu.lixko.ts3j.client.myts; + +import eu.lixko.ts3j.client.config.AppDirs; +import eu.lixko.ts3j.client.config.ProfileFiles; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Base64; +import java.util.Properties; + +/** + * The myTeamSpeak account this client stays signed in to. Signing in keeps the + * {@link MyTeamSpeak.Credentials} in the profile, private to the user, so the account + * can be read again later without asking for the password; signing out forgets them. + * Each read signs in afresh; only {@link MyTsFiles} keeps a session. + */ +public final class MyTeamSpeakLogin { + + private static final String FILE_NAME = "myteamspeak.properties"; + + private final File file; + private final MyTeamSpeak service; + private MyTeamSpeak.Credentials credentials; + private String username = ""; + + MyTeamSpeakLogin(File file, MyTeamSpeak service) { + this.file = file; + this.service = service; + read(); + } + + public static MyTeamSpeakLogin load() { + return new MyTeamSpeakLogin(AppDirs.file(FILE_NAME), new MyTeamSpeak()); + } + + public synchronized boolean isSignedIn() { + return credentials != null; + } + + /** Empty when signed out. */ + public synchronized String email() { + return credentials == null ? "" : credentials.email(); + } + + /** The account's display name; the email when the account has none. */ + public synchronized String username() { + return username.isBlank() ? email() : username; + } + + /** + * Signs in and stays signed in, returning what the account holds. Blocks for the key + * derivation and a few requests. Nothing is kept when it fails. + */ + public MyTeamSpeak.Account signIn(String email, String password) throws IOException, MyTsException { + MyTeamSpeak.Credentials fresh = MyTeamSpeak.Credentials.derive(email.trim(), password); + MyTeamSpeak.Account account = service.download(fresh); + synchronized (this) { + credentials = fresh; + username = account.username(); + write(); + } + return account; + } + + /** + * Reads the account again. When the server no longer takes the kept credentials — + * the password was changed elsewhere — this signs out before rethrowing. + * + * @throws IllegalStateException when signed out + */ + public MyTeamSpeak.Account fetch() throws IOException, MyTsException { + MyTeamSpeak.Credentials current; + synchronized (this) { + if (credentials == null) throw new IllegalStateException("Not signed in to myTeamSpeak"); + current = credentials; + } + try { + MyTeamSpeak.Account account = service.download(current); + synchronized (this) { + if (credentials == current && !account.username().equals(username)) { + username = account.username(); + write(); + } + } + return account; + } catch (MyTsException e) { + if (!e.credentialsRejected()) throw e; + synchronized (this) { + if (credentials == current) signOut(); + } + throw new MyTsException("myTeamSpeak no longer accepts the saved sign-in; the password may have " + + "changed. Sign in again.", e.code()); + } + } + + /** What signs in, or {@code null} when signed out. */ + synchronized MyTeamSpeak.Credentials credentials() { + return credentials; + } + + MyTeamSpeak service() { + return service; + } + + public synchronized void signOut() { + credentials = null; + username = ""; + //noinspection ResultOfMethodCallIgnored + file.delete(); + } + + private void read() { + if (!file.isFile()) return; + Properties p = new Properties(); + try (InputStream in = new FileInputStream(file)) { + p.load(in); + String email = p.getProperty("email", ""); + String token = p.getProperty("loginToken", ""); + byte[] key = Base64.getDecoder().decode(p.getProperty("accountKey", "")); + if (email.isEmpty() || token.isEmpty() || key.length == 0) return; + credentials = new MyTeamSpeak.Credentials(email, token, key); + username = p.getProperty("username", ""); + } catch (IOException | IllegalArgumentException unreadable) { + // Treated as signed out. + } + } + + private void write() { + Properties p = new Properties(); + p.setProperty("email", credentials.email()); + p.setProperty("username", username); + p.setProperty("loginToken", credentials.loginToken()); + p.setProperty("accountKey", Base64.getEncoder().encodeToString(credentials.accountKey())); + try { + AppDirs.createProfile(); + ProfileFiles.write(file, out -> p.store(out, "myTeamSpeak sign-in: a derived token and key, not the password")); + } catch (IOException e) { + // Signed in for this run only. + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTsCrypto.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTsCrypto.java new file mode 100644 index 0000000..d031ceb --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTsCrypto.java @@ -0,0 +1,136 @@ +package eu.lixko.ts3j.client.myts; + +import javax.crypto.AEADBadTagException; +import javax.crypto.Cipher; +import javax.crypto.Mac; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.Base64; + +/** + * The end-to-end encryption of myTeamSpeak synchronisation, as the official + * client's {@code teamcrypto} does it (see {@code docs/myteamspeak/CRYPTO_RE_SALT.md}). + * Both keys come from the password: the login token proves it to the server, and + * the account key unwraps the item key the server hands back, which the server + * itself never learns. + */ +final class MyTsCrypto { + + private static final int PBKDF2_ITERATIONS = 10_000; + private static final int LOGIN_TOKEN_BYTES = 48; + private static final int KEY_BYTES = 32; + private static final int GCM_TAG_BYTES = 16; + private static final int GCM_IV_BYTES = 12; + private static final int KEY_PACKAGE_VERSION = 2; + private static final int CTR_BLOCK_BYTES = 16; + private static final int ITEM_HASH_BYTES = 64; + + private MyTsCrypto() { + } + + /** What {@code LoginData.password} carries instead of the password. */ + static String loginToken(String email, String password) throws GeneralSecurityException { + return Base64.getEncoder().encodeToString(derive(email, password, "ts3Login", LOGIN_TOKEN_BYTES)); + } + + static byte[] accountKey(String email, String password) throws GeneralSecurityException { + return derive(email, password, "ts3Encryption", KEY_BYTES); + } + + /** + * Opens {@code LoginSession.key}: {@code 02 || tag[16] || iv[12] || ciphertext[32]}, + * AES-256-GCM under the account key, no AAD. + */ + static byte[] unwrapItemKey(byte[] accountKey, byte[] keyPackage) throws GeneralSecurityException { + if (keyPackage.length != 1 + GCM_TAG_BYTES + GCM_IV_BYTES + KEY_BYTES || keyPackage[0] != KEY_PACKAGE_VERSION) { + throw new GeneralSecurityException("Unsupported account key package"); + } + int ivAt = 1 + GCM_TAG_BYTES; + int dataAt = ivAt + GCM_IV_BYTES; + // JCA wants the tag after the ciphertext. + byte[] sealed = new byte[KEY_BYTES + GCM_TAG_BYTES]; + System.arraycopy(keyPackage, dataAt, sealed, 0, KEY_BYTES); + System.arraycopy(keyPackage, 1, sealed, KEY_BYTES, GCM_TAG_BYTES); + + Cipher gcm = Cipher.getInstance("AES/GCM/NoPadding"); + gcm.init(Cipher.DECRYPT_MODE, new SecretKeySpec(accountKey, "AES"), + new GCMParameterSpec(GCM_TAG_BYTES * 8, keyPackage, ivAt, GCM_IV_BYTES)); + try { + return gcm.doFinal(sealed); + } catch (AEADBadTagException e) { + throw new GeneralSecurityException("The account key does not match the password", e); + } + } + + /** + * Decrypts an item frame, {@code iv[16] || ciphertext || SHA-512(plaintext)}, into + * its {@code Item_Data} message. The cipher is AES-256-CTR, but with the counter + * incremented little-endian, so JCA's own CTR mode cannot be used. + */ + static byte[] decryptItem(byte[] frame, byte[] itemKey) throws GeneralSecurityException { + int textLength = frame.length - CTR_BLOCK_BYTES - ITEM_HASH_BYTES; + if (textLength <= 0) throw new GeneralSecurityException("Truncated item"); + + Cipher aes = Cipher.getInstance("AES/ECB/NoPadding"); + aes.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(itemKey, "AES")); + byte[] counter = Arrays.copyOf(frame, CTR_BLOCK_BYTES); + byte[] plain = new byte[textLength]; + for (int off = 0; off < textLength; off += CTR_BLOCK_BYTES) { + byte[] keyStream = aes.doFinal(counter); + int n = Math.min(CTR_BLOCK_BYTES, textLength - off); + for (int i = 0; i < n; i++) plain[off + i] = (byte) (frame[CTR_BLOCK_BYTES + off + i] ^ keyStream[i]); + incrementLittleEndian(counter); + } + + byte[] hash = MessageDigest.getInstance("SHA-512").digest(plain); + byte[] expected = Arrays.copyOfRange(frame, frame.length - ITEM_HASH_BYTES, frame.length); + if (!MessageDigest.isEqual(hash, expected)) throw new GeneralSecurityException("Item integrity check failed"); + return plain; + } + + /** PBKDF2-HMAC-SHA512 keyed by the password, salted with {@code lower(email) + purpose + password}. */ + private static byte[] derive(String email, String password, String purpose, int length) + throws GeneralSecurityException { + byte[] salt = (asciiLowerCase(email) + purpose + password).getBytes(StandardCharsets.UTF_8); + Mac hmac = Mac.getInstance("HmacSHA512"); + hmac.init(new SecretKeySpec(password.getBytes(StandardCharsets.UTF_8), "HmacSHA512")); + + byte[] out = new byte[length]; + byte[] blockSalt = Arrays.copyOf(salt, salt.length + 4); + for (int block = 1, off = 0; off < length; block++) { + blockSalt[salt.length] = (byte) (block >>> 24); + blockSalt[salt.length + 1] = (byte) (block >>> 16); + blockSalt[salt.length + 2] = (byte) (block >>> 8); + blockSalt[salt.length + 3] = (byte) block; + byte[] u = hmac.doFinal(blockSalt); + byte[] t = u.clone(); + for (int i = 1; i < PBKDF2_ITERATIONS; i++) { + u = hmac.doFinal(u); + for (int j = 0; j < t.length; j++) t[j] ^= u[j]; + } + int n = Math.min(t.length, length - off); + System.arraycopy(t, 0, out, off, n); + off += n; + } + return out; + } + + /** The official client lowercases bytewise, leaving anything outside ASCII alone. */ + private static String asciiLowerCase(String s) { + char[] chars = s.toCharArray(); + for (int i = 0; i < chars.length; i++) { + if (chars[i] >= 'A' && chars[i] <= 'Z') chars[i] += 'a' - 'A'; + } + return new String(chars); + } + + private static void incrementLittleEndian(byte[] counter) { + for (int i = 0; i < counter.length && ++counter[i] == 0; i++) { + // carry into the next byte + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTsException.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTsException.java new file mode 100644 index 0000000..b8b242f --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTsException.java @@ -0,0 +1,30 @@ +package eu.lixko.ts3j.client.myts; + +/** The myTeamSpeak service refused a request; the message is fit to show the user. */ +public final class MyTsException extends Exception { + + /** {@code ERROR_LOGIN_FAILED}: wrong email or password. */ + static final int LOGIN_FAILED = 202; + + private final int code; + + MyTsException(String message, int code) { + super(message); + this.code = code; + } + + MyTsException(String message, Throwable cause) { + super(message, cause); + this.code = 0; + } + + /** The service's {@code ErrorCommon}/{@code SyncStatus} code or HTTP status; 0 when there is none. */ + public int code() { + return code; + } + + /** The server no longer accepts the email and password, for instance after a password change. */ + public boolean credentialsRejected() { + return code == LOGIN_FAILED; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTsFiles.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTsFiles.java new file mode 100644 index 0000000..bf92339 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTsFiles.java @@ -0,0 +1,183 @@ +package eu.lixko.ts3j.client.myts; + +import eu.lixko.ts3j.client.proto.ProtobufReader; +import eu.lixko.ts3j.client.proto.ProtobufWriter; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; + +/** + * Files kept in myTeamSpeak cloud storage, as TeamSpeak 6 shares them in chat. The service + * hands out signed storage addresses: one to put a new file under this account's ID and a + * room, one to get a file someone put under theirs. Both need a signed-in account; the + * session is kept for later requests and renewed when it runs out. + * + *

    The storage addresses are signed for {@code Content-Type: text/plain} whatever the file + * is, both ways; a request without it is refused. + */ +public final class MyTsFiles { + + private static final String SIGNED_TYPE = "text/plain"; + private static final int TIMEOUT_MS = 30_000; + + private static final int ERROR_NOT_ALLOWED = 107; + private static final int ERROR_SESSION_EXPIRED = 109; + + private final MyTeamSpeakLogin login; + private final MyTeamSpeak service; + private MyTeamSpeak.Session session; + private MyTeamSpeak.Credentials sessionCredentials; + + public MyTsFiles(MyTeamSpeakLogin login) { + this(login, login.service()); + } + + MyTsFiles(MyTeamSpeakLogin login, MyTeamSpeak service) { + this.login = login; + this.service = service; + } + + /** Where a new file goes. */ + public record Upload(String fileId, String senderUserId, String url) { + } + + /** Asks for a place to put a new file shared in {@code room}. */ + public Upload requestUpload(String room) throws IOException, MyTsException { + return withSession(s -> { + String userId = ChatAttachment.padded(s.info().userId()); + byte[] request = new ProtobufWriter().string(1, s.id()).string(2, userId).string(3, room).toByteArray(); + FileInfo info = FileInfo.read(service.transport().call("user", "requestUploadFile", request)); + return new Upload(info.fileId, userId, info.url); + }); + } + + /** The address a file someone shared in {@code room} can be fetched from. */ + public String requestDownload(String owner, String room, String fileId) throws IOException, MyTsException { + return withSession(s -> { + byte[] request = new ProtobufWriter().string(1, s.id()).string(2, owner).string(3, room) + .string(4, fileId).toByteArray(); + return FileInfo.read(service.transport().call("user", "requestDownloadFile", request)).url; + }); + } + + /** Stores the file at an address {@link #requestUpload} gave. */ + public static void put(String url, InputStream data, long length) throws IOException { + HttpURLConnection http = open(url); + try { + http.setRequestMethod("PUT"); + http.setDoOutput(true); + http.setFixedLengthStreamingMode(length); + try (OutputStream out = http.getOutputStream()) { + data.transferTo(out); + } + int status = http.getResponseCode(); + if (status / 100 != 2) throw new IOException("The file store answered HTTP " + status); + } finally { + http.disconnect(); + } + } + + /** + * Fetches the file at an address {@link #requestDownload} gave. + * + * @throws IOException also when the file is larger than {@code maxBytes} + */ + public static byte[] get(String url, long maxBytes) throws IOException { + HttpURLConnection http = open(url); + try { + int status = http.getResponseCode(); + if (status != HttpURLConnection.HTTP_OK) throw new IOException("The file store answered HTTP " + status); + if (http.getContentLengthLong() > maxBytes) throw new IOException("The file is too large"); + try (InputStream in = http.getInputStream()) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buf = new byte[16 << 10]; + for (int n; (n = in.read(buf)) > 0; ) { + if (out.size() + n > maxBytes) throw new IOException("The file is too large"); + out.write(buf, 0, n); + } + return out.toByteArray(); + } + } finally { + http.disconnect(); + } + } + + /** Ends the kept session, e.g. on sign-out or exit; the next request signs in again. */ + public void close() { + MyTeamSpeak.Session ended; + synchronized (this) { + ended = session; + session = null; + sessionCredentials = null; + } + if (ended != null) service.signOut(ended.id()); + } + + private interface Request { + T run(MyTeamSpeak.Session session) throws IOException, MyTsException; + } + + private T withSession(Request request) throws IOException, MyTsException { + MyTeamSpeak.Session s = session(); + try { + return request.run(s); + } catch (MyTsException e) { + if (e.code() != ERROR_SESSION_EXPIRED) throw e; + synchronized (this) { + if (session == s) session = null; + } + return request.run(session()); + } + } + + private synchronized MyTeamSpeak.Session session() throws IOException, MyTsException { + MyTeamSpeak.Credentials credentials = login.credentials(); + if (session != null && sessionCredentials == credentials) return session; + if (session != null) service.signOut(session.id()); + session = null; + if (credentials == null) throw new MyTsException("Sign in to myTeamSpeak to share files", 0); + session = service.signIn(credentials); + sessionCredentials = credentials; + if (session.info().userId().isEmpty()) throw new MyTsException("The account has no myTeamSpeak ID", 0); + return session; + } + + private static HttpURLConnection open(String url) throws IOException { + HttpURLConnection http = (HttpURLConnection) new URL(url).openConnection(); + http.setConnectTimeout(TIMEOUT_MS); + http.setReadTimeout(TIMEOUT_MS); + http.setRequestProperty("Content-Type", SIGNED_TYPE); + return http; + } + + /** The service's {@code FileInfo} reply. */ + private record FileInfo(String fileId, String url) { + + static FileInfo read(byte[] reply) throws IOException, MyTsException { + ProtobufReader r = new ProtobufReader(reply); + boolean success = false; + int error = 0; + String fileId = "", url = ""; + while (r.next()) { + switch (r.fieldNumber()) { + case 1 -> success = r.readBool(); + case 2 -> error = (int) r.readVarint(); + case 5 -> fileId = r.readString(); + case 6 -> url = r.readString(); + default -> r.skip(); + } + } + if (success && !url.isEmpty()) return new FileInfo(fileId, url); + String message = switch (error) { + case ERROR_NOT_ALLOWED -> "The file is not available"; + case ERROR_SESSION_EXPIRED -> "The myTeamSpeak session ran out"; + default -> "myTeamSpeak refused the file (error " + error + ")"; + }; + throw new MyTsException(message, error); + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTsTransport.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTsTransport.java new file mode 100644 index 0000000..2818aa9 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/myts/MyTsTransport.java @@ -0,0 +1,54 @@ +package eu.lixko.ts3j.client.myts; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URI; +import java.nio.charset.StandardCharsets; + +/** + * One call to the myTeamSpeak client API: a protobuf request to a method of a + * service endpoint, answered with a protobuf reply. + */ +interface MyTsTransport { + + byte[] call(String endpoint, String method, byte[] request) throws IOException, MyTsException; + + /** + * The official client's wire form: an HTTP/1.1 POST of {@code } + * as {@code application/ts3cloud}. The reply is the bare protobuf, whatever its + * Content-Type says. Cloudflare in front turns away clients that look different, + * hence the cpp-httplib user agent. + */ + static MyTsTransport https(URI base) { + return (endpoint, method, request) -> { + byte[] name = method.getBytes(StandardCharsets.US_ASCII); + HttpURLConnection http = (HttpURLConnection) base.resolve(endpoint).toURL().openConnection(); + try { + http.setRequestMethod("POST"); + http.setConnectTimeout(15_000); + http.setReadTimeout(30_000); + http.setDoOutput(true); + http.setRequestProperty("Content-Type", "application/ts3cloud"); + http.setRequestProperty("Accept", "*/*"); + http.setRequestProperty("User-Agent", "cpp-httplib/0.11.1"); + http.setFixedLengthStreamingMode(1 + name.length + request.length); + try (OutputStream out = http.getOutputStream()) { + out.write(name.length); + out.write(name); + out.write(request); + } + int status = http.getResponseCode(); + if (status != HttpURLConnection.HTTP_OK) { + throw new MyTsException("The myTeamSpeak server answered HTTP " + status, status); + } + try (InputStream in = http.getInputStream()) { + return in.readAllBytes(); + } + } finally { + http.disconnect(); + } + }; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/AvatarAdmin.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/AvatarAdmin.java new file mode 100644 index 0000000..5b572a8 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/AvatarAdmin.java @@ -0,0 +1,120 @@ +package eu.lixko.ts3j.client.net; + +import com.github.manevolent.ts3j.command.SingleCommand; +import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; +import com.github.manevolent.ts3j.protocol.ProtocolRole; +import eu.lixko.ts3j.client.net.avatar.AvatarNaming; +import eu.lixko.ts3j.client.net.avatar.ImageFormat; +import eu.lixko.ts3j.client.net.filetransfer.FileTransfer; +import eu.lixko.ts3j.client.net.filetransfer.FileTransferManager; + +import java.io.File; +import java.nio.file.Files; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * Publishes and withdraws the local client's avatar, the way the official client does + * it: the picture goes into channel 0's file repository as {@code /avatar_} and + * {@code client_flag_avatar} is then set to its MD5, which is what other clients key + * their downloads on. + */ +final class AvatarAdmin { + + /** The server's own default for {@code i_client_max_avatar_filesize}. */ + static final int DEFAULT_MAX_AVATAR_BYTES = 200_000; + /** The largest avatar we are willing to download, whatever a server allows. */ + static final int MAX_AVATAR_DOWNLOAD_BYTES = 8 * 1024 * 1024; + + private static final long UPLOAD_TIMEOUT_MS = 60_000; + + private final TeamspeakConnection conn; + + AvatarAdmin(TeamspeakConnection conn) { + this.conn = conn; + } + + /** + * How large an avatar this server lets us upload, from + * {@code i_client_max_avatar_filesize}, or the server default while unknown. + */ + int maxUploadBytes() { + int limit = conn.getModel().selfPermissionValue("i_client_max_avatar_filesize"); + return limit > 0 ? limit : DEFAULT_MAX_AVATAR_BYTES; + } + + /** Uploads {@code source} as our avatar and announces it; returns its flag. */ + String upload(File source) throws Exception { + byte[] data = Files.readAllBytes(source.toPath()); + if (data.length == 0) throw new IllegalArgumentException("That file is empty"); + if (ImageFormat.detect(data) == null) { + throw new IllegalArgumentException("Avatars must be PNG, JPEG, GIF or BMP images"); + } + int limit = maxUploadBytes(); + if (data.length > limit) { + throw new IllegalArgumentException("This server limits avatars to " + (limit / 1024) + " KiB"); + } + String name = ownFileName(); + + CountDownLatch done = new CountDownLatch(1); + FileTransfer transfer = fileTransfers().upload(0, "", "/" + name, source, true, t -> { + if (t.isDone()) done.countDown(); + }); + if (!done.await(UPLOAD_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { + throw new IllegalStateException("The upload did not finish in time"); + } + if (transfer.getState() != FileTransfer.State.COMPLETED) { + throw new IllegalStateException(transfer.getErrorMessage() == null + ? "The upload failed" : transfer.getErrorMessage()); + } + String flag = AvatarNaming.flag(data); + setFlag(flag); + conn.getAvatars().put(data); + return flag; + } + + /** Clears our avatar flag and removes the file from the server. */ + void remove() throws Exception { + setFlag(""); + try { + deleteFile(conn.getSelfUniqueId()); + } catch (Exception ignored) { + // The flag is what other clients go by; a leftover file only wastes space. + // Servers refuse the deletion unless we may delete others' avatars too. + } + } + + /** + * Deletes another client's avatar, which needs {@code b_client_avatar_delete_other}; + * the server then clears their flag for everyone. + */ + void removeOther(String uniqueId) throws Exception { + deleteFile(uniqueId); + } + + /** + * Deleting names the avatar by its owner's unique id, {@code /avatar_}, which the + * server maps to the stored file itself; the stored name is refused ("convert error"). + */ + private void deleteFile(String uniqueId) throws Exception { + fileTransfers().delete(0, "", "/avatar_" + uniqueId); + } + + private void setFlag(String flag) throws Exception { + SingleCommand cmd = new SingleCommand("clientupdate", ProtocolRole.CLIENT, + new CommandSingleParameter("client_flag_avatar", flag)); + conn.socket().executeCommand(cmd).complete(); + } + + private String ownFileName() { + String name = AvatarNaming.fileName(conn.getSelfUniqueId()); + if (name == null) throw new IllegalStateException("Our identity has no usable unique id"); + return name; + } + + private FileTransferManager fileTransfers() { + FileTransferManager ft = conn.fileTransfers(); + if (ft == null) throw new IllegalStateException("Not connected"); + return ft; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/BanAdmin.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/BanAdmin.java new file mode 100644 index 0000000..1d488ba --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/BanAdmin.java @@ -0,0 +1,115 @@ +package eu.lixko.ts3j.client.net; + +import com.github.manevolent.ts3j.command.CommandException; +import com.github.manevolent.ts3j.command.SingleCommand; +import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; +import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent; +import com.github.manevolent.ts3j.protocol.ProtocolRole; +import eu.lixko.ts3j.client.net.ban.BanEntry; +import eu.lixko.ts3j.client.net.ban.BanRule; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** + * The server's ban list: reading it and adding, replacing and deleting entries. + * + *

    Split out of {@link TeamspeakConnection} like {@link ChannelAdmin}, and for the same + * reason: it is a self-contained request/response corner of the protocol that only the + * ban list window uses. Every call here blocks and must run off the UI thread; the + * connection's public wrappers do that. + */ +final class BanAdmin { + + /** What {@code banlist} answers when there are no bans at all. */ + private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501; + + private final TeamspeakConnection conn; + + /** + * The {@code banlist} reply in progress. The server answers the command with a burst + * of {@code notifybanlist} events rather than a command response, so one request may + * be in flight at a time and its entries are collected here until the command itself + * completes. + */ + private volatile List listing; + + BanAdmin(TeamspeakConnection conn) { + this.conn = conn; + } + + /** Reads every ban on the server. */ + List list() throws Exception { + List entries = Collections.synchronizedList(new ArrayList<>()); + listing = entries; + try { + conn.socket().executeCommand(new SingleCommand("banlist", ProtocolRole.CLIENT)).complete(); + // The entries were queued on the event thread before the command's own reply + // was read, so draining that thread is what guarantees they have all landed. + conn.awaitEventsProcessed(); + } catch (CommandException e) { + if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e; + } finally { + listing = null; + } + return new ArrayList<>(entries); + } + + /** Collects one {@code notifybanlist} entry for the request in flight. */ + void onListEntry(UnknownTeamspeakEvent e) { + List entries = listing; + if (entries == null) return; + BanEntry entry = BanEntry.from(e.getMap()); + if (entry.id >= 0) entries.add(entry); + } + + /** + * Adds a ban. + * + * @return the new ban's id, or -1 where the server did not name it + */ + int add(BanRule rule) throws Exception { + if (!rule.hasTarget()) throw new IllegalArgumentException("A ban needs something to match"); + SingleCommand cmd = new SingleCommand("banadd", ProtocolRole.CLIENT); + addIfSet(cmd, "ip", rule.ipRegex); + addIfSet(cmd, "name", rule.nameRegex); + addIfSet(cmd, "uid", rule.uid); + addIfSet(cmd, "mytsid", rule.mytsid); + if (!rule.isPermanent()) cmd.add(new CommandSingleParameter("time", Long.toString(rule.durationSeconds))); + addIfSet(cmd, "banreason", rule.reason); + for (SingleCommand answer : conn.socket().executeCommand(cmd).get()) { + Map fields = answer.toMap(); + if (fields.containsKey("banid")) { + return BanEntry.from(fields).id; + } + } + return -1; + } + + /** + * Replaces a ban with a re-written one. The server has no way to edit a ban in place, + * so the new one is added before the old is removed: a failure half-way leaves the + * client banned twice rather than not at all. + */ + void replace(int banId, BanRule rule) throws Exception { + add(rule); + try { + delete(banId); + } catch (Exception e) { + throw new IllegalStateException("The edited ban was added, but the original could not be" + + " removed: " + e.getMessage(), e); + } + } + + void delete(int banId) throws Exception { + SingleCommand cmd = new SingleCommand("bandel", ProtocolRole.CLIENT, + new CommandSingleParameter("banid", Integer.toString(banId))); + conn.socket().executeCommand(cmd).complete(); + } + + private static void addIfSet(SingleCommand cmd, String key, String value) { + if (value != null && !value.isEmpty()) cmd.add(new CommandSingleParameter(key, value)); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelAdmin.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelAdmin.java new file mode 100644 index 0000000..76e6d42 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelAdmin.java @@ -0,0 +1,282 @@ +package eu.lixko.ts3j.client.net; + +import com.github.manevolent.ts3j.api.Channel; +import com.github.manevolent.ts3j.command.MultiCommand; +import com.github.manevolent.ts3j.command.SingleCommand; +import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; +import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent; +import com.github.manevolent.ts3j.protocol.ProtocolRole; +import eu.lixko.ts3j.client.net.filetransfer.FileTransfer; +import eu.lixko.ts3j.client.net.filetransfer.FileTransferManager; +import eu.lixko.ts3j.client.net.filetransfer.RemoteFile; + +import java.io.File; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.zip.CRC32; + +/** + * Everything the channel editor needs of the server: reading and writing a channel's + * properties and its needed-power permissions, plus the virtual server's icon store. + * + *

    Split out of {@link TeamspeakConnection} because it is a self-contained request/ + * response corner of the protocol that only the editor uses. Every call here blocks and + * must run off the UI thread; the connection's public wrappers do that. + */ +final class ChannelAdmin { + + /** The directory a server's icons live in, where the server has one. */ + private static final String ICON_DIRECTORY = "icons"; + + /** How long to wait for a whole icon to travel over the file connection. */ + private static final long ICON_UPLOAD_TIMEOUT_MS = 30_000; + + private final TeamspeakConnection conn; + + /** + * The {@code channelpermlist} reply in progress. TeamSpeak answers the command with a + * burst of {@code notifychannelpermlist} events rather than a command response, and + * only the first of them repeats the channel id, so one request may be in flight at a + * time and its entries are collected here until the command itself completes. + */ + private volatile PermRequest permRequest; + + ChannelAdmin(TeamspeakConnection conn) { + this.conn = conn; + } + + // ---- channel properties ---- + + /** Reads a channel's full property set. */ + ChannelSettings readSettings(int channelId) throws Exception { + Channel info = conn.socket().getChannelInfo(channelId); + if (info == null) throw new IllegalStateException("The server did not describe that channel"); + return ChannelSettings.from(channelId, info.getMap()); + } + + /** + * Creates a channel below {@code parentId} (0 being the top level). + * + * @param properties the new channel's properties, as {@link ChannelSettings#creationParameters} + * @return the new channel's id + */ + int create(int parentId, Map properties) throws Exception { + SingleCommand cmd = new SingleCommand("channelcreate", ProtocolRole.CLIENT); + cmd.add(new CommandSingleParameter("cpid", Integer.toString(parentId))); + for (Map.Entry property : properties.entrySet()) { + cmd.add(new CommandSingleParameter(property.getKey(), property.getValue())); + } + for (SingleCommand answer : conn.socket().executeCommand(cmd).get()) { + int cid = parseInt(answer.toMap().get("cid"), -1); + if (cid > 0) return cid; + } + // Some servers acknowledge the command without naming the channel; the + // notifychannelcreated they also send does name it, so read it off the model + // once that event has been handled. + conn.awaitEventsProcessed(); + ChannelNode created = conn.getModel().findChannelByName(parentId, properties.get("channel_name")); + if (created == null) throw new IllegalStateException("The server did not report the new channel"); + return created.id; + } + + /** Applies {@code changes} (property name to value) with a single {@code channeledit}. */ + void edit(int channelId, Map changes) throws Exception { + if (changes.isEmpty()) return; + SingleCommand cmd = new SingleCommand("channeledit", ProtocolRole.CLIENT); + cmd.add(new CommandSingleParameter("cid", Integer.toString(channelId))); + for (Map.Entry change : changes.entrySet()) { + cmd.add(new CommandSingleParameter(change.getKey(), change.getValue())); + } + conn.socket().executeCommand(cmd).complete(); + } + + /** Deletes a channel, with its sub-channels and whoever is in them moved out when {@code force}. */ + void delete(int channelId, boolean force) throws Exception { + conn.socket().executeCommand(new SingleCommand("channeldelete", ProtocolRole.CLIENT, + new CommandSingleParameter("cid", Integer.toString(channelId)), + new CommandSingleParameter("force", force ? "1" : "0"))).complete(); + } + + // ---- channel permissions ---- + + /** + * Reads the permissions set directly on a channel. + * + * @return permission name to value, holding only the permissions the channel itself + * carries — anything inherited from a group is absent + */ + Map readPermissions(int channelId) throws Exception { + if (!conn.getModel().hasPermissionNames()) { + // channelpermlist reports numeric ids, which only the permissionlist response + // gives names to; without it the values could not be told apart. + throw new IllegalStateException("The server did not send its permission list"); + } + PermRequest request = new PermRequest(channelId); + permRequest = request; + try { + SingleCommand cmd = new SingleCommand("channelpermlist", ProtocolRole.CLIENT, + new CommandSingleParameter("cid", Integer.toString(channelId))); + conn.socket().executeCommand(cmd).complete(); + // The entries were queued on the event thread before the command's own reply + // was read, so draining that thread is what guarantees they have all landed. + conn.awaitEventsProcessed(); + } finally { + permRequest = null; + } + + Map byName = new LinkedHashMap<>(); + for (Map.Entry entry : request.values.entrySet()) { + String name = conn.getModel().permissionName(entry.getKey()); + if (name != null) byName.put(name, entry.getValue()); + } + return byName; + } + + /** Collects one {@code notifychannelpermlist} entry for the request in flight. */ + void onPermListEntry(UnknownTeamspeakEvent e) { + PermRequest request = permRequest; + if (request == null) return; + String cid = e.get("cid"); + if (cid != null && !cid.isEmpty() && parseInt(cid, -1) != request.channelId) return; + int permId = parseInt(e.get("permid"), -1); + if (permId >= 0) request.values.put(permId, parseInt(e.get("permvalue"), 0)); + } + + /** + * Sets and clears channel permissions by name. A permission set to a value is added or + * updated; one that is cleared is removed so the channel inherits it again. + */ + void writePermissions(int channelId, Map set, Collection remove) + throws Exception { + if (!set.isEmpty()) { + List parts = new ArrayList<>(set.size()); + for (Map.Entry perm : set.entrySet()) { + parts.add(new SingleCommand("channeladdperm", ProtocolRole.CLIENT, + new CommandSingleParameter("permsid", perm.getKey()), + new CommandSingleParameter("permvalue", Integer.toString(perm.getValue())))); + } + send("channeladdperm", channelId, parts); + } + if (!remove.isEmpty()) { + List parts = new ArrayList<>(remove.size()); + for (String name : remove) { + parts.add(new SingleCommand("channeldelperm", ProtocolRole.CLIENT, + new CommandSingleParameter("permsid", name))); + } + send("channeldelperm", channelId, parts); + } + } + + private void send(String name, int channelId, List parts) throws Exception { + MultiCommand cmd = new MultiCommand(name, ProtocolRole.CLIENT, parts); + cmd.add(new CommandSingleParameter("cid", Integer.toString(channelId))); + conn.socket().executeCommand(cmd).complete(); + } + + // ---- the server's icon store ---- + + /** + * The ids of the icons uploaded to this virtual server, which live in channel 0's file + * repository as {@code /icon_}. + */ + List listIcons() throws Exception { + List ids = new ArrayList<>(); + boolean hasIconDirectory = false; + for (RemoteFile file : fileTransfers().list(0, "", "/")) { + if (file.isDirectory()) { + hasIconDirectory |= file.getName().equals(ICON_DIRECTORY); + continue; + } + addIcon(ids, file); + } + // Newer servers keep the icons in their own directory rather than loose in the + // repository's root; both layouts exist, so whichever this server uses is read. + if (hasIconDirectory) { + for (RemoteFile file : fileTransfers().list(0, "", "/" + ICON_DIRECTORY)) { + if (!file.isDirectory()) addIcon(ids, file); + } + } + return ids; + } + + private static void addIcon(List ids, RemoteFile file) { + if (!file.getName().startsWith("icon_")) return; + long id = parseLong(file.getName().substring("icon_".length())); + if (id > 0 && !ids.contains(id)) ids.add(id); + } + + /** + * Uploads an image as a server icon. + * + * @return the icon's id, which TeamSpeak derives from the file's CRC32 + */ + long uploadIcon(File source) throws Exception { + byte[] data = Files.readAllBytes(source.toPath()); + if (data.length == 0) throw new IllegalArgumentException("That file is empty"); + if (data.length > TeamspeakConnection.MAX_ICON_BYTES) { + throw new IllegalArgumentException("Icons may not be larger than " + + (TeamspeakConnection.MAX_ICON_BYTES / 1024) + " KiB"); + } + CRC32 crc = new CRC32(); + crc.update(data); + long id = crc.getValue(); + + CountDownLatch done = new CountDownLatch(1); + FileTransfer transfer = fileTransfers().upload(0, "", "/icon_" + id, source, true, t -> { + if (t.isDone()) done.countDown(); + }); + if (!done.await(ICON_UPLOAD_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { + throw new IllegalStateException("The upload did not finish in time"); + } + if (transfer.getState() != FileTransfer.State.COMPLETED) { + throw new IllegalStateException(transfer.getErrorMessage() == null + ? "The upload failed" : transfer.getErrorMessage()); + } + return id; + } + + void deleteIcon(long iconId) throws Exception { + fileTransfers().delete(0, "", "/icon_" + iconId); + } + + private FileTransferManager fileTransfers() { + FileTransferManager ft = conn.fileTransfers(); + if (ft == null) throw new IllegalStateException("Not connected"); + return ft; + } + + // ---- helpers ---- + + private static int parseInt(String value, int fallback) { + try { + return value == null || value.isEmpty() ? fallback : Integer.parseInt(value.trim()); + } catch (NumberFormatException e) { + return fallback; + } + } + + private static long parseLong(String value) { + try { + return Long.parseLong(value.trim()); + } catch (NumberFormatException e) { + return 0; + } + } + + /** One in-flight {@code channelpermlist} and the entries received for it so far. */ + private static final class PermRequest { + final int channelId; + final Map values = new ConcurrentHashMap<>(); + + PermRequest(int channelId) { + this.channelId = channelId; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelCodec.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelCodec.java new file mode 100644 index 0000000..e97c299 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelCodec.java @@ -0,0 +1,73 @@ +package eu.lixko.ts3j.client.net; + +/** + * The voice codecs a channel can use, in TeamSpeak's own id order, with the editor's + * presets and what one talking client costs in bandwidth. + */ +public final class ChannelCodec { + + /** Codec names, indexed by {@link ChannelSettings#codec}. */ + public static final String[] NAMES = { + "Speex Narrowband", "Speex Wideband", "Speex Ultra-Wideband", + "CELT Mono", "Opus Voice", "Opus Music"}; + + public static final int OPUS_VOICE = 4; + public static final int OPUS_MUSIC = 5; + public static final int MAX_QUALITY = 10; + + /** The channel editor's presets; a codec and quality matching none of them is custom. */ + public enum Preset { + VOICE_MOBILE("Voice Mobile", OPUS_VOICE, 4), + VOICE_DESKTOP("Voice Desktop", OPUS_VOICE, 6), + MUSIC("Music", OPUS_MUSIC, 6); + + public final String label; + public final int codec; + public final int quality; + + Preset(String label, int codec, int quality) { + this.label = label; + this.codec = codec; + this.quality = quality; + } + + /** The preset with this codec and quality, or null for a custom setting. */ + public static Preset of(int codec, int quality) { + for (Preset p : values()) { + if (p.codec == codec && p.quality == quality) return p; + } + return null; + } + } + + /** + * Bandwidth per talking client in KiB/s at quality 0 and 10, per codec, as published by + * TeamSpeak. The steps in between are interpolated: the client shows a figure per + * quality step, and only the two ends of each codec's range are documented. + */ + private static final double[][] BANDWIDTH_RANGE = { + {2.49, 5.22}, {2.69, 7.37}, {2.73, 7.57}, {6.10, 13.92}, {2.73, 7.71}, {3.08, 11.87}}; + + private ChannelCodec() { + } + + public static String name(int codec) { + return NAMES[clampCodec(codec)]; + } + + public static int clampCodec(int codec) { + return Math.max(0, Math.min(NAMES.length - 1, codec)); + } + + /** KiB/s one talking client costs. */ + public static double bandwidth(int codec, int quality) { + double[] range = BANDWIDTH_RANGE[clampCodec(codec)]; + int q = Math.max(0, Math.min(MAX_QUALITY, quality)); + return range[0] + (range[1] - range[0]) * q / MAX_QUALITY; + } + + /** {@link #bandwidth} as the editor shows it. */ + public static String bandwidthText(int codec, int quality) { + return String.format("%.2f KiB/s", bandwidth(codec, quality)); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelNode.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelNode.java new file mode 100644 index 0000000..d6b71b0 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelNode.java @@ -0,0 +1,66 @@ +package eu.lixko.ts3j.client.net; + +import java.util.ArrayList; +import java.util.List; + +/** + * View-model of a TeamSpeak channel. The event thread updates it while the UI reads it, so + * every field is volatile; {@link #children} and {@link #clients} are replaced whole on each + * {@link ServerModel#buildTree()}, never changed in place. + */ +public final class ChannelNode { + public final int id; + public volatile int parentId; + public volatile int order; + public volatile String name; + public volatile String topic = ""; + public volatile String description = ""; + public volatile boolean descriptionLoaded; + public volatile boolean hasPassword; + public volatile boolean permanent; + public volatile int maxClients = -1; + /** Id of the channel's custom icon in the server's file repository, or 0 for none. */ + public volatile long iconId; + /** Whether the server sends us this channel's client list; set from the subscription events. */ + public volatile boolean subscribed; + + /** As of the last {@link ServerModel#buildTree()}; unmodifiable. */ + public volatile List children = List.of(); + public volatile List clients = List.of(); + + public ChannelNode(int id, String name) { + this.id = id; + this.name = name; + } + + /** @return whether this channel or any channel below it is subscribed */ + public boolean anySubscribed() { + if (subscribed) return true; + for (ChannelNode child : children) { + if (child.anySubscribed()) return true; + } + return false; + } + + /** @return whether this channel and every channel below it is subscribed */ + public boolean allSubscribed() { + if (!subscribed) return false; + for (ChannelNode child : children) { + if (!child.allSubscribed()) return false; + } + return true; + } + + /** @return this channel's id, followed by those of the channels below it when {@code family} */ + public List familyIds(boolean family) { + List ids = new ArrayList<>(); + collectIds(family, ids); + return ids; + } + + private void collectIds(boolean family, List into) { + into.add(id); + if (!family) return; + for (ChannelNode child : children) child.collectIds(true, into); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelSettings.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelSettings.java new file mode 100644 index 0000000..c02b1d6 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChannelSettings.java @@ -0,0 +1,219 @@ +package eu.lixko.ts3j.client.net; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * The editable properties of a channel, as read from {@code channelinfo} and written + * back with {@code channeledit}. + * + *

    Kept apart from {@link ChannelNode} on purpose: the node is the live tree state the + * server pushes at us, while this is a snapshot an editor works on. Submitting compares + * the edited copy against the untouched original ({@link #changesFrom}) so only the + * properties the user actually changed are sent — TeamSpeak refuses the whole command + * when it contains one property the client may not modify, even an unchanged one. + */ +public final class ChannelSettings { + + /** How long a channel outlives its last occupant. */ + public enum Type {TEMPORARY, SEMI_PERMANENT, PERMANENT} + + /** TeamSpeak's ceiling for {@code channel_delete_delay}, in seconds. */ + public static final int MAX_DELETE_DELAY = 604800; + + public int id; + public int parentId; + public String name = ""; + public String topic = ""; + public String description = ""; + public String phoneticName = ""; + /** Whether the server reports a password on this channel; the password itself is never readable. */ + public boolean hasPassword; + /** {@code null} leaves the password alone, {@code ""} removes it, anything else sets it. */ + public String password; + public Type type = Type.PERMANENT; + public boolean defaultChannel; + /** The sibling this channel sorts after, or 0 to sort first. */ + public int order; + public int neededTalkPower; + /** TeamSpeak codec id; see {@code com.github.manevolent.ts3j.api.Codec}. */ + public int codec = 4; + public int codecQuality = 6; + public boolean encrypted = true; + public int deleteDelay; + public boolean maxClientsUnlimited = true; + public int maxClients = 16; + public boolean familyInherited = true; + public boolean familyUnlimited; + public int maxFamilyClients = 16; + public long iconId; + + /** Reads a {@code channelinfo} (or {@code channellist}) property map. */ + public static ChannelSettings from(int channelId, Map props) { + ChannelSettings s = new ChannelSettings(); + s.id = channelId; + s.parentId = intOf(props, "pid", intOf(props, "cpid", 0)); + s.name = strOf(props, "channel_name"); + s.topic = strOf(props, "channel_topic"); + s.description = strOf(props, "channel_description"); + s.phoneticName = strOf(props, "channel_name_phonetic"); + s.hasPassword = boolOf(props, "channel_flag_password"); + if (boolOf(props, "channel_flag_permanent")) s.type = Type.PERMANENT; + else if (boolOf(props, "channel_flag_semi_permanent")) s.type = Type.SEMI_PERMANENT; + else s.type = Type.TEMPORARY; + s.defaultChannel = boolOf(props, "channel_flag_default"); + s.order = intOf(props, "channel_order", 0); + s.neededTalkPower = intOf(props, "channel_needed_talk_power", 0); + s.codec = intOf(props, "channel_codec", 4); + s.codecQuality = intOf(props, "channel_codec_quality", 6); + s.encrypted = !boolOf(props, "channel_codec_is_unencrypted"); + s.deleteDelay = intOf(props, "channel_delete_delay", 0); + s.maxClientsUnlimited = boolOf(props, "channel_flag_maxclients_unlimited"); + s.maxClients = Math.max(0, intOf(props, "channel_maxclients", 16)); + s.familyInherited = boolOf(props, "channel_flag_maxfamilyclients_inherited"); + s.familyUnlimited = boolOf(props, "channel_flag_maxfamilyclients_unlimited"); + s.maxFamilyClients = Math.max(0, intOf(props, "channel_maxfamilyclients", 16)); + s.iconId = longOf(props, "channel_icon_id"); + return s; + } + + public ChannelSettings copy() { + ChannelSettings c = new ChannelSettings(); + c.id = id; + c.parentId = parentId; + c.name = name; + c.topic = topic; + c.description = description; + c.phoneticName = phoneticName; + c.hasPassword = hasPassword; + c.password = password; + c.type = type; + c.defaultChannel = defaultChannel; + c.order = order; + c.neededTalkPower = neededTalkPower; + c.codec = codec; + c.codecQuality = codecQuality; + c.encrypted = encrypted; + c.deleteDelay = deleteDelay; + c.maxClientsUnlimited = maxClientsUnlimited; + c.maxClients = maxClients; + c.familyInherited = familyInherited; + c.familyUnlimited = familyUnlimited; + c.maxFamilyClients = maxFamilyClients; + c.iconId = iconId; + return c; + } + + /** + * The {@code channeledit} parameters needed to turn {@code original} into this. + * + * @return property name to value, empty when nothing changed + */ + public Map changesFrom(ChannelSettings original) { + Map changes = new LinkedHashMap<>(); + putIfChanged(changes, "channel_name", name, original.name); + putIfChanged(changes, "channel_topic", topic, original.topic); + putIfChanged(changes, "channel_description", description, original.description); + putIfChanged(changes, "channel_name_phonetic", phoneticName, original.phoneticName); + if (password != null) changes.put("channel_password", password); + if (type != original.type) { + // The three flags are mutually exclusive and the server wants the whole set: + // clearing one without setting another leaves the channel type ambiguous. + changes.put("channel_flag_permanent", flag(type == Type.PERMANENT)); + changes.put("channel_flag_semi_permanent", flag(type == Type.SEMI_PERMANENT)); + changes.put("channel_flag_temporary", flag(type == Type.TEMPORARY)); + } + // Clearing the default flag is meaningless — some channel has to be the default — + // so only setting it is ever sent. + if (defaultChannel && !original.defaultChannel) changes.put("channel_flag_default", "1"); + putIfChanged(changes, "channel_order", order, original.order); + putIfChanged(changes, "channel_needed_talk_power", neededTalkPower, original.neededTalkPower); + putIfChanged(changes, "channel_codec", codec, original.codec); + putIfChanged(changes, "channel_codec_quality", codecQuality, original.codecQuality); + putIfChanged(changes, "channel_codec_is_unencrypted", !encrypted, !original.encrypted); + putIfChanged(changes, "channel_delete_delay", deleteDelay, original.deleteDelay); + putIfChanged(changes, "channel_flag_maxclients_unlimited", + maxClientsUnlimited, original.maxClientsUnlimited); + if (!maxClientsUnlimited) putIfChanged(changes, "channel_maxclients", maxClients, original.maxClients); + putIfChanged(changes, "channel_flag_maxfamilyclients_inherited", + familyInherited, original.familyInherited); + putIfChanged(changes, "channel_flag_maxfamilyclients_unlimited", + familyUnlimited, original.familyUnlimited); + if (!familyInherited && !familyUnlimited) { + putIfChanged(changes, "channel_maxfamilyclients", maxFamilyClients, original.maxFamilyClients); + } + if (iconId != original.iconId) changes.put("channel_icon_id", Long.toString(iconId)); + return changes; + } + + /** + * The {@code channelcreate} parameters for a channel that does not exist yet. + * + *

    Everything a fresh channel would get anyway is left out, because TeamSpeak checks + * a create permission per property that is present — a client allowed to create plain + * channels but not, say, ones with a topic must not send an empty topic. What the + * server cannot infer is always sent: the name, the channel type (whose absent flags + * would silently mean temporary), the codec, and the client limits when they are not + * unlimited. + */ + public Map creationParameters() { + Map params = changesFrom(new ChannelSettings()); + params.put("channel_name", name); + params.put("channel_flag_permanent", flag(type == Type.PERMANENT)); + params.put("channel_flag_semi_permanent", flag(type == Type.SEMI_PERMANENT)); + params.put("channel_flag_temporary", flag(type == Type.TEMPORARY)); + params.put("channel_codec", Integer.toString(codec)); + params.put("channel_codec_quality", Integer.toString(codecQuality)); + if (!maxClientsUnlimited) params.put("channel_maxclients", Integer.toString(maxClients)); + if (!familyInherited && !familyUnlimited) { + params.put("channel_maxfamilyclients", Integer.toString(maxFamilyClients)); + } + if (password == null || password.isEmpty()) params.remove("channel_password"); + return params; + } + + private static void putIfChanged(Map into, String key, String value, String was) { + if (!value.equals(was)) into.put(key, value); + } + + private static void putIfChanged(Map into, String key, int value, int was) { + if (value != was) into.put(key, Integer.toString(value)); + } + + private static void putIfChanged(Map into, String key, boolean value, boolean was) { + if (value != was) into.put(key, flag(value)); + } + + private static String flag(boolean set) { + return set ? "1" : "0"; + } + + private static String strOf(Map props, String key) { + String v = props.get(key); + return v == null ? "" : v; + } + + private static boolean boolOf(Map props, String key) { + return "1".equals(props.get(key)); + } + + private static int intOf(Map props, String key, int fallback) { + try { + String v = props.get(key); + return v == null || v.isEmpty() ? fallback : Integer.parseInt(v.trim()); + } catch (NumberFormatException e) { + return fallback; + } + } + + private static long longOf(Map props, String key) { + try { + String v = props.get(key); + if (v == null || v.isEmpty()) return 0; + long id = Long.parseLong(v.trim()); + return id < 0 ? id & 0xFFFFFFFFL : id; + } catch (NumberFormatException e) { + return 0; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ClientEntry.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ClientEntry.java new file mode 100644 index 0000000..fad4d16 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ClientEntry.java @@ -0,0 +1,90 @@ +package eu.lixko.ts3j.client.net; + +/** + * View-model of a connected client. The event and audio threads update it while the UI reads + * it, so every field is volatile; {@link #serverGroupIds} is replaced, never changed in place. + */ +public final class ClientEntry { + public final int id; + public volatile int channelId; + public volatile String nickname; + /** How text-to-speech should say the nickname ({@code client_nickname_phonetic}). */ + public volatile String phoneticNickname = ""; + public volatile String uniqueId = ""; + public volatile int databaseId; + public volatile int type; // 0 = normal voice client, 1 = server-query + public volatile int talkPower; + /** Waiting for a moderator to grant talk power ({@code client_talk_request}). */ + public volatile boolean talkRequest; + + public volatile int[] serverGroupIds = new int[0]; + public volatile int channelGroupId; + + // Filled on demand from clientinfo. + public volatile String platform = ""; + public volatile String version = ""; + public volatile long idleTimeMs; + public volatile String description = ""; + /** MD5 of the client's avatar ({@code client_flag_avatar}); empty when they have none. */ + public volatile String avatarFlag = ""; + /** Where the server places the client ({@code client_country}), as an ISO code; empty when it cannot tell. */ + public volatile String country = ""; + /** File transfer traffic this month ({@code client_month_bytes_*}), -1 until asked for. */ + public volatile long monthBytesDownloaded = -1; + public volatile long monthBytesUploaded = -1; + + public volatile boolean talking; + public volatile boolean inputMuted; // microphone muted (client_input_muted) + public volatile boolean outputMuted; // speakers muted / deafened (client_output_muted) + /** False while the capture device is unavailable: another tab holds the microphone. */ + public volatile boolean inputHardware = true; + /** False while the playback device is unavailable. */ + public volatile boolean outputHardware = true; + public volatile boolean away; + /** The message published with the away state, empty when there is none. */ + public volatile String awayMessage = ""; + public volatile boolean channelCommander; + /** Unread messages in the client's offline message inbox ({@code client_unread_messages}). */ + public volatile int unreadMessages; + public volatile boolean self; + + public ClientEntry(int id, String nickname) { + this.id = id; + this.nickname = nickname; + } + + public boolean isQuery() { + return type == 1; + } + + public boolean inServerGroup(int groupId) { + for (int id : serverGroupIds) if (id == groupId) return true; + return false; + } + + /** Adds a server group id, if not already present. */ + public void addServerGroup(int groupId) { + int[] ids = serverGroupIds; + for (int id : ids) if (id == groupId) return; + int[] updated = java.util.Arrays.copyOf(ids, ids.length + 1); + updated[ids.length] = groupId; + serverGroupIds = updated; + } + + /** Removes a server group id, if present. */ + public void removeServerGroup(int groupId) { + int[] ids = serverGroupIds; + int index = -1; + for (int i = 0; i < ids.length; i++) { + if (ids[i] == groupId) { + index = i; + break; + } + } + if (index < 0) return; + int[] updated = new int[ids.length - 1]; + System.arraycopy(ids, 0, updated, 0, index); + System.arraycopy(ids, index + 1, updated, index, ids.length - index - 1); + serverGroupIds = updated; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ClientStatus.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ClientStatus.java new file mode 100644 index 0000000..bb50df3 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ClientStatus.java @@ -0,0 +1,29 @@ +package eu.lixko.ts3j.client.net; + +/** + * What the channel tree shows for a client, in the order the official client gives the + * states priority: the first that applies wins. + */ +public enum ClientStatus { + QUERY, + SPEAKERS_DISABLED, + SPEAKERS_MUTED, + MIC_DISABLED, + MIC_MUTED, + AWAY, + COMMANDER_TALKING, + COMMANDER, + TALKING, + IDLE; + + public static ClientStatus of(ClientEntry c) { + if (c.isQuery()) return QUERY; + if (!c.outputHardware) return SPEAKERS_DISABLED; + if (c.outputMuted) return SPEAKERS_MUTED; + if (!c.inputHardware) return MIC_DISABLED; + if (c.inputMuted) return MIC_MUTED; + if (c.away) return AWAY; + if (c.channelCommander) return c.talking ? COMMANDER_TALKING : COMMANDER; + return c.talking ? TALKING : IDLE; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Complaint.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Complaint.java new file mode 100644 index 0000000..0524dca --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Complaint.java @@ -0,0 +1,35 @@ +package eu.lixko.ts3j.client.net; + +import java.util.Map; + +/** + * A complaint one client filed about another; the server keeps at most one per pair. + * + * @param targetDbId the database id of the client complained about + * @param fromDbId the database id of the client who complained + */ +public record Complaint(int targetDbId, String targetName, int fromDbId, String fromName, + String message, long timestampEpochSeconds) { + + /** Reads a complaint off a {@code notifycomplainlist} event's fields. */ + static Complaint from(Map fields) { + return new Complaint((int) parseLong(fields.get("tcldbid")), + orEmpty(fields.get("tname")), + (int) parseLong(fields.get("fcldbid")), + orEmpty(fields.get("fname")), + orEmpty(fields.get("message")), + parseLong(fields.get("timestamp"))); + } + + private static String orEmpty(String s) { + return s == null || s.equals("null") ? "" : s; + } + + private static long parseLong(String s) { + try { + return s == null ? 0 : Long.parseLong(s.trim()); + } catch (NumberFormatException e) { + return 0; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ComplaintAdmin.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ComplaintAdmin.java new file mode 100644 index 0000000..a347cdc --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ComplaintAdmin.java @@ -0,0 +1,79 @@ +package eu.lixko.ts3j.client.net; + +import com.github.manevolent.ts3j.command.CommandException; +import com.github.manevolent.ts3j.command.SingleCommand; +import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; +import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent; +import com.github.manevolent.ts3j.protocol.ProtocolRole; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * The server's complaints: filing, listing and removing them. + * + *

    Split out of {@link TeamspeakConnection} like {@link BanAdmin}, and answered the same + * way: {@code complainlist} replies with {@code notifycomplainlist} events ahead of the + * command's own completion. Every call here blocks and must run off the UI thread; the + * connection's public wrappers do that. + */ +final class ComplaintAdmin { + + /** What {@code complainlist} answers when there are no complaints at all. */ + private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501; + /** What {@code complainadd} answers when we already complained about that client. */ + private static final int ERROR_DATABASE_DUPLICATE_ENTRY = 0x0502; + + private final TeamspeakConnection conn; + + /** The {@code complainlist} reply in progress; one request may be in flight at a time. */ + private volatile List listing; + + ComplaintAdmin(TeamspeakConnection conn) { + this.conn = conn; + } + + List list() throws Exception { + List complaints = Collections.synchronizedList(new ArrayList<>()); + listing = complaints; + try { + conn.socket().executeCommand(new SingleCommand("complainlist", ProtocolRole.CLIENT)).complete(); + conn.awaitEventsProcessed(); + } catch (CommandException e) { + if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e; + } finally { + listing = null; + } + return new ArrayList<>(complaints); + } + + void onListEntry(UnknownTeamspeakEvent e) { + List complaints = listing; + if (complaints != null) complaints.add(Complaint.from(e.getMap())); + } + + /** Files a complaint about a client; the server takes one per client from each of us. */ + void add(int targetDbId, String message) throws Exception { + try { + conn.socket().executeCommand(new SingleCommand("complainadd", ProtocolRole.CLIENT, + new CommandSingleParameter("tcldbid", Integer.toString(targetDbId)), + new CommandSingleParameter("message", message))).complete(); + } catch (CommandException e) { + if (e.getErrorId() != ERROR_DATABASE_DUPLICATE_ENTRY) throw e; + throw new IllegalStateException("Cannot add multiple complaints about the same client."); + } + } + + void delete(Complaint complaint) throws Exception { + conn.socket().executeCommand(new SingleCommand("complaindel", ProtocolRole.CLIENT, + new CommandSingleParameter("tcldbid", Integer.toString(complaint.targetDbId())), + new CommandSingleParameter("fcldbid", Integer.toString(complaint.fromDbId())))).complete(); + } + + /** Removes every complaint about one client. */ + void deleteAll(int targetDbId) throws Exception { + conn.socket().executeCommand(new SingleCommand("complaindelall", ProtocolRole.CLIENT, + new CommandSingleParameter("tcldbid", Integer.toString(targetDbId)))).complete(); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionEventHandler.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionEventHandler.java new file mode 100644 index 0000000..59ded4d --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionEventHandler.java @@ -0,0 +1,743 @@ +package eu.lixko.ts3j.client.net; + +import com.github.manevolent.ts3j.event.*; +import com.github.manevolent.ts3j.api.TextMessageTargetMode; +import eu.lixko.ts3j.client.contacts.Contact; +import eu.lixko.ts3j.client.sound.SoundEvent; +import eu.lixko.ts3j.client.sound.SoundNotifier; + +import java.util.Map; + +/** + * The {@link TS3Listener} side of a connection: keeps {@link ServerModel} in sync with + * incoming notify events, mirrors native TeamSpeak's server-tab log lines, and picks the + * matching {@link SoundEvent} for each one. Registered alongside {@link TeamspeakConnection} + * itself (which keeps only the lifecycle-critical {@code onDisconnected} callback) so this + * class can stay focused on "event arrived, update state and tell the user" and nothing else. + */ +final class ConnectionEventHandler implements TS3Listener { + + // ---- who went where: TeamSpeak's reason ids ---- + + /** {@code reasonid} of a client view/move notification. */ + private static final int REASON_SWITCHED = 0; + private static final int REASON_MOVED = 1; + private static final int REASON_TIMEOUT = 3; + private static final int REASON_CHANNEL_KICK = 4; + private static final int REASON_SERVER_KICK = 5; + private static final int REASON_BAN = 6; + + private final TeamspeakConnection conn; + + ConnectionEventHandler(TeamspeakConnection conn) { + this.conn = conn; + } + + @Override + public void onClientJoin(ClientJoinEvent e) { + ClientEntry c = conn.getModel().putClient(e.getClientId(), e.getClientNickname(), e.getClientTargetId()); + c.type = safeInt(e, "client_type"); + c.talkPower = e.getClientTalkPower(); + c.talkRequest = talkRequested(e); + c.phoneticNickname = TeamspeakConnection.orEmpty(e.get("client_nickname_phonetic")); + c.inputMuted = e.isClientInputMuted(); + c.outputMuted = e.isClientOutputMuted(); + c.inputHardware = e.isClientUsingHardwareInput(); + c.outputHardware = e.isClientUsingHardwareOutput(); + c.away = e.isClientAway(); + c.awayMessage = TeamspeakConnection.orEmpty(e.get("client_away_message")); + c.uniqueId = TeamspeakConnection.orEmpty(e.getUniqueClientIdentifier()); + c.avatarFlag = TeamspeakConnection.orEmpty(e.get("client_flag_avatar")); + c.country = TeamspeakConnection.orEmpty(e.get("client_country")); + c.databaseId = e.getClientDatabaseId(); + c.serverGroupIds = parseIntList(e.getClientServerGroups()); + c.channelGroupId = e.getClientChannelGroupId(); + c.unreadMessages = safeInt(e, "client_unread_messages"); + c.self = (e.getClientId() == conn.getSelfClientId()); + // Query clients stay out of sight, as they do in the tree and in TS3's log. + if (!c.self && !c.isQuery()) { + conn.applyContact(c); + announceClientEntered(e); + logClientEntered(e); + } + conn.ui.onModelChanged(); + } + + @Override + public void onClientLeave(ClientLeaveEvent e) { + ClientEntry gone = conn.getModel().getClient(e.getClientId()); + if (e.getClientId() == conn.getSelfClientId()) { + announceOwnRemoval(safeInt(e, "reasonid"), e); + } else if (gone == null || !gone.isQuery()) { + String name = conn.clientLink(e.getClientId()); + announceClientLeft(e); + logClientLeft(e, name); + } + conn.getModel().removeClient(e.getClientId()); + if (conn.getPlayback() != null) conn.getPlayback().removeClient(e.getClientId()); + conn.ui.onModelChanged(); + } + + @Override + public void onClientMoved(ClientMovedEvent e) { + ClientEntry c = conn.getModel().getClient(e.getClientId()); + if (c != null) { + int from = c.channelId; + c.channelId = e.getTargetChannelId(); + if (e.getClientId() == conn.getSelfClientId()) { + conn.getModel().enteredChannel(e.getTargetChannelId()); + announceOwnMove(safeInt(e, "reasonid"), e); + logOwnMove(e, from, e.getTargetChannelId()); + } else if (!c.isQuery()) { + announceClientMoved(safeInt(e, "reasonid"), e.getClientId(), from, e.getTargetChannelId()); + logClientMoved(e, conn.clientLink(c.id), from, e.getTargetChannelId()); + } + conn.ui.onModelChanged(); + } + } + + /** A client became visible to us, logged the way native TS3's server tab does. */ + private void logClientEntered(ClientJoinEvent e) { + String name = conn.clientLink(e.getClientId(), + TeamspeakConnection.orEmpty(e.getUniqueClientIdentifier()), e.getClientNickname()); + // A client connecting also comes with "switched", only from no channel at all. + int reason = safeInt(e, "reasonid"); + if (reason == REASON_SWITCHED && e.getClientFromId() == 0) reason = -1; + switch (reason) { + case REASON_MOVED: + conn.log(name + " appears, coming from channel \"" + conn.channelLink(e.getClientFromId()) + "\""); + break; + case REASON_CHANNEL_KICK: + conn.log(name + " appears, was kicked from channel \"" + conn.channelLink(e.getClientFromId()) + + "\" by " + invokerName(e)); + break; + case REASON_SWITCHED: + conn.log(name + " switched to channel \"" + conn.channelLink(e.getClientTargetId()) + + "\", coming from channel \"" + conn.channelLink(e.getClientFromId()) + "\""); + break; + default: + conn.log(name + " connected to channel \"" + conn.channelLink(e.getClientTargetId()) + "\""); + } + } + + /** A client stopped being visible to us. */ + private void logClientLeft(ClientLeaveEvent e, String name) { + String reasonMsg = TeamspeakConnection.orEmpty(e.get("reasonmsg")); + String suffix = reasonMsg.isEmpty() ? "" : " (" + reasonMsg + ")"; + int reason = safeInt(e, "reasonid"); + // A client leaving the server may also come with "switched", only to no channel at all. + if (reason == REASON_SWITCHED && e.getClientTargetId() == 0) reason = -1; + switch (reason) { + case REASON_TIMEOUT: + conn.log(name + " dropped (ping timeout)"); + break; + case REASON_SERVER_KICK: + conn.log(name + " was kicked from the server by " + invokerName(e) + suffix); + break; + case REASON_BAN: + conn.log(name + " was banned from the server by " + invokerName(e) + suffix); + break; + case REASON_CHANNEL_KICK: + conn.log(name + " left: was kicked to channel \"" + conn.channelLink(e.getClientTargetId()) + + "\" by " + invokerName(e) + suffix); + break; + case REASON_MOVED: + conn.log(name + " left, heading to channel \"" + conn.channelLink(e.getClientTargetId()) + "\""); + break; + case REASON_SWITCHED: + conn.log(name + " left, switched to channel \"" + conn.channelLink(e.getClientTargetId()) + "\""); + break; + default: + conn.log(name + " disconnected"); + } + } + + /** A client we can see moved between two channels we can see. */ + private void logClientMoved(ClientMovedEvent e, String name, int fromChannel, int toChannel) { + String reasonMsg = TeamspeakConnection.orEmpty(e.get("reasonmsg")); + String suffix = reasonMsg.isEmpty() ? "" : " (" + reasonMsg + ")"; + switch (safeInt(e, "reasonid")) { + case REASON_MOVED: + conn.log(name + " was moved from channel \"" + conn.channelLink(fromChannel) + "\" to \"" + + conn.channelLink(toChannel) + "\" by " + invokerName(e)); + break; + case REASON_CHANNEL_KICK: + conn.log(name + " was kicked from channel \"" + conn.channelLink(fromChannel) + "\" to \"" + + conn.channelLink(toChannel) + "\" by " + invokerName(e) + suffix); + break; + default: + conn.log(name + " switched from channel \"" + conn.channelLink(fromChannel) + "\" to \"" + + conn.channelLink(toChannel) + "\""); + } + } + + /** Our own move between channels, logged the way TS3 does for everyone else. */ + private void logOwnMove(ClientMovedEvent e, int fromChannel, int toChannel) { + String reasonMsg = TeamspeakConnection.orEmpty(e.get("reasonmsg")); + String suffix = reasonMsg.isEmpty() ? "" : " (" + reasonMsg + ")"; + switch (safeInt(e, "reasonid")) { + case REASON_MOVED: + conn.log("You were moved from channel \"" + conn.channelLink(fromChannel) + "\" to \"" + + conn.channelLink(toChannel) + "\" by " + invokerName(e)); + break; + case REASON_CHANNEL_KICK: + conn.log("You were kicked from channel \"" + conn.channelLink(fromChannel) + "\" to \"" + + conn.channelLink(toChannel) + "\" by " + invokerName(e) + suffix); + break; + default: + conn.log("You switched from channel \"" + conn.channelLink(fromChannel) + "\" to \"" + + conn.channelLink(toChannel) + "\""); + } + } + + /** + * A client became visible: either they just connected, or they moved in from a + * channel we could not see — TeamSpeak's "appears" case. + */ + private void announceClientEntered(ClientJoinEvent e) { + if (!conn.isConnected()) return; + int clientId = e.getClientId(); + boolean current = conn.inOwnChannel(e.getClientTargetId()); + Map vars = conn.clientVars(clientId, e.getClientNickname()); + switch (safeInt(e, "reasonid")) { + case REASON_MOVED: + conn.sound(current ? SoundEvent.CLIENT_MOVED_TO_CURRENT_CHANNEL_APPEARS + : SoundEvent.CLIENT_MOVED_TO_OTHER_CHANNEL_APPEARS, vars); + break; + case REASON_CHANNEL_KICK: + conn.sound(current ? SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_TO_CURRENT_CHANNEL_APPEARS + : SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_TO_OTHER_CHANNEL_APPEARS, vars); + break; + case REASON_SWITCHED: + conn.sound(current ? SoundEvent.CLIENT_SWITCHED_TO_CURRENT_CHANNEL_APPEARS + : SoundEvent.CLIENT_SWITCHED_TO_OTHER_CHANNEL_APPEARS, vars); + break; + default: + conn.sound(current ? SoundEvent.CLIENT_CONNECTION_CONNECTED_CURRENT_CHANNEL + : SoundEvent.CLIENT_CONNECTION_CONNECTED_SERVER, vars); + } + } + + /** A client stopped being visible: they left the server, or moved out of sight. */ + private void announceClientLeft(ClientLeaveEvent e) { + if (!conn.isConnected()) return; + int clientId = e.getClientId(); + boolean current = conn.inOwnChannel(e.getClientFromId()); + Map vars = conn.clientVars(clientId, null); + switch (safeInt(e, "reasonid")) { + case REASON_TIMEOUT: + conn.sound(current ? SoundEvent.CLIENT_CONNECTION_LOST_CONNECTION_CURRENT_CHANNEL + : SoundEvent.CLIENT_CONNECTION_LOST_CONNECTION_SERVER, vars); + break; + case REASON_SERVER_KICK: + conn.sound(current ? SoundEvent.CLIENT_WAS_KICKED_FROM_SERVER_CURRENT_CHANNEL + : SoundEvent.CLIENT_WAS_KICKED_FROM_SERVER_SERVER, vars); + break; + case REASON_BAN: + conn.sound(current ? SoundEvent.CLIENT_WAS_BANNED_CURRENT_CHANNEL + : SoundEvent.CLIENT_WAS_BANNED_SERVER, vars); + break; + case REASON_CHANNEL_KICK: + conn.sound(current ? SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_FROM_CURRENT_CHANNEL_DISAPPEARS + : SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_TO_OTHER_CHANNEL_DISAPPEARS, vars); + break; + case REASON_MOVED: + conn.sound(current ? SoundEvent.CLIENT_MOVED_FROM_CURRENT_CHANNEL_DISAPPEARS + : SoundEvent.CLIENT_MOVED_TO_OTHER_CHANNEL_DISAPPEARS, vars); + break; + case REASON_SWITCHED: + conn.sound(current ? SoundEvent.CLIENT_SWITCHED_FROM_CURRENT_CHANNEL_DISAPPEARS + : SoundEvent.CLIENT_SWITCHED_TO_OTHER_CHANNEL_DISAPPEARS, vars); + break; + default: + conn.sound(current ? SoundEvent.CLIENT_CONNECTION_DISCONNECTED_CURRENT_CHANNEL + : SoundEvent.CLIENT_CONNECTION_DISCONNECTED_SERVER, vars); + } + } + + /** A client we can see moved between two channels we can see ("stays"). */ + private void announceClientMoved(int reason, int clientId, int fromChannel, int toChannel) { + if (!conn.isConnected()) return; + boolean toCurrent = conn.inOwnChannel(toChannel); + boolean fromCurrent = conn.inOwnChannel(fromChannel); + Map vars = conn.clientVars(clientId, null); + switch (reason) { + case REASON_MOVED: + conn.sound(toCurrent ? SoundEvent.CLIENT_MOVED_TO_CURRENT_CHANNEL_STAYS + : fromCurrent ? SoundEvent.CLIENT_MOVED_FROM_CURRENT_CHANNEL_STAYS + : SoundEvent.CLIENT_MOVED_TO_OTHER_CHANNEL_STAYS, vars); + break; + case REASON_CHANNEL_KICK: + conn.sound(toCurrent ? SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_TO_CURRENT_CHANNEL_STAYS + : fromCurrent ? SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_FROM_CURRENT_CHANNEL_STAYS + : SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_TO_OTHER_CHANNEL_STAYS, vars); + break; + default: + conn.sound(toCurrent ? SoundEvent.CLIENT_SWITCHED_TO_CURRENT_CHANNEL_STAYS + : fromCurrent ? SoundEvent.CLIENT_SWITCHED_FROM_CURRENT_CHANNEL_STAYS + : SoundEvent.CLIENT_SWITCHED_TO_OTHER_CHANNEL_STAYS, vars); + } + } + + /** We changed channel ourselves, or somebody changed it for us. */ + private void announceOwnMove(int reason, ClientMovedEvent e) { + if (!conn.isConnected()) return; + Map vars = conn.channelVars(e.getTargetChannelId(), e.get("invokername")); + switch (reason) { + case REASON_MOVED: + conn.sound(SoundEvent.YOU_WERE_MOVED_TO_DIFFERENT_CHANNEL, vars); + break; + case REASON_CHANNEL_KICK: + conn.sound(SoundEvent.YOU_WERE_KICKED_FROM_CHANNEL, vars); + break; + default: + conn.sound(SoundEvent.YOU_SWITCHED_CHANNEL, vars); + } + } + + /** We were removed from the server (kick or ban); the disconnect follows. */ + private void announceOwnRemoval(int reason, ClientLeaveEvent e) { + if (!conn.isConnected()) return; + Map vars = SoundNotifier.vars( + "servername", conn.getModel().getServerName(), + "clientname", TeamspeakConnection.orEmpty(e.get("invokername")), + "reason", TeamspeakConnection.orEmpty(e.get("reasonmsg"))); + if (reason == REASON_SERVER_KICK) { + conn.sound(SoundEvent.YOU_WERE_KICKED_FROM_SERVER, vars); + } else if (reason == REASON_BAN) { + conn.sound(SoundEvent.YOU_WERE_BANNED, vars); + } + } + + @Override + public void onClientChanged(ClientUpdatedEvent e) { + ClientEntry c = conn.getModel().getClient(e.getClientId()); + if (c == null) return; + boolean renamed = has(e, "client_nickname") && !e.get("client_nickname").equals(c.nickname); + String oldName = c.nickname; + if (renamed) c.nickname = e.get("client_nickname"); + if (has(e, "client_input_muted")) c.inputMuted = e.getBoolean("client_input_muted"); + if (has(e, "client_output_muted")) c.outputMuted = e.getBoolean("client_output_muted"); + if (has(e, "client_input_hardware")) c.inputHardware = e.getBoolean("client_input_hardware"); + if (has(e, "client_output_hardware")) c.outputHardware = e.getBoolean("client_output_hardware"); + if (has(e, "client_away")) { + c.away = e.getBoolean("client_away"); + // Both fields travel together, so an absent message here means "no message" + // — which `has` cannot tell from "not reported". + c.awayMessage = c.away ? TeamspeakConnection.orEmpty(e.get("client_away_message")) : ""; + } else if (reported(e, "client_away_message")) { + c.awayMessage = TeamspeakConnection.orEmpty(e.get("client_away_message")); + } + if (has(e, "client_talk_power")) c.talkPower = e.getInt("client_talk_power"); + if (has(e, "client_talk_request")) c.talkRequest = talkRequested(e); + if (reported(e, "client_nickname_phonetic")) { + c.phoneticNickname = TeamspeakConnection.orEmpty(e.get("client_nickname_phonetic")); + } + if (reported(e, "client_description")) { + c.description = TeamspeakConnection.orEmpty(e.get("client_description")); + conn.ui.onInfoUpdated(); + } + // The answer to clientgetvariables. + if (has(e, "client_version") || has(e, "client_platform")) { + if (has(e, "client_version")) c.version = e.get("client_version"); + if (has(e, "client_platform")) c.platform = e.get("client_platform"); + conn.ui.onInfoUpdated(); + } + if (has(e, "client_month_bytes_downloaded")) + c.monthBytesDownloaded = TeamspeakConnection.safeLong(e, "client_month_bytes_downloaded"); + if (has(e, "client_month_bytes_uploaded")) + c.monthBytesUploaded = TeamspeakConnection.safeLong(e, "client_month_bytes_uploaded"); + if (has(e, "client_is_channel_commander")) + c.channelCommander = e.getBoolean("client_is_channel_commander"); + if (reported(e, "client_flag_avatar")) c.avatarFlag = TeamspeakConnection.orEmpty(e.get("client_flag_avatar")); + if (reported(e, "client_country")) c.country = TeamspeakConnection.orEmpty(e.get("client_country")); + if (has(e, "client_unread_messages")) { + int before = c.unreadMessages; + c.unreadMessages = safeInt(e, "client_unread_messages"); + if (c.id == conn.getSelfClientId()) conn.unreadMessagesChanged(before); + } + announceClientUpdate(e, c, renamed, oldName); + conn.ui.onModelChanged(); + } + + /** Renames, talk-power changes and recording flags all arrive as a client update. */ + private void announceClientUpdate(ClientUpdatedEvent e, ClientEntry c, boolean renamed, String oldName) { + if (!conn.isConnected()) return; + boolean self = c.id == conn.getSelfClientId(); + Map vars = conn.clientVars(c.id, null); + + if (renamed) { + conn.sound(safeInt(e, "invokerid") == conn.getSelfClientId() + ? SoundEvent.CLIENT_RENAMED_BY_YOU : SoundEvent.CLIENT_RENAMED_BY_OTHER, vars); + conn.log(oldName + " is now known as " + conn.clientLink(c.id)); + } + if (has(e, "client_talk_request") && talkRequested(e) && !self) { + conn.sound(SoundEvent.CLIENT_REQUESTED_TALK_POWER, vars); + } + if (self && has(e, "client_is_talker")) { + conn.sound(e.getBoolean("client_is_talker") + ? SoundEvent.YOU_WERE_GRANTED_TALK_POWER : SoundEvent.YOU_WERE_REVOKED_TALK_POWER, vars); + } + if (!self && has(e, "client_is_recording")) { + boolean recording = e.getBoolean("client_is_recording"); + if (!recording) { + conn.sound(SoundEvent.CLIENT_RECORDING_STOP, vars); + } else { + conn.sound(conn.inOwnChannel(c.channelId) + ? SoundEvent.CLIENT_RECORDING_IN_CHANNEL : SoundEvent.CLIENT_RECORDING_START, vars); + } + } + } + + @Override + public void onChannelCreate(ChannelCreateEvent e) { + int cid = e.getChannelId(); + int pid = safeInt(e, "cpid"); + if (pid == 0) pid = safeInt(e, "pid"); + int order = safeInt(e, "channel_order"); + ChannelNode node = conn.getModel().putChannel(cid, e.get("channel_name"), pid, order); + applyChannelProperties(node, e); + conn.getModel().relinkChannel(cid, pid, order); + if (conn.isConnected()) { + conn.sound(byInvoker(e, SoundEvent.CHANNEL_CREATED_BY_YOU, SoundEvent.CHANNEL_CREATED_BY_OTHER, + SoundEvent.CHANNEL_CREATED_BY_OTHER), conn.channelVars(cid, e.get("invokername"))); + conn.log("Channel \"" + conn.channelLink(cid) + "\" was created by " + invokerName(e)); + } + conn.ui.onModelChanged(); + } + + @Override + public void onChannelDeleted(ChannelDeletedEvent e) { + int cid = e.getChannelId(); + if (conn.isConnected()) { + conn.sound(byInvoker(e, SoundEvent.CHANNEL_DELETED_BY_YOU, SoundEvent.CHANNEL_DELETED_BY_OTHER, + SoundEvent.CHANNEL_DELETED_BY_SERVER), conn.channelVars(cid, e.get("invokername"))); + conn.log("Channel \"" + conn.channelName(cid) + "\" was deleted by " + invokerName(e)); + } + conn.getModel().removeChannel(cid); + conn.ui.onModelChanged(); + } + + @Override + public void onChannelEdit(ChannelEditedEvent e) { + ChannelNode ch = conn.getModel().getChannel(safeInt(e, "cid")); + if (ch == null) return; + // The answer to channelgetdescription; an empty description comes as a bare key. + if (reported(e, "channel_description")) { + ch.description = TeamspeakConnection.orEmpty(e.get("channel_description")); + ch.descriptionLoaded = true; + conn.ui.onInfoUpdated(); + } + // That answer has no invoker: nothing was edited. + if (!e.getMap().containsKey("invokerid")) return; + applyChannelProperties(ch, e); + // Sorting among the same siblings arrives here too, and TS3 announces it as an edit. + if (has(e, "channel_order")) conn.getModel().relinkChannel(ch.id, ch.parentId, e.getInt("channel_order")); + if (conn.isConnected()) { + boolean current = conn.inOwnChannel(ch.id); + conn.sound(current + ? byInvoker(e, SoundEvent.CHANNEL_EDITED_CURRENT_BY_YOU, + SoundEvent.CHANNEL_EDITED_CURRENT_BY_OTHER, SoundEvent.CHANNEL_EDITED_CURRENT_BY_OTHER) + : byInvoker(e, SoundEvent.CHANNEL_EDITED_OTHER_BY_YOU, + SoundEvent.CHANNEL_EDITED_OTHER_BY_OTHER, SoundEvent.CHANNEL_EDITED_OTHER_BY_SERVER), + conn.channelVars(ch.id, e.get("invokername"))); + conn.log("Channel \"" + conn.channelLink(ch.id) + "\" was edited by " + invokerName(e)); + } + conn.ui.onModelChanged(); + } + + /** The properties a channel event carries that the model keeps; each only when present. */ + private static void applyChannelProperties(ChannelNode ch, BaseEvent e) { + if (has(e, "channel_name")) ch.name = e.get("channel_name"); + // An emptied topic arrives as a bare key, which has() would skip. + if (reported(e, "channel_topic")) ch.topic = TeamspeakConnection.orEmpty(e.get("channel_topic")); + if (has(e, "channel_icon_id")) ch.iconId = TeamspeakConnection.safeLong(e, "channel_icon_id"); + if (has(e, "channel_flag_password")) ch.hasPassword = e.getBoolean("channel_flag_password"); + if (has(e, "channel_flag_permanent")) ch.permanent = e.getBoolean("channel_flag_permanent"); + if (has(e, "channel_flag_maxclients_unlimited") && e.getBoolean("channel_flag_maxclients_unlimited")) { + ch.maxClients = -1; + } else if (has(e, "channel_maxclients")) { + ch.maxClients = safeInt(e, "channel_maxclients"); + } + } + + /** + * Descriptions never travel with the notify, so a cached one has to be re-fetched. + * Only channels whose description was already loaded are refreshed; the rest pick the + * new text up the first time they are looked at. + */ + @Override + public void onChannelDescriptionChanged(ChannelDescriptionEditedEvent e) { + ChannelNode ch = conn.getModel().getChannel(safeInt(e, "cid")); + if (ch == null || !ch.descriptionLoaded) return; + ch.descriptionLoaded = false; + conn.requestChannelInfo(ch.id); + } + + @Override + public void onChannelMoved(ChannelMovedEvent e) { + ChannelNode ch = conn.getModel().getChannel(safeInt(e, "cid")); + if (ch == null) return; + int parent = has(e, "cpid") ? e.getInt("cpid") : ch.parentId; + int order = has(e, "order") ? e.getInt("order") : ch.order; + conn.getModel().relinkChannel(ch.id, parent, order); + if (conn.isConnected()) { + conn.sound(byInvoker(e, SoundEvent.CHANNEL_MOVED_BY_YOU, SoundEvent.CHANNEL_MOVED_BY_OTHER, + SoundEvent.CHANNEL_MOVED_BY_OTHER), conn.channelVars(ch.id, e.get("invokername"))); + String newParent = parent == 0 ? conn.getModel().getServerName() : conn.channelLink(parent); + conn.log("Channel \"" + conn.channelLink(ch.id) + "\" was moved by " + invokerName(e) + + ", new parent channel is \"" + newParent + "\""); + } + conn.ui.onModelChanged(); + } + + @Override + public void onChannelSubscribed(ChannelSubscribedEvent e) { + setSubscribed(safeInt(e, "cid"), true); + } + + @Override + public void onChannelUnsubscribed(ChannelUnsubscribedEvent e) { + setSubscribed(safeInt(e, "cid"), false); + } + + private void setSubscribed(int cid, boolean subscribed) { + ChannelNode ch = conn.getModel().getChannel(cid); + if (ch == null || ch.subscribed == subscribed) return; + ch.subscribed = subscribed; + conn.ui.onModelChanged(); + } + + @Override + public void onServerEdit(ServerEditedEvent e) { + if (has(e, "virtualserver_name")) conn.getModel().setServerName(e.get("virtualserver_name")); + conn.getModel().putServerProperties(e.getMap()); + if (conn.isConnected()) { + conn.sound(byInvoker(e, SoundEvent.SERVER_EDITED_BY_YOU, SoundEvent.SERVER_EDITED_BY_OTHER, + SoundEvent.SERVER_EDITED_BY_OTHER), conn.serverVars()); + } + conn.ui.onModelChanged(); + } + + @Override + public void onServerGroupClientAdded(ServerGroupClientAddedEvent e) { + ClientEntry c = conn.getModel().getClient(e.getClientId()); + if (c != null) c.addServerGroup(e.getServerGroupId()); + boolean self = e.getClientId() == conn.getSelfClientId(); + if (self) conn.requestSelfPowers(); + conn.sound(self + ? byInvoker(e, SoundEvent.YOU_SERVERGROUP_ADDED_BY_USER, SoundEvent.YOU_SERVERGROUP_ADDED_BY_USER, + SoundEvent.YOU_SERVERGROUP_ADDED_BY_SERVER) + : byInvoker(e, SoundEvent.CLIENT_SERVERGROUP_ADDED_BY_USER, + SoundEvent.CLIENT_SERVERGROUP_ADDED_BY_USER, SoundEvent.CLIENT_SERVERGROUP_ADDED_BY_SERVER), + groupVars(e.getClientId(), serverGroupName(e.getServerGroupId()))); + conn.log(clientLogName(e.getClientId()) + " was added to server group \"" + serverGroupName(e.getServerGroupId()) + + "\" by " + invokerName(e) + "."); + conn.ui.onModelChanged(); + } + + @Override + public void onServerGroupClientDeleted(ServerGroupClientDeletedEvent e) { + int clientId = safeInt(e, "clid"); + ClientEntry c = conn.getModel().getClient(clientId); + if (c != null) c.removeServerGroup(e.getServerGroupId()); + boolean self = clientId == conn.getSelfClientId(); + if (self) conn.requestSelfPowers(); + conn.sound(self + ? byInvoker(e, SoundEvent.YOU_SERVERGROUP_REMOVED_BY_USER, + SoundEvent.YOU_SERVERGROUP_REMOVED_BY_USER, SoundEvent.YOU_SERVERGROUP_REMOVED_BY_SERVER) + : byInvoker(e, SoundEvent.CLIENT_SERVERGROUP_REMOVED_BY_USER, + SoundEvent.CLIENT_SERVERGROUP_REMOVED_BY_USER, SoundEvent.CLIENT_SERVERGROUP_REMOVED_BY_SERVER), + groupVars(clientId, serverGroupName(e.getServerGroupId()))); + conn.log(clientLogName(clientId) + " was removed from server group \"" + serverGroupName(e.getServerGroupId()) + + "\" by " + invokerName(e) + "."); + conn.ui.onModelChanged(); + } + + @Override + public void onClientChannelGroupChanged(ClientChannelGroupChangedEvent e) { + ClientEntry c = conn.getModel().getClient(e.getClientId()); + if (c != null) c.channelGroupId = e.getChannelGroupId(); + boolean self = e.getClientId() == conn.getSelfClientId(); + if (self) conn.requestSelfPowers(); + String groupName = conn.getModel().channelGroupName(e.getChannelGroupId()); + conn.sound(self + ? byInvoker(e, SoundEvent.YOU_CHANNELGROUP_CHANGED_BY_USER, + SoundEvent.YOU_CHANNELGROUP_CHANGED_BY_USER, SoundEvent.YOU_CHANNELGROUP_CHANGED_BY_SERVER) + : byInvoker(e, SoundEvent.CLIENT_CHANNELGROUP_CHANGED_BY_USER, + SoundEvent.CLIENT_CHANNELGROUP_CHANGED_BY_USER, SoundEvent.CLIENT_CHANNELGROUP_CHANGED_BY_SERVER), + groupVars(e.getClientId(), groupName)); + conn.log("Channel group \"" + TeamspeakConnection.orEmpty(groupName) + "\" was assigned to " + + clientLogName(e.getClientId()) + " by " + invokerName(e) + "."); + conn.ui.onModelChanged(); + } + + /** + * The group's own name. The notify's {@code name} field is misleading: TeamSpeak fills + * it with the client's nickname, not the group's. + */ + private String serverGroupName(int groupId) { + Group g = conn.getModel().serverGroup(groupId); + return g != null ? g.name : "#" + groupId; + } + + /** A client's name for a log line, as a link, falling back to its id once it has left. */ + private String clientLogName(int clientId) { + return conn.clientLink(clientId); + } + + /** Picks the event variant matching who caused the change: us, another client, or the server. */ + private SoundEvent byInvoker(BaseEvent e, SoundEvent byYou, SoundEvent byOther, SoundEvent byServer) { + int invoker = safeInt(e, "invokerid"); + if (invoker == conn.getSelfClientId() && invoker != 0) return byYou; + return invoker == 0 ? byServer : byOther; + } + + private Map groupVars(int clientId, String groupName) { + Map vars = conn.clientVars(clientId, null); + vars.put("groupname", TeamspeakConnection.orEmpty(groupName)); + return vars; + } + + @Override + public void onChannelList(ChannelListEvent e) { + // Incremental channel arriving during connect. + int cid = e.getChannelId(); + ChannelNode node = conn.getModel().putChannel(cid, e.get("channel_name"), + safeInt(e, "cpid"), safeInt(e, "channel_order")); + applyChannelProperties(node, e); + } + + @Override + public void onServerGroupList(ServerGroupListEvent e) { + int id = safeInt(e, "sgid"); + if (id > 0) conn.getModel().putServerGroup(toGroup(e, id)); + } + + @Override + public void onChannelGroupList(ChannelGroupListEvent e) { + int id = safeInt(e, "cgid"); + if (id > 0) conn.getModel().putChannelGroup(toGroup(e, id)); + } + + private static Group toGroup(BaseEvent e, int id) { + return new Group(id, e.get("name"), TeamspeakConnection.safeLong(e, "iconid"), safeInt(e, "sortid"), + safeInt(e, "type"), safeInt(e, "n_member_addp"), safeInt(e, "n_member_removep")); + } + + @Override + public void onPermissionList(PermissionListEvent e) { + conn.getModel().putPermissionName(e.get("permname")); + } + + @Override + public void onClientNeededPermissions(ClientNeededPermissionsEvent e) { + conn.getModel().putSelfPermissionValue(safeInt(e, "permid"), safeInt(e, "permvalue")); + } + + @Override + public void onTextMessage(TextMessageEvent e) { + if (e.getInvokerId() == conn.getSelfClientId()) return; // don't echo our own + Contact contact = conn.contacts.find(e.getInvokerUniqueId()); + if (contact != null) { + boolean isPrivate = e.getTargetMode() == TextMessageTargetMode.CLIENT; + if (isPrivate ? contact.ignorePrivateMessages : contact.ignorePublicMessages) return; + } + ConnectionListener.ChatScope scope; + SoundEvent notification; + switch (e.getTargetMode()) { + case CLIENT: + scope = ConnectionListener.ChatScope.PRIVATE; + notification = SoundEvent.CHAT_RECEIVED_MESSAGE_CLIENT; + break; + case CHANNEL: + scope = ConnectionListener.ChatScope.CHANNEL; + notification = SoundEvent.CHAT_RECEIVED_MESSAGE_CHANNEL; + break; + default: + scope = ConnectionListener.ChatScope.SERVER; + notification = SoundEvent.CHAT_RECEIVED_MESSAGE_SERVER; + break; + } + conn.persistIncomingChat(scope, e.getInvokerId(), e.getInvokerUniqueId(), e.getInvokerName(), e.getMessage()); + conn.sound(notification, conn.clientVars(e.getInvokerId(), e.getInvokerName())); + conn.ui.onChat(scope, e.getInvokerId(), e.getInvokerUniqueId(), e.getInvokerName(), e.getMessage()); + } + + @Override + public void onClientPoke(ClientPokeEvent e) { + Contact contact = conn.contacts.find(e.getInvokerUniqueId()); + if (contact != null && contact.ignorePokes) return; + conn.sound(SoundEvent.OTHER_RECEIVED_POKE, conn.clientVars(e.getInvokerId(), e.getInvokerName())); + String from = conn.contacts.displayName(e.getInvokerUniqueId(), TeamspeakConnection.orEmpty(e.getInvokerName())); + conn.ui.onPoke(from, TeamspeakConnection.orEmpty(e.get("msg"))); + } + + @Override + public void onUnknownEvent(UnknownTeamspeakEvent e) { + if ("notifyconnectioninfo".equals(e.getCommand())) conn.stats.onReport(e); + else if ("notifychannelpermlist".equals(e.getCommand())) conn.channels.onPermListEntry(e); + else if ("notifybanlist".equals(e.getCommand())) conn.bans.onListEntry(e); + else if ("notifytokenlist".equals(e.getCommand())) conn.privilegeKeys.onListEntry(e); + else if ("notifytokenadd".equals(e.getCommand())) conn.privilegeKeys.onAdded(e); + else if ("notifycomplainlist".equals(e.getCommand())) conn.complaints.onListEntry(e); + else if ("notifyserverlog".equals(e.getCommand())) conn.serverLog.onLine(e); + else conn.offlineMessages.onReply(e); + } + + // ---- helpers ---- + + /** Who caused an event, linked where the server named them; "the server" when nobody did. */ + private String invokerName(BaseEvent e) { + String name = TeamspeakConnection.orEmpty(e.get("invokername")); + if (name.isEmpty()) return "the server"; + return conn.clientLink(safeInt(e, "invokerid"), + TeamspeakConnection.orEmpty(e.get("invokeruid")), name); + } + + /** {@code client_talk_request} holds the request's timestamp, or 0 when there is none. */ + private static boolean talkRequested(BaseEvent e) { + String v = e.get("client_talk_request"); + return v != null && !v.isBlank() && !v.trim().equals("0"); + } + + private static int safeInt(BaseEvent e, String key) { + try { + String v = e.get(key); + return v == null ? 0 : Integer.parseInt(v.trim()); + } catch (Exception ex) { + return 0; + } + } + + /** + * Whether the event actually carries a field. ts3j answers a missing key with an + * empty string rather than null, so a plain null check is always true — and a + * partial update (say, someone muting) would otherwise look like it reported + * every other field as well. + */ + private static boolean has(BaseEvent e, String key) { + String value = e.get(key); + return value != null && !value.isEmpty(); + } + + /** Whether the event carries a field at all, even empty: for text that can be cleared. */ + private static boolean reported(BaseEvent e, String key) { + return e.getMap().containsKey(key); + } + + /** Parses a comma-separated id list (e.g. server groups "6,12,15"). */ + private static int[] parseIntList(String csv) { + if (csv == null || csv.isEmpty()) return new int[0]; + String[] parts = csv.split(","); + int[] out = new int[parts.length]; + int n = 0; + for (String p : parts) { + try { + out[n++] = Integer.parseInt(p.trim()); + } catch (NumberFormatException ignored) { + } + } + return n == parts.length ? out : java.util.Arrays.copyOf(out, n); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionListener.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionListener.java new file mode 100644 index 0000000..3190991 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionListener.java @@ -0,0 +1,62 @@ +package eu.lixko.ts3j.client.net; + +import java.util.List; + +/** + * UI-facing callbacks fired by {@link TeamspeakConnection}. Implementations are + * responsible for marshalling to the Swing EDT. + */ +public interface ConnectionListener { + + /** Message scope for chat display. */ + enum ChatScope {SERVER, CHANNEL, PRIVATE} + + void onStatus(String status); + + void onConnected(); + + void onDisconnected(String reason); + + /** The channel/client model changed and any tree view should be rebuilt. */ + void onModelChanged(); + + /** On-demand channel/client details finished loading; refresh any info view. */ + void onInfoUpdated(); + + /** A group icon finished downloading; repaint anything showing icons. */ + void onIconsUpdated(); + + void onChat(ChatScope scope, int fromClientId, String fromUniqueId, String fromName, String message); + + /** Previously persisted TS3 HTML log entries for one chat scope. */ + default void onChatHistory(ChatScope scope, List htmlEntries) { + } + + /** Previously persisted TS3 HTML log entries for a private chat. */ + default void onPrivateChatHistory(int clientId, String nickname, List htmlEntries) { + } + + /** A client (possibly the local one) started or stopped talking. */ + void onTalkStateChanged(int clientId, boolean talking); + + void onError(String message); + + /** Someone poked the local client. */ + void onPoke(String fromName, String message); + + /** + * Something happened on the server that native TS3 records in the server + * log: a client connecting/disconnecting/moving, a channel being edited, + * a group being (un)assigned, and so on. + */ + void onServerLog(String message); + + /** Our offline message inbox's unread count changed, or became known on connecting. */ + default void onUnreadMessagesChanged(int unread) { + } + + /** A server-log line already rendered in TS3's HTML log format. */ + default void onServerLogHtml(String html) { + onServerLog(html == null ? "" : html); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionStats.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionStats.java new file mode 100644 index 0000000..00cc497 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionStats.java @@ -0,0 +1,83 @@ +package eu.lixko.ts3j.client.net; + +import eu.lixko.ts3j.client.audio.VoiceReceiveStats; + +import java.util.EnumMap; +import java.util.Map; + +/** + * A snapshot of a client's connection statistics, as shown in the Connection + * Info window. Values default to {@code -1} meaning "unknown / not reported", + * which callers should render as a dash. + * + *

    Traffic is seen from the client's side, as TeamSpeak shows it: in is what + * the client received, out what it sent. For a remote client the figures come + * from {@code notifyconnectioninfo} (the server relays the client's own counters, plus + * the loss it measured itself); for the local client they are read from our own socket. + */ +public final class ConnectionStats { + + /** The three traffic categories TeamSpeak accounts separately. */ + public enum Kind {SPEECH, KEEPALIVE, CONTROL} + + /** A quota permission's value for "no limit". */ + public static final long UNLIMITED = -1; + + public int clientId; + public String nickname = ""; + public boolean self; + + /** Empty when the server withholds it. */ + public String ip = ""; + public int port = -1; + + public double pingMs = -1; + public double pingDeviationMs = -1; + public long connectedTimeMs = -1; + public long idleTimeMs = -1; + + public long filetransferBandwidthSent = -1; + public long filetransferBandwidthReceived = -1; + + public final Traffic total = new Traffic(); + private final Map perKind = new EnumMap<>(Kind.class); + + public long monthBytesDownloaded = -1; + public long monthBytesUploaded = -1; + /** Our own transfer quota in MiB, or {@link #UNLIMITED}; only known for ourselves. */ + public long downloadQuotaMb = UNLIMITED; + public long uploadQuotaMb = UNLIMITED; + + /** + * How voice has been coming in here, measured by this client's own playback: from this + * speaker, or for ourselves from everyone. {@code null} when nothing was heard. + */ + public VoiceReceiveStats voiceReceived; + + /** One category's figures, or {@link #total} for a null {@code kind}. */ + public Traffic traffic(Kind kind) { + return kind == null ? total : perKind.computeIfAbsent(kind, k -> new Traffic()); + } + + /** One direction pair of counters. Values default to {@code -1} meaning "unknown". */ + public static final class Traffic { + /** Fractions 0..1: server to client, and client to server. */ + public double lossIn = -1; + public double lossOut = -1; + public long packetsIn = -1; + public long packetsOut = -1; + public long bytesIn = -1; + public long bytesOut = -1; + public long bandwidthInLastSecond = -1; + public long bandwidthOutLastSecond = -1; + public long bandwidthInLastMinute = -1; + public long bandwidthOutLastMinute = -1; + + /** The chance a packet is lost either way, or whichever direction is known. */ + public double lossTotal() { + if (lossIn < 0) return lossOut; + if (lossOut < 0) return lossIn; + return 1 - (1 - lossIn) * (1 - lossOut); + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionStatsCollector.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionStatsCollector.java new file mode 100644 index 0000000..edbf5bd --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionStatsCollector.java @@ -0,0 +1,288 @@ +package eu.lixko.ts3j.client.net; + +import com.github.manevolent.ts3j.command.SingleCommand; +import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; +import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent; +import com.github.manevolent.ts3j.protocol.PacketKind; +import com.github.manevolent.ts3j.protocol.ProtocolRole; +import com.github.manevolent.ts3j.protocol.packet.statistics.PacketStatistics; +import com.github.manevolent.ts3j.protocol.socket.client.LocalTeamspeakClientSocket; +import com.github.manevolent.ts3j.util.Pair; +import eu.lixko.ts3j.client.audio.VoiceOutput; +import eu.lixko.ts3j.client.net.filetransfer.FileTransferManager; + +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + +/** + * Builds {@link ConnectionStats} snapshots for the info window from {@code getconnectioninfo}. + * + *

    For another client the server answers twice: at once with the figures it last + * heard, then again once the client has sent fresh ones ({@code setconnectioninfo}). + * For ourselves it answers once, with only what it measures itself (address, idle time, + * the loss on the way in); the traffic comes from our own socket's counters. + */ +final class ConnectionStatsCollector { + + private static final long REPORT_WAIT_MS = 1000; + /** {@code clientgetvariables} for the month's transfer figures, which change slowly. */ + private static final long VARIABLES_REFRESH_MS = 10_000; + + private final TeamspeakConnection conn; + + /** Requests awaiting their reports, keyed by client id. */ + private final Map pending = new ConcurrentHashMap<>(); + private final Map variablesAskedAt = new ConcurrentHashMap<>(); + /** The file transfer byte counts at the previous poll: time, sent, received. */ + private long[] lastTransferSample; + + ConnectionStatsCollector(TeamspeakConnection conn) { + this.conn = conn; + } + + /** Drops any requests left over from a connection that just went away. */ + void clear() { + pending.clear(); + variablesAskedAt.clear(); + lastTransferSample = null; + } + + /** + * Fetches a client's statistics and delivers them to {@code callback} exactly once, + * on a background thread. May be called repeatedly to poll. + */ + void request(int clientId, Consumer callback) { + new Thread(() -> callback.accept(collect(clientId)), "ts3j-conninfo").start(); + } + + /** Folds an arriving {@code notifyconnectioninfo} report into its request. */ + void onReport(UnknownTeamspeakEvent e) { + Pending p = pending.get(safeInt(e.get("clid"))); + if (p == null) return; + synchronized (p.stats) { + applyReport(p.stats, e.getMap()); + } + p.reports.countDown(); + } + + private ConnectionStats collect(int clientId) { + ConnectionStats s = new ConnectionStats(); + s.clientId = clientId; + s.self = clientId == conn.getSelfClientId(); + refreshVariables(clientId); + awaitReports(s, s.self ? 1 : 2); + + synchronized (s) { + if (s.self) { + applyLocal(s); + applyTransferRate(s); + } + sumKinds(s); + ClientEntry entry = conn.getModel().getClient(clientId); + if (entry != null) { + s.nickname = entry.nickname; + s.monthBytesDownloaded = entry.monthBytesDownloaded; + s.monthBytesUploaded = entry.monthBytesUploaded; + } + if (s.self) { + ServerModel model = conn.getModel(); + s.downloadQuotaMb = model.selfPermissionValue("i_ft_quota_mb_download_per_client", -1); + s.uploadQuotaMb = model.selfPermissionValue("i_ft_quota_mb_upload_per_client", -1); + } + VoiceOutput playback = conn.getPlayback(); + if (playback != null) { + s.voiceReceived = s.self ? playback.receiveStats() : playback.receiveStats(clientId); + } + } + return s; + } + + private void awaitReports(ConnectionStats s, int expected) { + LocalTeamspeakClientSocket client = conn.client; + if (client == null) return; + Pending p = new Pending(s, expected); + pending.put(s.clientId, p); + try { + client.executeCommand(new SingleCommand("getconnectioninfo", ProtocolRole.CLIENT, + new CommandSingleParameter("clid", Integer.toString(s.clientId)))).complete(); + p.reports.await(REPORT_WAIT_MS, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (Exception ignored) { + // refused (e.g. no permission to view it); what is known locally still shows + } finally { + pending.remove(s.clientId, p); + } + } + + /** Asks for the month's transfer figures now and then; they land in the model. */ + private void refreshVariables(int clientId) { + long now = System.currentTimeMillis(); + Long last = variablesAskedAt.get(clientId); + if (last != null && now - last < VARIABLES_REFRESH_MS) return; + variablesAskedAt.put(clientId, now); + conn.requestClientInfo(clientId); + } + + /** Our own traffic, straight from the socket. */ + private void applyLocal(ConnectionStats s) { + long connectedAt = conn.connectedAtMs; + if (connectedAt > 0) s.connectedTimeMs = System.currentTimeMillis() - connectedAt; + + LocalTeamspeakClientSocket c = conn.client; + if (c == null) return; + try { + Pair ping = c.getPing(); + s.pingMs = ping.getKey() * 1000.0; + s.pingDeviationMs = ping.getValue() * 1000.0; + } catch (Exception ignored) { + // ping unavailable; leave as unknown + } + for (PacketKind kind : PacketKind.values()) { + PacketStatistics st = c.getStatistics(kind); + ConnectionStats.Traffic t = s.traffic(mapKind(kind)); + t.packetsIn = add(t.packetsIn, st.getReceivedPackets()); + t.packetsOut = add(t.packetsOut, st.getSentPackets()); + t.bytesIn = add(t.bytesIn, st.getReceivedBytes()); + t.bytesOut = add(t.bytesOut, st.getSentBytes()); + t.bandwidthInLastSecond = add(t.bandwidthInLastSecond, st.getReceivedBytesLastSecond()); + t.bandwidthOutLastSecond = add(t.bandwidthOutLastSecond, st.getSentBytesLastSecond()); + t.bandwidthInLastMinute = add(t.bandwidthInLastMinute, st.getReceivedBandwidthLastMinute()); + t.bandwidthOutLastMinute = add(t.bandwidthOutLastMinute, st.getSentBandwidthLastMinute()); + } + } + + /** Our file transfer rate since the previous poll; the server reports it only for others. */ + private synchronized void applyTransferRate(ConnectionStats s) { + FileTransferManager ft = conn.fileTransfers(); + if (ft == null) return; + long[] now = {System.currentTimeMillis(), ft.bytesSent(), ft.bytesReceived()}; + long[] last = lastTransferSample; + lastTransferSample = now; + long elapsed = last == null ? 0 : now[0] - last[0]; + s.filetransferBandwidthSent = elapsed <= 0 ? 0 : (now[1] - last[1]) * 1000 / elapsed; + s.filetransferBandwidthReceived = elapsed <= 0 ? 0 : (now[2] - last[2]) * 1000 / elapsed; + } + + /** Several of ts3j's packet kinds (commands and their acks) make up one TeamSpeak category. */ + private static long add(long current, long value) { + return Math.max(current, 0) + value; + } + + /** Fills the totals from the categories: clients report only those. */ + private static void sumKinds(ConnectionStats s) { + ConnectionStats.Traffic total = s.total; + if (total.packetsIn >= 0) return; + total.packetsIn = total.packetsOut = total.bytesIn = total.bytesOut = 0; + total.bandwidthInLastSecond = total.bandwidthOutLastSecond = 0; + total.bandwidthInLastMinute = total.bandwidthOutLastMinute = 0; + for (ConnectionStats.Kind kind : ConnectionStats.Kind.values()) { + ConnectionStats.Traffic t = s.traffic(kind); + total.packetsIn += Math.max(t.packetsIn, 0); + total.packetsOut += Math.max(t.packetsOut, 0); + total.bytesIn += Math.max(t.bytesIn, 0); + total.bytesOut += Math.max(t.bytesOut, 0); + total.bandwidthInLastSecond += Math.max(t.bandwidthInLastSecond, 0); + total.bandwidthOutLastSecond += Math.max(t.bandwidthOutLastSecond, 0); + total.bandwidthInLastMinute += Math.max(t.bandwidthInLastMinute, 0); + total.bandwidthOutLastMinute += Math.max(t.bandwidthOutLastMinute, 0); + } + } + + /** Parses TeamSpeak's {@code connection_*} fields; ones the report leaves out stay as they are. */ + private static void applyReport(ConnectionStats s, Map m) { + s.pingMs = pickDouble(s.pingMs, m.get("connection_ping")); + s.pingDeviationMs = pickDouble(s.pingDeviationMs, m.get("connection_ping_deviation")); + s.connectedTimeMs = pick(s.connectedTimeMs, m.get("connection_connected_time")); + s.idleTimeMs = pick(s.idleTimeMs, m.get("connection_idle_time")); + String ip = m.get("connection_client_ip"); + if (ip != null && !ip.isEmpty()) s.ip = ip; + s.port = (int) pick(s.port, m.get("connection_client_port")); + s.filetransferBandwidthSent = pick(s.filetransferBandwidthSent, m.get("connection_filetransfer_bandwidth_sent")); + s.filetransferBandwidthReceived = + pick(s.filetransferBandwidthReceived, m.get("connection_filetransfer_bandwidth_received")); + + applyTraffic(s.total, m, "total"); + for (ConnectionStats.Kind kind : ConnectionStats.Kind.values()) { + applyTraffic(s.traffic(kind), m, kind.name().toLowerCase(Locale.ROOT)); + } + } + + private static void applyTraffic(ConnectionStats.Traffic t, Map m, String suffix) { + t.lossIn = pickDouble(t.lossIn, m.get("connection_server2client_packetloss_" + suffix)); + t.lossOut = pickDouble(t.lossOut, m.get("connection_client2server_packetloss_" + suffix)); + t.packetsIn = pick(t.packetsIn, m.get("connection_packets_received_" + suffix)); + t.packetsOut = pick(t.packetsOut, m.get("connection_packets_sent_" + suffix)); + t.bytesIn = pick(t.bytesIn, m.get("connection_bytes_received_" + suffix)); + t.bytesOut = pick(t.bytesOut, m.get("connection_bytes_sent_" + suffix)); + t.bandwidthInLastSecond = pick(t.bandwidthInLastSecond, m.get("connection_bandwidth_received_last_second_" + suffix)); + t.bandwidthOutLastSecond = pick(t.bandwidthOutLastSecond, m.get("connection_bandwidth_sent_last_second_" + suffix)); + t.bandwidthInLastMinute = pick(t.bandwidthInLastMinute, m.get("connection_bandwidth_received_last_minute_" + suffix)); + t.bandwidthOutLastMinute = pick(t.bandwidthOutLastMinute, m.get("connection_bandwidth_sent_last_minute_" + suffix)); + } + + private static ConnectionStats.Kind mapKind(PacketKind kind) { + switch (kind) { + case KEEPALIVE: + return ConnectionStats.Kind.KEEPALIVE; + case SPEECH: + return ConnectionStats.Kind.SPEECH; + default: + return ConnectionStats.Kind.CONTROL; + } + } + + private static long pick(long current, String value) { + long v = parseLong(value); + return v >= 0 ? v : current; + } + + private static double pickDouble(double current, String value) { + double v = parseDouble(value); + return v >= 0 ? v : current; + } + + /** Parses a long, returning -1 for null/blank/non-numeric input. */ + private static long parseLong(String s) { + if (s == null || s.isEmpty()) return -1; + try { + return Long.parseLong(s.trim()); + } catch (NumberFormatException e) { + return -1; + } + } + + /** Parses a double, returning -1 for null/blank/non-numeric input. */ + private static double parseDouble(String s) { + if (s == null || s.isEmpty()) return -1; + try { + return Double.parseDouble(s.trim()); + } catch (NumberFormatException e) { + return -1; + } + } + + /** @return the parsed value, or 0 when it is absent or not a number */ + private static int safeInt(String value) { + try { + return value == null ? 0 : Integer.parseInt(value.trim()); + } catch (NumberFormatException ex) { + return 0; + } + } + + /** A request's snapshot, filled in by its reports as they arrive. */ + private static final class Pending { + final ConnectionStats stats; + final CountDownLatch reports; + + Pending(ConnectionStats stats, int expected) { + this.stats = stats; + this.reports = new CountDownLatch(expected); + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionStatsFormat.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionStatsFormat.java new file mode 100644 index 0000000..4c42439 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionStatsFormat.java @@ -0,0 +1,186 @@ +package eu.lixko.ts3j.client.net; + +import eu.lixko.ts3j.client.audio.VoiceReceiveStats; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; + +/** + * Renders {@link ConnectionStats} the way the official Connection Info window does: a + * summary, one traffic table per tab with Total / In / Out columns, and a quota tab. + * An unknown value (negative) shows as a dash. + */ +public final class ConnectionStatsFormat { + + public static final String UNKNOWN = "—"; + public static final String HIDDEN = "Hidden"; + public static final String UNLIMITED = "Unlimited"; + public static final String EXCEEDED = "Exceeded"; + + /** The traffic table's column headings, after the row labels. */ + public static final List COLUMNS = List.of("Total", "In", "Out"); + + private ConnectionStatsFormat() { + } + + /** A labelled figure. */ + public record Row(String label, String value) { + } + + /** A traffic table row; {@code total} is empty where the official client leaves it blank. */ + public record TrafficRow(String label, String total, String in, String out) { + } + + /** A traffic tab: the totals for a null {@code kind}, else one category. */ + public record Tab(String title, ConnectionStats.Kind kind) { + } + + public static final List TRAFFIC_TABS = List.of( + new Tab("Total", null), + new Tab("Speech", ConnectionStats.Kind.SPEECH), + new Tab("Keep Alive", ConnectionStats.Kind.KEEPALIVE), + new Tab("Control", ConnectionStats.Kind.CONTROL)); + + public static final String QUOTA_TAB = "Quota"; + public static final String VOICE_TAB = "Voice received"; + + /** Who the client is and how the link to them is doing; {@code s} may be null while loading. */ + public static List summaryRows(ConnectionStats s, String nickname) { + ConnectionStats k = s == null ? new ConnectionStats() : s; + return List.of( + new Row("Client name", nickname), + new Row("Connection time", duration(k.connectedTimeMs)), + new Row("Idle time", duration(k.idleTimeMs)), + new Row("Ping", ping(k.pingMs, k.pingDeviationMs)), + new Row("Client address", s == null ? UNKNOWN : address(s))); + } + + /** {@code ip:port}, what the copy button next to it puts on the clipboard; null when unknown. */ + public static String copyableAddress(ConnectionStats s) { + if (s == null || s.ip.isEmpty()) return null; + return s.port > 0 ? s.ip + ":" + s.port : s.ip; + } + + private static String address(ConnectionStats s) { + String address = copyableAddress(s); + return address == null ? HIDDEN : address; + } + + /** One traffic tab's table; only the totals carry the file transfer row. */ + public static List trafficRows(ConnectionStats s, ConnectionStats.Kind kind) { + ConnectionStats.Traffic t = s == null ? new ConnectionStats.Traffic() : s.traffic(kind); + List rows = new ArrayList<>(List.of( + new TrafficRow("Packet loss", loss(t.lossTotal()), loss(t.lossIn), loss(t.lossOut)), + new TrafficRow("Packets transferred", "", count(t.packetsIn), count(t.packetsOut)), + new TrafficRow("Bytes transferred", "", bytes(t.bytesIn), bytes(t.bytesOut)), + new TrafficRow("Bandwidth last second", "", + rate(t.bandwidthInLastSecond), rate(t.bandwidthOutLastSecond)), + new TrafficRow("Bandwidth last minute", "", + rate(t.bandwidthInLastMinute), rate(t.bandwidthOutLastMinute)))); + if (kind == null) { + long in = s == null ? -1 : s.filetransferBandwidthReceived; + long out = s == null ? -1 : s.filetransferBandwidthSent; + rows.add(new TrafficRow("File transfer bandwidth", "", rate(in), rate(out))); + } + return rows; + } + + /** + * The quota tab: downloads, then uploads. Only our own limits are known, so another + * client's groups hold just the month's figure. + */ + public static List> quotaGroups(ConnectionStats s) { + ConnectionStats k = s == null ? new ConnectionStats() : s; + return List.of( + quota(k, "download", "Downloaded this month:", k.monthBytesDownloaded, k.downloadQuotaMb), + quota(k, "upload", "Uploaded this month:", k.monthBytesUploaded, k.uploadQuotaMb)); + } + + private static List quota(ConnectionStats s, String direction, String label, long used, long quotaMb) { + Row month = new Row(label, bytes(used)); + if (!s.self) return List.of(month); + String available = quotaMb < 0 ? UNLIMITED : bytes(quotaMb * 1024 * 1024); + String remaining; + if (quotaMb < 0) remaining = UNLIMITED; + else if (used < 0) remaining = UNKNOWN; + else if (used > quotaMb * 1024 * 1024) remaining = EXCEEDED; + else remaining = bytes(quotaMb * 1024 * 1024 - used); + return List.of(month, + new Row("Available " + direction + " quota:", available), + new Row("Remaining " + direction + " this month:", remaining)); + } + + /** The voice our playback received; every value is a dash when nothing was heard. */ + public static List voiceRows(VoiceReceiveStats v) { + VoiceReceiveStats s = v == null ? VoiceReceiveStats.NONE : v; + boolean known = v != null; + return List.of( + new Row("Received", known ? count(s.received()) : UNKNOWN), + new Row("Played", known ? countOf(s.played(), s.due()) : UNKNOWN), + new Row("Missed", known ? countOf(s.missed(), s.due()) : UNKNOWN), + new Row("Recovered (FEC)", known ? countOf(s.recovered(), s.missed()) : UNKNOWN), + new Row("Out of order", known ? countOf(s.outOfOrder(), s.received()) : UNKNOWN), + new Row("Dropped (too late)", known ? countOf(s.late(), s.received()) : UNKNOWN), + new Row("Discarded (copies)", known ? countOf(s.duplicates(), s.received()) : UNKNOWN)); + } + + // ---- figures ---- + + /** {@code 153 ms ± 217.0}. */ + public static String ping(double ms, double deviationMs) { + if (ms < 0) return UNKNOWN; + String base = Math.round(ms) + " ms"; + if (deviationMs >= 0) base += " ± " + new DecimalFormat("0.0").format(deviationMs); + return base; + } + + /** A fraction 0..1 as a percentage. */ + public static String loss(double fraction) { + if (fraction < 0) return UNKNOWN; + return new DecimalFormat("0.00").format(fraction * 100.0) + " %"; + } + + /** {@code 133}, {@code 2.12 k}, {@code 1.05 M}. */ + public static String count(long n) { + if (n < 0) return UNKNOWN; + if (n < 1000) return Long.toString(n); + DecimalFormat f = new DecimalFormat("0.00"); + if (n < 1_000_000) return f.format(n / 1e3) + " k"; + return f.format(n / 1e6) + " M"; + } + + /** A count with its share of {@code of}, e.g. {@code 12 (0.4 %)}. */ + public static String countOf(long n, long of) { + if (n < 0) return UNKNOWN; + if (of <= 0) return count(n); + return count(n) + " (" + new DecimalFormat("0.0").format(100.0 * n / of) + " %)"; + } + + public static String bytes(long bytes) { + if (bytes < 0) return UNKNOWN; + if (bytes < 1024) return bytes + " Bytes"; + DecimalFormat f = new DecimalFormat("0.00"); + double kib = bytes / 1024.0; + if (kib < 1024) return f.format(kib) + " KiB"; + double mib = kib / 1024.0; + if (mib < 1024) return f.format(mib) + " MiB"; + return f.format(mib / 1024.0) + " GiB"; + } + + public static String rate(long bytesPerSecond) { + return bytesPerSecond < 0 ? UNKNOWN : bytes(bytesPerSecond) + "/s"; + } + + /** {@code 04:34}, or {@code 15:35:17} from an hour on. */ + public static String duration(long ms) { + if (ms < 0) return UNKNOWN; + long totalSeconds = ms / 1000; + long hours = totalSeconds / 3600; + long minutes = (totalSeconds % 3600) / 60; + long seconds = totalSeconds % 60; + return hours > 0 + ? String.format("%02d:%02d:%02d", hours, minutes, seconds) + : String.format("%02d:%02d", minutes, seconds); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/DatabaseClient.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/DatabaseClient.java new file mode 100644 index 0000000..539f5af --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/DatabaseClient.java @@ -0,0 +1,9 @@ +package eu.lixko.ts3j.client.net; + +/** + * A client the server's database knows, online or not: what an offline message is addressed to. + * + * @param nickname the nickname they last used on this server + */ +public record DatabaseClient(String uniqueId, int databaseId, String nickname) { +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Details.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Details.java new file mode 100644 index 0000000..b937157 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Details.java @@ -0,0 +1,125 @@ +package eu.lixko.ts3j.client.net; + +import eu.lixko.ts3j.client.contacts.Contact; + +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; + +/** + * What the info box tells about the server, a channel or a client, as the TeamSpeak 3 client's + * info frame does: labelled facts, then a description in BBCode. The same on every frontend, + * which only lays it out. + * + * @param description BBCode; empty when there is none + * @param pending the description is still being asked for + */ +public record Details(String title, List fields, String description, boolean pending) { + + /** + * One labelled fact. + * + * @param groups the groups {@code value} names, in order, for frontends that show their icons; + * empty when it names none + * @param minor for frontends short of room to show only on asking + */ + public record Field(String label, String value, List groups, boolean minor) { + Field(String label, String value) { + this(label, value, List.of(), false); + } + + Field(String label, String value, List groups) { + this(label, value, groups, false); + } + + static Field minor(String label, String value) { + return new Field(label, value, List.of(), true); + } + } + + private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + public static Details server(ServerModel model, String address) { + List fields = new ArrayList<>(); + fields.add(new Field("Address", address)); + String version = model.serverProperty("virtualserver_version"); + String platform = model.serverProperty("virtualserver_platform"); + if (!version.isEmpty()) fields.add(new Field("Version", version + (platform.isEmpty() ? "" : " on " + platform))); + String max = model.serverProperty("virtualserver_maxclients"); + fields.add(new Field("Clients", model.clientCount() + (max.isEmpty() ? "" : " / " + max))); + fields.add(new Field("Channels", Integer.toString(model.channelCount()))); + long created = parseLong(model.serverProperty("virtualserver_created")); + if (created > 0) { + fields.add(new Field("Created", DATE.format(Instant.ofEpochSecond(created).atZone(ZoneId.systemDefault())))); + } + String welcome = model.serverProperty("virtualserver_welcomemessage").trim(); + String host = model.serverProperty("virtualserver_hostmessage").trim(); + String description = welcome.isEmpty() || host.isEmpty() ? welcome + host : welcome + "\n\n" + host; + return new Details(model.getServerName(), fields, description, false); + } + + public static Details channel(ChannelNode ch) { + List fields = new ArrayList<>(); + if (ch.maxClients >= 0) fields.add(new Field("Max clients", Integer.toString(ch.maxClients))); + if (ch.hasPassword) fields.add(new Field("Password", "protected")); + if (!ch.topic.isEmpty()) fields.add(new Field("Topic", ch.topic)); + String description = ch.description == null ? "" : ch.description; + return new Details(ch.name, fields, description, description.isEmpty() && !ch.descriptionLoaded); + } + + /** @param contact the client's contact entry, or null */ + public static Details client(ClientEntry cl, ServerModel model, Contact contact) { + List fields = new ArrayList<>(); + if (contact != null) { + String type = contact.type.label(); + if (!contact.phoneticNickname.isEmpty()) type += " (" + contact.phoneticNickname + ")"; + fields.add(Field.minor("Contact", type)); + } + + List serverGroups = model.serverGroupsOf(cl.serverGroupIds); + if (serverGroups.isEmpty()) { + List names = model.serverGroupNames(cl.serverGroupIds); + fields.add(new Field("Server groups", names.isEmpty() ? "—" : String.join(", ", names))); + } else { + // A nameless group is there for its icon only; without one, there is nothing to show of it. + List shown = new ArrayList<>(); + List names = new ArrayList<>(); + for (Group g : serverGroups) { + if (g.name.isBlank() && g.iconId == 0) continue; + shown.add(g); + if (!g.name.isBlank()) names.add(g.name.trim()); + } + fields.add(new Field("Server groups", names.isEmpty() ? "—" : String.join(", ", names), shown)); + } + Group channelGroup = model.channelGroup(cl.channelGroupId); + fields.add(channelGroup != null + ? new Field("Channel group", channelGroup.name, List.of(channelGroup)) + : new Field("Channel group", "#" + cl.channelGroupId)); + + if (cl.talkPower != 0) fields.add(Field.minor("Talk power", Integer.toString(cl.talkPower))); + if (!cl.version.isEmpty()) { + fields.add(Field.minor("Version", cl.version + (cl.platform.isEmpty() ? "" : " on " + cl.platform))); + } else if (!cl.platform.isEmpty()) { + fields.add(Field.minor("Platform", cl.platform)); + } + if (cl.away) fields.add(Field.minor("Status", "Away")); + if (!cl.inputHardware) fields.add(Field.minor("Microphone", "disabled")); + else if (cl.inputMuted) fields.add(Field.minor("Microphone", "muted")); + if (!cl.outputHardware) fields.add(Field.minor("Speakers", "disabled")); + else if (cl.outputMuted) fields.add(Field.minor("Speakers", "muted")); + if (!cl.uniqueId.isEmpty()) fields.add(Field.minor("Unique ID", cl.uniqueId)); + + String name = contact == null ? cl.nickname : contact.displayName(cl.nickname); + return new Details(name, fields, cl.description == null ? "" : cl.description, false); + } + + private static long parseLong(String s) { + try { + return s.isEmpty() ? 0 : Long.parseLong(s.trim()); + } catch (NumberFormatException e) { + return 0; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Group.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Group.java new file mode 100644 index 0000000..c8569a2 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Group.java @@ -0,0 +1,34 @@ +package eu.lixko.ts3j.client.net; + +/** A server or channel group as announced by the server. */ +public final class Group { + + public final int id; + public final String name; + /** Id of the group's icon (0 = none); resolved through {@link IconRepository}. */ + public final long iconId; + /** Display order among groups; lower comes first. */ + public final int sortId; + /** TS3 group type: 0 = template, 1 = regular, 2 = query (server groups only). */ + public final int type; + /** Power needed to add a member to this group. */ + public final int neededMemberAddPower; + /** Power needed to remove a member from this group. */ + public final int neededMemberRemovePower; + + public Group(int id, String name, long iconId, int sortId, int type, + int neededMemberAddPower, int neededMemberRemovePower) { + this.id = id; + this.name = name; + this.iconId = iconId; + this.sortId = sortId; + this.type = type; + this.neededMemberAddPower = neededMemberAddPower; + this.neededMemberRemovePower = neededMemberRemovePower; + } + + /** Regular, user-assignable groups exclude templates and query-only groups. */ + public boolean isRegular() { + return type == 1; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/GroupChoice.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/GroupChoice.java new file mode 100644 index 0000000..51203e1 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/GroupChoice.java @@ -0,0 +1,5 @@ +package eu.lixko.ts3j.client.net; + +/** A group as offered for one client: whether they are in it, and whether we may change that. */ +public record GroupChoice(Group group, boolean assigned, boolean allowed) { +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/HostButton.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/HostButton.java new file mode 100644 index 0000000..45097cf --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/HostButton.java @@ -0,0 +1,19 @@ +package eu.lixko.ts3j.client.net; + +/** + * The button a server puts in the toolbar's top right corner, linking to its host's site. + * + * @param url what a click opens; empty when the button only shows + * @param gfxUrl the picture to show; empty for TeamSpeak's own host button icon + * @param tooltip shown on hover; may be empty + */ +public record HostButton(String url, String gfxUrl, String tooltip) { + + /** @return the button, or {@code null} when the server sets neither a link nor a picture */ + public static HostButton of(String url, String gfxUrl, String tooltip) { + url = url == null ? "" : url.trim(); + gfxUrl = gfxUrl == null ? "" : gfxUrl.trim(); + if (url.isEmpty() && gfxUrl.isEmpty()) return null; + return new HostButton(url, gfxUrl, tooltip == null ? "" : tooltip.trim()); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/IconRepository.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/IconRepository.java new file mode 100644 index 0000000..0e234c3 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/IconRepository.java @@ -0,0 +1,200 @@ +package eu.lixko.ts3j.client.net; + +import eu.lixko.ts3j.client.config.AppDirs; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * Supplies the raw PNG bytes of a TeamSpeak icon id, as used by server and channel + * groups. + * + *

    Ids up to {@link #MAX_BUNDLED_ID} identify the icons shipped with the client + * (TeamSpeak's default group icons); anything above that is a server-specific icon + * stored in the virtual server's file repository as {@code /icon_} in channel 0, + * which is downloaded once and then cached in memory and on disk. + * + *

    Lookups never block: {@link #get(long)} returns {@code null} while an icon is + * still being fetched and the listener is notified once it becomes available. + */ +public final class IconRepository { + + /** Icons at or below this id are bundled defaults rather than server uploads. */ + public static final int MAX_BUNDLED_ID = 1000; + + /** + * The default group icons shipped with the client, in the order TeamSpeak's own icon + * packs list them. These are what the icon chooser offers as "local" icons. + */ + public static final List BUNDLED_IDS = List.of(100L, 200L, 300L, 500L, 600L); + + /** Downloads {@code /icon_} from the connected server's file repository. */ + public interface Fetcher { + byte[] fetchIcon(long iconId) throws Exception; + } + + private final Fetcher fetcher; + private final Runnable onIconLoaded; + private final Map icons = new ConcurrentHashMap<>(); + private final Set pending = ConcurrentHashMap.newKeySet(); + private final Set failed = ConcurrentHashMap.newKeySet(); + private final ExecutorService downloads = Executors.newSingleThreadExecutor(r -> { + Thread t = new Thread(r, "ts3j-icons"); + t.setDaemon(true); + return t; + }); + + /** + * @param onIconLoaded run (off the UI thread) whenever a previously missing icon + * has arrived, so the view can repaint + */ + public IconRepository(Fetcher fetcher, Runnable onIconLoaded) { + this.fetcher = fetcher; + this.onIconLoaded = onIconLoaded; + } + + /** + * @return the icon's PNG bytes, or {@code null} if it is unknown, still loading or + * unavailable. A server icon that is not cached yet starts downloading. + */ + public byte[] get(long iconId) { + long id = normalize(iconId); + if (id == 0) return null; + + byte[] cached = icons.get(id); + if (cached != null) return cached; + + byte[] bundled = readBundled(id); + if (bundled != null) { + icons.put(id, bundled); + return bundled; + } + if (id <= MAX_BUNDLED_ID) return null; // a default icon we do not ship + + byte[] fromDisk = readDiskCache(id); + if (fromDisk != null) { + icons.put(id, fromDisk); + return fromDisk; + } + if (!failed.contains(id) && pending.add(id)) { + downloads.execute(() -> download(id)); + } + return null; + } + + /** + * The icon as a file on disk, materialising bundled icons into the cache directory + * on first use, for callers that can only reference images by URL (HTML views). + * + * @return the file, or {@code null} while the icon is unavailable + */ + public File file(long iconId) { + long id = normalize(iconId); + byte[] data = get(id); + if (data == null) return null; + File file = new File(cacheDir(), "icon_" + id + ".png"); + if (!file.isFile()) writeDiskCache(id, data); + return file.isFile() ? file : null; + } + + /** + * An icon that needs no server: one shipped with the client or downloaded earlier, + * e.g. for a bookmark while it is not connected. + * + * @return the icon's PNG bytes, or {@code null} if it has never been fetched + */ + public static byte[] cached(long iconId) { + long id = normalize(iconId); + if (id == 0) return null; + byte[] bundled = readBundled(id); + return bundled != null || id <= MAX_BUNDLED_ID ? bundled : readDiskCache(id); + } + + /** An icon id as a property carries it, 0 for none or garbage. */ + public static long parseId(String value) { + if (value == null || value.isBlank()) return 0; + try { + return normalize(Long.parseLong(value.trim())); + } catch (NumberFormatException e) { + return 0; + } + } + + /** Forgets download failures so icons can be retried on the next reconnect. */ + public void retryFailed() { + failed.clear(); + } + + public void shutdown() { + downloads.shutdownNow(); + } + + private void download(long id) { + try { + byte[] data = fetcher.fetchIcon(id); + if (data == null || data.length == 0) { + failed.add(id); + return; + } + icons.put(id, data); + writeDiskCache(id, data); + if (onIconLoaded != null) onIconLoaded.run(); + } catch (IllegalStateException e) { + // Not connected (yet): a channel icon can be asked for while the tree is + // first painted, before file transfers are up. Leave it retryable. + } catch (Exception e) { + // Missing or permission-denied icons are common; don't ask again. + failed.add(id); + } finally { + pending.remove(id); + } + } + + /** + * TeamSpeak transmits icon ids as unsigned 32-bit CRCs, which arrive here through + * signed parsing; fold them back into their unsigned value. + */ + private static long normalize(long iconId) { + return iconId < 0 ? iconId & 0xFFFFFFFFL : iconId; + } + + private static byte[] readBundled(long id) { + try (InputStream in = IconRepository.class.getResourceAsStream("/icons/group_" + id + ".png")) { + return in == null ? null : in.readAllBytes(); + } catch (IOException e) { + return null; + } + } + + private static File cacheDir() { + return new File(AppDirs.profile(), "icons"); + } + + private static byte[] readDiskCache(long id) { + File file = new File(cacheDir(), "icon_" + id + ".png"); + if (!file.isFile()) return null; + try { + return Files.readAllBytes(file.toPath()); + } catch (IOException e) { + return null; + } + } + + private void writeDiskCache(long id, byte[] data) { + try { + //noinspection ResultOfMethodCallIgnored + cacheDir().mkdirs(); + Files.write(new File(cacheDir(), "icon_" + id + ".png").toPath(), data); + } catch (IOException ignored) { + // the in-memory cache still serves this session + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/OfflineMessage.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/OfflineMessage.java new file mode 100644 index 0000000..08ec79c --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/OfflineMessage.java @@ -0,0 +1,39 @@ +package eu.lixko.ts3j.client.net; + +import java.util.Map; + +/** + * A message in our offline message inbox on the server, without its body: {@code messagelist} + * leaves that out, and reading it costs a {@code messageget} each. + * + * @param senderName the sender's last known nickname, or their unique id when the server has forgotten them + */ +public record OfflineMessage(int id, String senderUid, String senderName, String subject, + long timestampEpochSeconds, boolean read) { + + /** Reads a message off a {@code notifymessagelist} event's fields. */ + static OfflineMessage from(Map fields, String senderName) { + return new OfflineMessage((int) parseLong(fields.get("msgid")), + orEmpty(fields.get("cluid")), + senderName, + orEmpty(fields.get("subject")), + parseLong(fields.get("timestamp")), + "1".equals(fields.get("flag_read"))); + } + + public OfflineMessage withRead(boolean read) { + return new OfflineMessage(id, senderUid, senderName, subject, timestampEpochSeconds, read); + } + + static String orEmpty(String s) { + return s == null || s.equals("null") ? "" : s; + } + + private static long parseLong(String s) { + try { + return s == null ? 0 : Long.parseLong(s.trim()); + } catch (NumberFormatException e) { + return 0; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/OfflineMessageAdmin.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/OfflineMessageAdmin.java new file mode 100644 index 0000000..f95e2de --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/OfflineMessageAdmin.java @@ -0,0 +1,163 @@ +package eu.lixko.ts3j.client.net; + +import com.github.manevolent.ts3j.command.CommandException; +import com.github.manevolent.ts3j.command.SingleCommand; +import com.github.manevolent.ts3j.command.parameter.CommandParameter; +import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; +import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent; +import com.github.manevolent.ts3j.protocol.ProtocolRole; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Our offline message inbox on the server, sending offline messages, and finding the + * database clients to send them to. + * + *

    Split out of {@link TeamspeakConnection} like {@link ComplaintAdmin}. Every reply comes as + * notifications ahead of the command's completion, collected into {@link #replies}; calls are + * serialised so two requests never share it. Every call blocks and must run off the UI thread. + */ +final class OfflineMessageAdmin { + + /** What a listing answers when it has nothing to list. */ + private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501; + /** What a unique id or database id lookup answers when the server has no such client. */ + private static final int ERROR_INVALID_CLIENT_ID = 0x0200; + /** The most matches a nickname search names; each costs a lookup, and lookups flood quickly. */ + private static final int MAX_SEARCH_RESULTS = 10; + + private final TeamspeakConnection conn; + /** Senders' nicknames by unique id; they cost a lookup each, so a connection asks once. */ + private final Map names = new ConcurrentHashMap<>(); + + /** The notification the request in flight is answered by, and what has arrived of it. */ + private volatile String awaited; + private volatile List> replies; + + OfflineMessageAdmin(TeamspeakConnection conn) { + this.conn = conn; + } + + /** Forgets what the last server told us; a reconnect may be to another server. */ + void reset() { + names.clear(); + } + + void onReply(UnknownTeamspeakEvent e) { + List> collected = replies; + if (collected != null && e.getCommand().equals(awaited)) collected.add(e.getMap()); + } + + /** Runs a command and returns the {@code notification} rows it was answered with; none when the result is empty. */ + private synchronized List> query(String notification, String command, + CommandParameter... params) throws Exception { + List> collected = Collections.synchronizedList(new ArrayList<>()); + awaited = notification; + replies = collected; + try { + conn.socket().executeCommand(new SingleCommand(command, ProtocolRole.CLIENT, params)).complete(); + conn.awaitEventsProcessed(); + } catch (CommandException e) { + if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e; + } finally { + replies = null; + awaited = null; + } + return new ArrayList<>(collected); + } + + private synchronized void execute(String command, CommandParameter... params) throws Exception { + conn.socket().executeCommand(new SingleCommand(command, ProtocolRole.CLIENT, params)).complete(); + } + + private static CommandSingleParameter param(String key, Object value) { + return new CommandSingleParameter(key, String.valueOf(value)); + } + + // ---- inbox ---- + + List list() throws Exception { + List messages = new ArrayList<>(); + for (Map row : query("notifymessagelist", "messagelist")) { + String sender = OfflineMessage.orEmpty(row.get("cluid")); + messages.add(OfflineMessage.from(row, senderName(sender))); + } + return messages; + } + + private String senderName(String uniqueId) throws Exception { + if (uniqueId.isEmpty()) return ""; + String known = names.get(uniqueId); + if (known != null) return known; + DatabaseClient client = lookupUid(uniqueId); + String name = client != null ? client.nickname() : uniqueId; + names.put(uniqueId, name); + return name; + } + + /** Reads a message's body; this does not mark it read. */ + String body(int messageId) throws Exception { + List> rows = query("notifymessage", "messageget", param("msgid", messageId)); + if (rows.isEmpty()) throw new IllegalStateException("The message is gone."); + return OfflineMessage.orEmpty(rows.get(0).get("message")); + } + + void setRead(int messageId, boolean read) throws Exception { + execute("messageupdateflag", param("msgid", messageId), param("flag", read ? 1 : 0)); + } + + void delete(int messageId) throws Exception { + execute("messagedel", param("msgid", messageId)); + } + + void send(String recipientUid, String subject, String message) throws Exception { + execute("messageadd", param("cluid", recipientUid), param("subject", subject), param("message", message)); + } + + // ---- recipients ---- + + /** @return the client with this unique id, or {@code null} when the server has never seen them */ + DatabaseClient lookupUid(String uniqueId) throws Exception { + try { + List> rows = query("notifyclientnamefromuid", "clientgetnamefromuid", + param("cluid", uniqueId)); + return rows.isEmpty() ? null : fromNameReply(rows.get(0)); + } catch (CommandException e) { + if (e.getErrorId() == ERROR_INVALID_CLIENT_ID) return null; + throw e; + } + } + + /** + * Clients whose last nickname contains {@code nickname}. Needs + * {@code b_virtualserver_client_dbsearch}, which the server never reports to us up front. + */ + List search(String nickname) throws Exception { + List> found = query("notifyclientdbfind", "clientdbfind", + param("pattern", "%" + nickname + "%")); + List clients = new ArrayList<>(); + for (Map row : found) { + if (clients.size() == MAX_SEARCH_RESULTS) break; + List> named = query("notifyclientnamefromdbid", "clientgetnamefromdbid", + param("cldbid", OfflineMessage.orEmpty(row.get("cldbid")))); + if (!named.isEmpty()) clients.add(fromNameReply(named.get(0))); + } + for (DatabaseClient c : clients) names.put(c.uniqueId(), c.nickname()); + return clients; + } + + private static DatabaseClient fromNameReply(Map row) { + int dbId; + try { + dbId = Integer.parseInt(OfflineMessage.orEmpty(row.get("cldbid")).trim()); + } catch (NumberFormatException e) { + dbId = 0; + } + return new DatabaseClient(OfflineMessage.orEmpty(row.get("cluid")), dbId, + OfflineMessage.orEmpty(row.get("name"))); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/PictureDownloads.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/PictureDownloads.java new file mode 100644 index 0000000..4fb5487 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/PictureDownloads.java @@ -0,0 +1,202 @@ +package eu.lixko.ts3j.client.net; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * The pictures descriptions show, fetched from the web on first sight and kept on disk + * for a month after they were last shown. + * + *

    Lookups never block: {@link #get} returns {@code null} while a picture is on its + * way, and the listeners hear when one has come or could not be had. + */ +public final class PictureDownloads { + + /** Fetches the pictures whose addresses use a scheme of its own, rather than from the web. */ + public interface Source { + /** @return the picture, or {@code null} when it cannot be had */ + byte[] fetch(String url, long maxBytes) throws IOException; + } + + private static final long MAX_BYTES = 8L << 20; + private static final int TIMEOUT_MS = 10_000; + private static final long KEEP_MS = 30L * 24 * 60 * 60 * 1000; + private static final String USER_AGENT = "ts3client"; + private static final int MAX_REDIRECTS = 5; + + private final File dir; + private final boolean plainHttp; + private final List listeners = new CopyOnWriteArrayList<>(); + private final Set pending = ConcurrentHashMap.newKeySet(); + private final Set failed = ConcurrentHashMap.newKeySet(); + private final Map sources = new ConcurrentHashMap<>(); + private final ExecutorService downloads = Executors.newFixedThreadPool(2, r -> { + Thread t = new Thread(r, "picture-download"); + t.setDaemon(true); + return t; + }); + + /** + * @param plainHttp whether plain http may be used; where it may not (Android), an + * http address is fetched over https, which most hosts also serve + */ + public PictureDownloads(File dir, boolean plainHttp) { + this.dir = dir; + this.plainHttp = plainHttp; + downloads.execute(this::prune); + } + + /** @param listener run off the UI thread whenever a picture has come or failed */ + public void addListener(Runnable listener) { + listeners.add(listener); + } + + /** Fetches addresses starting with {@code scheme} (e.g. {@code "tsattach:"}) from {@code source}. */ + public void addSource(String scheme, Source source) { + sources.put(scheme, source); + } + + /** Asks again for the pictures that could not be had, e.g. once signed in to where they come from. */ + public void retryFailed() { + failed.clear(); + for (Runnable listener : listeners) listener.run(); + } + + public void removeListener(Runnable listener) { + listeners.remove(listener); + } + + /** + * @return the picture's file, or {@code null} while it downloads or when it cannot be + * had (see {@link #failed}). A picture not on disk yet starts downloading. + */ + public File get(String url) { + File file = new File(dir, name(url)); + if (file.isFile()) { + //noinspection ResultOfMethodCallIgnored + file.setLastModified(System.currentTimeMillis()); + return file; + } + if (!failed.contains(url) && pending.add(url)) downloads.execute(() -> download(url, file)); + return null; + } + + /** Whether the picture could not be had this session; it is not asked for again until then. */ + public boolean failed(String url) { + return failed.contains(url); + } + + private void download(String url, File file) { + try { + Source source = source(url); + byte[] data = source != null ? source.fetch(url, MAX_BYTES) : fetch(allowed(url)); + if (data == null) { + failed.add(url); + } else { + //noinspection ResultOfMethodCallIgnored + dir.mkdirs(); + File part = new File(dir, file.getName() + ".part"); + Files.write(part.toPath(), data); + Files.move(part.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING); + } + } catch (IOException | RuntimeException e) { + failed.add(url); + } finally { + pending.remove(url); + } + for (Runnable listener : listeners) listener.run(); + } + + private Source source(String url) { + for (Map.Entry e : sources.entrySet()) { + if (url.startsWith(e.getKey())) return e.getValue(); + } + return null; + } + + /** The address as it may be fetched here: over https where plain http is not allowed. */ + private String allowed(String url) { + boolean http = url.regionMatches(true, 0, "http://", 0, 7); + return plainHttp || !http ? url : "https://" + url.substring(7); + } + + /** + * Follows redirects itself: Java does not follow one that changes protocol, which is how + * many hosts send plain http on to https. + */ + private byte[] fetch(String url) throws IOException { + for (int hop = 0; hop <= MAX_REDIRECTS; hop++) { + HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); + try { + connection.setInstanceFollowRedirects(false); + connection.setConnectTimeout(TIMEOUT_MS); + connection.setReadTimeout(TIMEOUT_MS); + // Some hosts turn away Java's own agent (Wikimedia does). + connection.setRequestProperty("User-Agent", USER_AGENT); + int code = connection.getResponseCode(); + String location = connection.getHeaderField("Location"); + if (code / 100 == 3 && location != null) { + String next = new URL(new URL(url), location).toString(); + if (!next.regionMatches(true, 0, "http", 0, 4)) return null; + url = allowed(next); + continue; + } + return code == HttpURLConnection.HTTP_OK ? read(connection) : null; + } finally { + connection.disconnect(); + } + } + return null; + } + + private static byte[] read(HttpURLConnection connection) throws IOException { + if (connection.getContentLengthLong() > MAX_BYTES) return null; + try (InputStream in = connection.getInputStream()) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buffer = new byte[16 * 1024]; + for (int n; (n = in.read(buffer)) >= 0; ) { + out.write(buffer, 0, n); + if (out.size() > MAX_BYTES) return null; + } + return out.toByteArray(); + } + } + + /** Forgets the pictures not shown for a month. */ + private void prune() { + File[] files = dir.listFiles(); + if (files == null) return; + long cutoff = System.currentTimeMillis() - KEEP_MS; + for (File f : files) { + //noinspection ResultOfMethodCallIgnored + if (f.lastModified() < cutoff) f.delete(); + } + } + + private static String name(String url) { + try { + byte[] hash = MessageDigest.getInstance("SHA-1").digest(url.getBytes(StandardCharsets.UTF_8)); + StringBuilder sb = new StringBuilder(); + for (byte b : hash) sb.append(String.format("%02x", b)); + return sb.toString(); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/PrivilegeKey.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/PrivilegeKey.java new file mode 100644 index 0000000..f83b7ab --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/PrivilegeKey.java @@ -0,0 +1,36 @@ +package eu.lixko.ts3j.client.net; + +import java.util.Map; + +/** + * A privilege key (token): a one-time code that puts whoever redeems it into a server + * group, or into a channel group in one channel. + * + * @param groupId the server or channel group it grants + * @param channelId the channel a channel group key applies in; 0 for a server group key + */ +public record PrivilegeKey(String token, boolean channelGroup, int groupId, int channelId, + long createdEpochSeconds, String description) { + + /** Reads a key off a {@code notifytokenlist} event's fields. */ + static PrivilegeKey from(Map fields) { + return new PrivilegeKey(orEmpty(fields.get("token")), + parseLong(fields.get("token_type")) == 1, + (int) parseLong(fields.get("token_id1")), + (int) parseLong(fields.get("token_id2")), + parseLong(fields.get("token_created")), + orEmpty(fields.get("token_description"))); + } + + private static String orEmpty(String s) { + return s == null || s.equals("null") ? "" : s; + } + + private static long parseLong(String s) { + try { + return s == null ? 0 : Long.parseLong(s.trim()); + } catch (NumberFormatException e) { + return 0; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/PrivilegeKeyAdmin.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/PrivilegeKeyAdmin.java new file mode 100644 index 0000000..bf11b15 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/PrivilegeKeyAdmin.java @@ -0,0 +1,90 @@ +package eu.lixko.ts3j.client.net; + +import com.github.manevolent.ts3j.command.CommandException; +import com.github.manevolent.ts3j.command.SingleCommand; +import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; +import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent; +import com.github.manevolent.ts3j.protocol.ProtocolRole; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * The server's privilege keys: listing, creating, deleting and redeeming them. + * + *

    Split out of {@link TeamspeakConnection} like {@link BanAdmin}, and answered the same + * way: {@code tokenlist} and {@code tokenadd} reply with notifications ahead of the + * command's own completion. Every call here blocks and must run off the UI thread; the + * connection's public wrappers do that. + */ +final class PrivilegeKeyAdmin { + + /** What {@code tokenlist} answers when there are no keys at all. */ + private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501; + + private final TeamspeakConnection conn; + + /** The {@code tokenlist} reply in progress; one request may be in flight at a time. */ + private volatile List listing; + /** The key the {@code tokenadd} in flight was answered with. */ + private volatile String created; + + PrivilegeKeyAdmin(TeamspeakConnection conn) { + this.conn = conn; + } + + List list() throws Exception { + List keys = Collections.synchronizedList(new ArrayList<>()); + listing = keys; + try { + conn.socket().executeCommand(new SingleCommand("tokenlist", ProtocolRole.CLIENT)).complete(); + conn.awaitEventsProcessed(); + } catch (CommandException e) { + if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e; + } finally { + listing = null; + } + return new ArrayList<>(keys); + } + + void onListEntry(UnknownTeamspeakEvent e) { + List keys = listing; + if (keys != null) keys.add(PrivilegeKey.from(e.getMap())); + } + + /** + * Creates a key. + * + * @param channelId the channel a channel group key applies in; ignored for a server group + * @return the new key + */ + synchronized String add(boolean channelGroup, int groupId, int channelId, String description) throws Exception { + SingleCommand cmd = new SingleCommand("tokenadd", ProtocolRole.CLIENT); + cmd.add(new CommandSingleParameter("tokentype", channelGroup ? "1" : "0")); + cmd.add(new CommandSingleParameter("tokenid1", Integer.toString(groupId))); + cmd.add(new CommandSingleParameter("tokenid2", channelGroup ? Integer.toString(channelId) : "0")); + cmd.add(new CommandSingleParameter("tokendescription", description)); + created = null; + conn.socket().executeCommand(cmd).complete(); + conn.awaitEventsProcessed(); + String token = created; + if (token == null || token.isEmpty()) throw new IllegalStateException("The server did not return the key"); + return token; + } + + void onAdded(UnknownTeamspeakEvent e) { + created = e.get("token"); + } + + void delete(String token) throws Exception { + conn.socket().executeCommand(new SingleCommand("tokendelete", ProtocolRole.CLIENT, + new CommandSingleParameter("token", token))).complete(); + } + + /** Redeems a key; the server announces the resulting group change itself. */ + void use(String token) throws Exception { + conn.socket().executeCommand(new SingleCommand("tokenuse", ProtocolRole.CLIENT, + new CommandSingleParameter("token", token))).complete(); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerLogAdmin.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerLogAdmin.java new file mode 100644 index 0000000..2fd1785 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerLogAdmin.java @@ -0,0 +1,82 @@ +package eu.lixko.ts3j.client.net; + +import com.github.manevolent.ts3j.command.CommandException; +import com.github.manevolent.ts3j.command.SingleCommand; +import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; +import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent; +import com.github.manevolent.ts3j.protocol.ProtocolRole; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Reads the virtual server's log with {@code logview}, which answers with one + * {@code notifyserverlog} per line, newest first, each also carrying {@code last_pos}: where + * the lines it returned begin in the log file, and so where the older ones end. + * + *

    Split out of {@link TeamspeakConnection} like {@link BanAdmin}. Every call here blocks + * and must run off the UI thread; the connection's public wrapper does that. + */ +final class ServerLogAdmin { + + /** The most lines {@code logview} returns at once. */ + static final int PAGE_LINES = 100; + + /** What {@code logview} may answer for an empty log. */ + private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501; + + private final TeamspeakConnection conn; + + /** The {@code logview} reply in progress; one request may be in flight at a time. */ + private volatile Reply reply; + + private static final class Reply { + final List entries = Collections.synchronizedList(new ArrayList<>()); + volatile long lastPos; + } + + ServerLogAdmin(TeamspeakConnection conn) { + this.conn = conn; + } + + /** + * Reads the newest lines, or with {@code olderFrom} > 0 those ending there (from an + * earlier {@link ServerLogPage#olderFrom()}). + */ + synchronized ServerLogPage read(long olderFrom) throws Exception { + SingleCommand cmd = new SingleCommand("logview", ProtocolRole.CLIENT); + cmd.add(new CommandSingleParameter("lines", Integer.toString(PAGE_LINES))); + if (olderFrom > 0) cmd.add(new CommandSingleParameter("begin_pos", Long.toString(olderFrom))); + cmd.add(new CommandSingleParameter("reverse", "1")); + cmd.add(new CommandSingleParameter("instance", "0")); + Reply r = new Reply(); + reply = r; + try { + conn.socket().executeCommand(cmd).complete(); + conn.awaitEventsProcessed(); + } catch (CommandException e) { + if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e; + } finally { + reply = null; + } + List entries = new ArrayList<>(r.entries); + Collections.reverse(entries); + return new ServerLogPage(entries, entries.isEmpty() ? 0 : r.lastPos); + } + + void onLine(UnknownTeamspeakEvent e) { + Reply r = reply; + if (r == null) return; + String line = e.get("l"); + if (line != null && !line.isEmpty()) r.entries.add(ServerLogEntry.parse(line)); + String lastPos = e.get("last_pos"); + if (lastPos != null) { + try { + r.lastPos = Long.parseLong(lastPos.trim()); + } catch (NumberFormatException ignored) { + // keep what the earlier lines said + } + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerLogEntry.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerLogEntry.java new file mode 100644 index 0000000..cd94e46 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerLogEntry.java @@ -0,0 +1,49 @@ +package eu.lixko.ts3j.client.net; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.Locale; + +/** + * One line of the virtual server's log, as {@code logview} hands it over: + * {@code 2026-10-04 13:11:01.038554|INFO |VirtualServer |1 |message}. + * + * @param timestamp when the server wrote it, in UTC as the server logs; {@code null} if the line had none + * @param channel the server component that wrote it, e.g. {@code VirtualServer} or {@code PktHandler} + */ +public record ServerLogEntry(LocalDateTime timestamp, Level level, String channel, String message) { + + /** The server's log levels, most severe first. */ + public enum Level { + CRITICAL, ERROR, WARNING, INFO, DEBUG, DEVEL + } + + private static final DateTimeFormatter TIMESTAMP = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSSSSS]"); + + /** + * Reads a log line. One whose timestamp is damaged — the server cuts the start off the + * file's very first line — keeps the rest; one that does not follow the format at all + * is kept whole as an info message. + */ + public static ServerLogEntry parse(String line) { + String[] fields = line.split("\\|", 5); + if (fields.length == 5) { + try { + Level level = Level.valueOf(fields[1].trim().toUpperCase(Locale.ROOT)); + return new ServerLogEntry(timestamp(fields[0]), level, fields[2].trim(), fields[4]); + } catch (IllegalArgumentException ignored) { + // not a line of ours; fall through + } + } + return new ServerLogEntry(null, Level.INFO, "", line); + } + + private static LocalDateTime timestamp(String field) { + try { + return LocalDateTime.parse(field.trim(), TIMESTAMP); + } catch (DateTimeParseException e) { + return null; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerLogPage.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerLogPage.java new file mode 100644 index 0000000..5fefb56 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerLogPage.java @@ -0,0 +1,15 @@ +package eu.lixko.ts3j.client.net; + +import java.util.List; + +/** + * A stretch of the server's log, oldest line first. + * + * @param olderFrom where the log's older lines end, to ask for them next; 0 once the start is reached + */ +public record ServerLogPage(List entries, long olderFrom) { + + public boolean hasOlder() { + return olderFrom > 0; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerModel.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerModel.java new file mode 100644 index 0000000..a72b6a1 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerModel.java @@ -0,0 +1,612 @@ +package eu.lixko.ts3j.client.net; + +import eu.lixko.ts3j.client.net.ban.BanEntry; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * The current server state (channels + clients), updated from ts3j's event thread and read + * from the UI. The maps are guarded by the instance; the {@link ChannelNode}s and + * {@link ClientEntry}s handed out are live, with volatile fields, so a reader sees each value + * as it is now but not several of them changed together. + */ +public final class ServerModel { + + private final Map channels = new LinkedHashMap<>(); + private final Map clients = new LinkedHashMap<>(); + private final Map serverGroups = new LinkedHashMap<>(); + private final Map channelGroups = new LinkedHashMap<>(); + /** + * Permission id -> name, learned from the server's {@code permissionlist} response. + * Entries carry no id of their own: TS3 numbers them by position in the response, + * starting at 1, and the empty "group_id_end" separator records marking category + * boundaries don't count toward that position, so only {@link #putPermissionName} + * advances it. + */ + private final Map permissionNames = new LinkedHashMap<>(); + private final Map permissionIds = new HashMap<>(); + private static final int FIRST_PERMISSION_ID = 1; + private int nextPermissionId = FIRST_PERMISSION_ID; + /** Permission id -> the local client's resolved value, from {@code notifyclientneededpermissions}. */ + private final Map selfPermissionValues = new LinkedHashMap<>(); + /** The local client's {@link #UNREPORTED_PERMISSIONS}, which the needed permissions leave out; absent until known. */ + private final Map unreportedValues = new HashMap<>(); + private String serverName = "TeamSpeak Server"; + /** The {@code virtualserver_*} properties from {@code initserver}, kept up to date by server edits. */ + private final Map serverProperties = new HashMap<>(); + /** The channel group everyone starts in, e.g. "Guest" — not worth offering to (re)assign. */ + private int defaultChannelGroupId; + + public synchronized void clear() { + channels.clear(); + clients.clear(); + serverGroups.clear(); + channelGroups.clear(); + permissionNames.clear(); + permissionIds.clear(); + nextPermissionId = FIRST_PERMISSION_ID; + selfPermissionValues.clear(); + unreportedValues.clear(); + serverProperties.clear(); + defaultChannelGroupId = 0; + } + + // ---- groups ---- + + public synchronized void putServerGroup(Group group) { + if (group != null && group.name != null) serverGroups.put(group.id, group); + } + + public synchronized void putChannelGroup(Group group) { + if (group != null && group.name != null) channelGroups.put(group.id, group); + } + + public synchronized Group channelGroup(int id) { + return channelGroups.get(id); + } + + public synchronized String channelGroupName(int id) { + Group g = channelGroups.get(id); + return g == null ? null : g.name; + } + + public synchronized Group serverGroup(int id) { + return serverGroups.get(id); + } + + /** Resolves a client's server-group ids to groups, ordered for display. */ + public synchronized List serverGroupsOf(int[] ids) { + List groups = new ArrayList<>(); + if (ids != null) { + for (int id : ids) { + Group g = serverGroups.get(id); + if (g != null) groups.add(g); + } + } + groups.sort(Comparator.comparingInt((Group g) -> g.sortId).thenComparingInt(g -> g.id)); + return groups; + } + + /** Resolves server-group ids to their names, keeping unknown ids as "#id". */ + public synchronized List serverGroupNames(int[] ids) { + List names = new ArrayList<>(); + if (ids != null) { + for (int id : ids) { + Group g = serverGroups.get(id); + names.add(g != null ? g.name : "#" + id); + } + } + return names; + } + + /** Regular (non-template, non-query) server groups, ordered for display. */ + public synchronized List allServerGroups() { + return regularGroups(serverGroups); + } + + /** Regular (non-template, non-query) channel groups, ordered for display. */ + public synchronized List allChannelGroups() { + return regularGroups(channelGroups); + } + + private static List regularGroups(Map groups) { + List list = new ArrayList<>(); + for (Group g : groups.values()) { + if (g.isRegular()) list.add(g); + } + list.sort(Comparator.comparingInt((Group g) -> g.sortId).thenComparingInt(g -> g.id)); + return list; + } + + // ---- permissions ---- + + /** Records the next named entry of a {@code permissionlist} response; ignores separators. */ + public synchronized void putPermissionName(String name) { + if (name == null || name.isEmpty()) return; + permissionNames.put(nextPermissionId, name); + permissionIds.putIfAbsent(name, nextPermissionId); + nextPermissionId++; + } + + public synchronized void putSelfPermissionValue(int permId, int value) { + selfPermissionValues.put(permId, value); + } + + /** Whether the server's {@code permissionlist} has arrived, so ids can be named at all. */ + public synchronized boolean hasPermissionNames() { + return !permissionNames.isEmpty(); + } + + /** The name the server gave permission id {@code id}, or {@code null} if unknown. */ + public synchronized String permissionName(int id) { + return permissionNames.get(id); + } + + /** + * The local client's resolved value for a named permission (e.g. + * {@code "i_group_member_add_power"}), or {@code 0} if it isn't known + * yet (the {@code permissionlist} request is still in flight, or the server + * never reported a non-default value for it). + */ + public synchronized int selfPermissionValue(String name) { + return selfPermissionValue(name, 0); + } + + /** As {@link #selfPermissionValue(String)}, with {@code absent} for a permission not (yet) reported. */ + public synchronized int selfPermissionValue(String name, int absent) { + Integer id = permissionIds.get(name); + Integer value = id == null ? null : selfPermissionValues.get(id); + return value == null ? absent : value; + } + + /** + * The permissions {@code notifyclientneededpermissions} never carries, not even for an admin; + * they have to be asked for with {@code permget}. + */ + public static final List UNREPORTED_PERMISSIONS = List.of("i_client_move_power", + "i_client_kick_from_channel_power", "i_client_kick_from_server_power", "i_client_ban_power", + "b_client_complain_delete", "b_client_complain_delete_own"); + + /** Takes on the answer to asking for {@link #UNREPORTED_PERMISSIONS}; those it leaves out count as 0. */ + public synchronized void setUnreportedPermissions(Map values) { + unreportedValues.clear(); + unreportedValues.putAll(values); + } + + /** One of {@link #UNREPORTED_PERMISSIONS}; 0 until known, or when the server would not tell. */ + public synchronized int selfPower(String name) { + return unreportedValues.getOrDefault(name, 0); + } + + // ---- what the local client may do ---- + + /** + * Whether we hold a permission. Until the server has named its permissions nothing can + * be resolved, so everything is offered and the server is left to refuse. + */ + public synchronized boolean permits(String permission) { + return !hasPermissionNames() || selfPermissionValue(permission) > 0; + } + + /** + * Whether we may delete all of {@code bans}: any ban with {@code b_client_ban_delete}, + * only our own with {@code b_client_ban_delete_own}. + * + * @param selfUid our unique identifier, which is how a ban names its creator + */ + public synchronized boolean canDeleteBans(Collection bans, String selfUid) { + if (permits("b_client_ban_delete")) return true; + if (!permits("b_client_ban_delete_own")) return false; + return bans.stream().allMatch(b -> b.createdBy(selfUid)); + } + + /** + * Whether we may remove all of {@code complaints}: any with {@code b_client_complain_delete}, + * only those we filed with {@code b_client_complain_delete_own}. + */ + public synchronized boolean canDeleteComplaints(Collection complaints, int selfDbId) { + if (selfPower("b_client_complain_delete") > 0) return true; + if (selfPower("b_client_complain_delete_own") <= 0) return false; + return complaints.stream().allMatch(c -> c.fromDbId() == selfDbId); + } + + /** Whether we may rewrite {@code ban}: that is deleting it and creating its replacement. */ + public synchronized boolean canEditBan(BanEntry ban, String selfUid) { + return permits("b_client_ban_create") && canDeleteBans(List.of(ban), selfUid); + } + + /** {@code i_client_ban_max_bantime}: the longest ban we may hand out in seconds; 0 or -1 for no limit. */ + public synchronized long maxBanSeconds() { + return selfPermissionValue("i_client_ban_max_bantime"); + } + + /** + * Whether the local client has enough power to assign {@code group}, or to take it + * away when {@code assigned}: the add power always gates it, and the remove power + * additionally gates a group already held. {@code -1} is TS3's "unlimited" sentinel on + * either side: an unlimited local power always passes, and a group that needs + * unlimited power can only be touched by a local client that has it. + */ + public synchronized boolean canToggleGroup(Group group, boolean assigned) { + return hasPower(group.neededMemberAddPower, selfPermissionValue("i_group_member_add_power")) + && (!assigned || hasPower(group.neededMemberRemovePower, + selfPermissionValue("i_group_member_remove_power"))); + } + + /** Every regular server group, with whether {@code client} is in it and whether we may change that. */ + public synchronized List serverGroupChoices(ClientEntry client) { + List out = new ArrayList<>(); + for (Group g : allServerGroups()) { + boolean assigned = client.inServerGroup(g.id); + out.add(new GroupChoice(g, assigned, canToggleGroup(g, assigned))); + } + return out; + } + + /** Every regular channel group, with whether it is {@code client}'s and whether we may make it so. */ + public synchronized List channelGroupChoices(ClientEntry client) { + List out = new ArrayList<>(); + for (Group g : allChannelGroups()) { + boolean assigned = client.channelGroupId == g.id; + out.add(new GroupChoice(g, assigned, canToggleGroup(g, assigned))); + } + return out; + } + + /** The regular server or channel groups we have the power to put someone in, so may make a privilege key for. */ + public synchronized List privilegeKeyGroups(boolean channelGroups) { + List out = new ArrayList<>(); + for (Group g : channelGroups ? allChannelGroups() : allServerGroups()) { + if (canToggleGroup(g, false)) out.add(g); + } + return out; + } + + private static boolean hasPower(int needed, int own) { + if (own == -1) return true; + if (needed == -1) return false; + return own >= needed; + } + + /** + * Whether a channel shows in the tree at all — it doesn't while we are not subscribed + * to it (e.g. it needs more subscribe power than we have). + */ + public synchronized boolean isChannelVisible(int channelId) { + ChannelNode channel = channels.get(channelId); + return channel != null && channel.subscribed; + } + + /** + * Whether we can expect a join to succeed: the channel must be visible to us, and + * not already full. This can't account for a join-power permission requirement — + * unlike group membership, TS3 doesn't expose a channel's join-power threshold as + * a plain property, only as a permission resolved through channel/channel-group/ + * server-group inheritance, which isn't something a regular client can query. + */ + public synchronized boolean canJoinChannel(int channelId) { + ChannelNode channel = channels.get(channelId); + if (channel == null || !channel.subscribed) return false; + if (channel.maxClients < 0) return true; + int inside = 0; + for (ClientEntry c : clients.values()) { + if (c.channelId == channelId && !c.isQuery()) inside++; + } + return inside < channel.maxClients; + } + + public synchronized String getServerName() { + return serverName; + } + + public synchronized void setServerName(String name) { + if (name != null && !name.isEmpty()) this.serverName = name; + } + + /** Takes on the server properties among {@code properties}, keeping the others. */ + public synchronized void putServerProperties(Map properties) { + properties.forEach((key, value) -> { + // An empty property comes as a bare key, without a value. + if (key.startsWith("virtualserver_")) serverProperties.put(key, value == null ? "" : value); + }); + } + + /** @return the server property, empty when unknown */ + public synchronized String serverProperty(String key) { + return serverProperties.getOrDefault(key, ""); + } + + /** The server's own icon, 0 when it has none. */ + public synchronized long serverIconId() { + return IconRepository.parseId(serverProperty("virtualserver_icon_id")); + } + + /** The button the server puts in the toolbar's corner, or {@code null} when it has none. */ + public synchronized HostButton hostButton() { + return HostButton.of(serverProperty("virtualserver_hostbutton_url"), + serverProperty("virtualserver_hostbutton_gfx_url"), + serverProperty("virtualserver_hostbutton_tooltip")); + } + + public synchronized int defaultChannelGroupId() { + return defaultChannelGroupId; + } + + public synchronized void setDefaultChannelGroupId(int id) { + this.defaultChannelGroupId = id; + } + + // ---- channels ---- + + public synchronized ChannelNode putChannel(int id, String name, int parentId, int order) { + ChannelNode c = channels.computeIfAbsent(id, k -> new ChannelNode(id, name)); + if (name != null) c.name = name; + c.parentId = parentId; + c.order = order; + return c; + } + + public synchronized ChannelNode getChannel(int id) { + return channels.get(id); + } + + /** + * Marks the channel we are in as subscribed. The server tells us about it along with + * everything else there, but never announces the subscription for the channel we + * start out in, although it stays subscribed after we leave it. + */ + public synchronized void enteredChannel(int id) { + ChannelNode channel = channels.get(id); + if (channel != null) channel.subscribed = true; + } + + public synchronized void removeChannel(int id) { + ChannelNode c = channels.remove(id); + if (c == null) return; + // Whatever followed it now follows its predecessor. + for (ChannelNode o : channels.values()) { + if (o.parentId == c.parentId && o.order == id) o.order = c.order; + } + } + + /** + * Places a channel after {@code newOrder} (0 = first) under {@code newParentId}, + * repairing the sibling links the server does not re-announce: the channel that + * used to follow it, and the one that follows it now. + */ + public synchronized void relinkChannel(int cid, int newParentId, int newOrder) { + ChannelNode c = channels.get(cid); + if (c == null) return; + for (ChannelNode o : channels.values()) { + if (o.id == cid) continue; + if (o.parentId == c.parentId && o.order == cid) o.order = c.order; + } + for (ChannelNode o : channels.values()) { + if (o.id == cid) continue; + if (o.parentId == newParentId && o.order == newOrder) o.order = cid; + } + c.parentId = newParentId; + c.order = newOrder; + } + + /** + * The channels sharing a parent with {@code channelId}, in the order they appear in the + * tree and excluding the channel itself — what the editor offers as places to sort after. + */ + public synchronized List siblingsOf(int channelId) { + ChannelNode channel = channels.get(channelId); + if (channel == null) return new ArrayList<>(); + // Ordered with the channel still in place: the order links form a chain, and + // pulling a link out of it first would strand everything below. + List siblings = childrenOf(channel.parentId); + siblings.remove(channel); + return siblings; + } + + /** + * The channels directly below {@code parentId} (0 being the top level), in the order + * they appear in the tree — what a new channel can be sorted after. + */ + public synchronized List childrenOf(int parentId) { + List children = new ArrayList<>(); + for (ChannelNode c : channels.values()) { + if (c.parentId == parentId) children.add(c); + } + sortSiblings(children); + return children; + } + + /** Every channel, depth first in the order the tree shows them. */ + public synchronized List channelsInTreeOrder() { + List out = new ArrayList<>(); + addInTreeOrder(0, out); + return out; + } + + private void addInTreeOrder(int parentId, List out) { + for (ChannelNode c : childrenOf(parentId)) { + out.add(c); + addInTreeOrder(c.id, out); + } + } + + /** The channel of that exact name directly below {@code parentId}, or {@code null}. */ + public synchronized ChannelNode findChannelByName(int parentId, String name) { + for (ChannelNode c : channels.values()) { + if (c.parentId == parentId && c.name.equals(name)) return c; + } + return null; + } + + /** The "/"-separated path of a channel from the root, e.g. {@code "Lobby/Games"}. */ + public synchronized String channelPath(int id) { + ChannelNode c = channels.get(id); + if (c == null) return ""; + StringBuilder sb = new StringBuilder(); + for (int guard = 0; c != null && guard < 64; guard++) { + if (sb.length() > 0) sb.insert(0, '/'); + sb.insert(0, c.name == null ? "" : c.name); + c = channels.get(c.parentId); + } + return sb.toString(); + } + + /** + * Resolves a channel reference as stored in a bookmark: either a "/"-separated + * path (matched case-insensitively) or {@code "/"}. + * + * @return the channel, or {@code null} if the server has no such channel + */ + public synchronized ChannelNode findChannelByPath(String path) { + if (path == null) return null; + String trimmed = path.trim(); + while (trimmed.startsWith("/")) trimmed = trimmed.substring(1); + while (trimmed.endsWith("/")) trimmed = trimmed.substring(0, trimmed.length() - 1); + if (trimmed.isEmpty()) return null; + + if (trimmed.chars().allMatch(Character::isDigit)) { + ChannelNode byId = channels.get(Integer.parseInt(trimmed)); + if (byId != null) return byId; + } + for (ChannelNode c : channels.values()) { + if (channelPath(c.id).equalsIgnoreCase(trimmed)) return c; + } + // Fall back to a plain name match so a bookmark keeps working when the + // channel is moved within the tree. + for (ChannelNode c : channels.values()) { + if (c.name != null && c.name.equalsIgnoreCase(trimmed)) return c; + } + return null; + } + + // ---- clients ---- + + public synchronized ClientEntry putClient(int id, String nickname, int channelId) { + ClientEntry c = clients.computeIfAbsent(id, k -> new ClientEntry(id, nickname)); + if (nickname != null) c.nickname = nickname; + c.channelId = channelId; + return c; + } + + public synchronized ClientEntry getClient(int id) { + return clients.get(id); + } + + public synchronized void removeClient(int id) { + clients.remove(id); + } + + /** A snapshot of every client on the server. */ + public synchronized List allClients() { + return new ArrayList<>(clients.values()); + } + + public synchronized ClientEntry findClientByUniqueId(String uniqueId) { + if (uniqueId == null || uniqueId.isEmpty()) return null; + for (ClientEntry c : clients.values()) { + if (uniqueId.equals(c.uniqueId)) return c; + } + return null; + } + + /** An online client by its database id, or {@code null} if none is visible. */ + public synchronized ClientEntry findClientByDatabaseId(int databaseId) { + if (databaseId <= 0) return null; + for (ClientEntry c : clients.values()) { + if (c.databaseId == databaseId) return c; + } + return null; + } + + public synchronized ClientEntry findClientByName(String name) { + for (ClientEntry c : clients.values()) { + if (c.nickname != null && c.nickname.equals(name)) return c; + } + return null; + } + + /** + * Builds an ordered forest of channels (each with its clients attached), sorted + * by TS3's channel order chain and then by client talk power / name. + * + * @return the list of root channels (parentId == 0) + */ + public synchronized List buildTree() { + // Fresh lists, published whole: whoever still walks the previous tree keeps a consistent one. + Map> children = new HashMap<>(); + Map> inside = new HashMap<>(); + List roots = new ArrayList<>(); + for (ChannelNode c : channels.values()) { + ChannelNode parent = channels.get(c.parentId); + if (c.parentId == 0 || parent == null) { + roots.add(c); + } else { + children.computeIfAbsent(parent.id, id -> new ArrayList<>()).add(c); + } + } + for (ClientEntry cl : clients.values()) { + if (cl.isQuery()) continue; // hide server-query clients from the tree + if (channels.containsKey(cl.channelId)) { + inside.computeIfAbsent(cl.channelId, id -> new ArrayList<>()).add(cl); + } + } + + Comparator byClient = Comparator + .comparingInt((ClientEntry c) -> -c.talkPower) + .thenComparing(c -> c.nickname == null ? "" : c.nickname.toLowerCase()); + + sortSiblings(roots); + for (ChannelNode c : channels.values()) { + List below = children.getOrDefault(c.id, List.of()); + sortSiblings(below); + c.children = List.copyOf(below); + List members = inside.getOrDefault(c.id, List.of()); + if (members.size() > 1) members.sort(byClient); + c.clients = List.copyOf(members); + } + return roots; + } + + /** + * Orders one set of sibling channels in place. TS3 stores the position as + * {@code channel_order} = the id of the channel above it (0 = topmost), so the + * siblings form a linked list rather than a sortable key. + */ + private static void sortSiblings(List siblings) { + if (siblings.size() < 2) return; + Map byPredecessor = new LinkedHashMap<>(); + for (ChannelNode c : siblings) byPredecessor.putIfAbsent(c.order, c); + + List ordered = new ArrayList<>(siblings.size()); + java.util.Set placed = new java.util.HashSet<>(); + for (int key = 0; ; ) { + ChannelNode next = byPredecessor.get(key); + if (next == null || !placed.add(next.id)) break; + ordered.add(next); + key = next.id; + } + // A broken chain (duplicate or dangling links) leaves stragglers; keep them + // rather than dropping channels from the tree. + for (ChannelNode c : siblings) { + if (!placed.contains(c.id)) ordered.add(c); + } + siblings.clear(); + siblings.addAll(ordered); + } + + public synchronized int channelCount() { + return channels.size(); + } + + public synchronized int clientCount() { + int n = 0; + for (ClientEntry c : clients.values()) if (!c.isQuery()) n++; + return n; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Spacers.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Spacers.java new file mode 100644 index 0000000..d1ca382 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Spacers.java @@ -0,0 +1,83 @@ +package eu.lixko.ts3j.client.net; + + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Parses TeamSpeak 3 "spacer" channel names — cosmetic root channels used as + * separators, e.g. {@code [spacer0]---}, {@code [*spacer1]=}, {@code [cspacer]Rules}. + * The tag selects alignment ({@code l}/{@code c}/{@code r}) or fill ({@code *}). + */ +public final class Spacers { + + /** + * A parsed spacer name. + * + * @param align 'l', 'c', 'r', or '*' (repeat the caption to fill) + */ + public record Spacer(char align, String caption) { + } + + /** The tag's identifying part, which is what keeps two spacers' names apart. */ + private static final Pattern TAG = Pattern.compile("^\\[(?:\\*|[lcr])?spacer([^\\]]*)\\]"); + + private static final Pattern PATTERN = + Pattern.compile("^\\[(\\*|[lcr])?spacer[^\\]]*\\](.*)$"); + + private Spacers() { + } + + /** Returns spacer info if {@code channelName} is a spacer, else {@code null}. */ + public static Spacer parse(String channelName) { + if (channelName == null) return null; + Matcher m = PATTERN.matcher(channelName); + if (!m.matches()) return null; + String tag = m.group(1); + char align = (tag == null || tag.isEmpty()) ? 'l' : tag.charAt(0); + return new Spacer(align, m.group(2)); + } + + public static boolean isSpacer(String channelName) { + return parse(channelName) != null; + } + + /** + * A spacer name no channel among {@code siblings} is using: {@code [spacerN]} with the + * lowest free N. TeamSpeak needs channel names to be unique, and the number in the tag + * is how spacers — which usually all read the same — get away with it. + */ + public static String freeName(List siblings) { + Set taken = new HashSet<>(); + for (ChannelNode sibling : siblings) { + Matcher m = TAG.matcher(sibling.name == null ? "" : sibling.name); + if (m.find()) taken.add(m.group(1)); + } + for (int n = 0; ; n++) { + if (taken.add(Integer.toString(n))) return "[spacer" + n + "]"; + } + } + + /** Builds the visible label for a spacer at roughly the given character width. */ + public static String render(Spacer s, int width) { + String caption = s.caption() == null ? "" : s.caption(); + if (s.align() == '*') { + if (caption.isEmpty()) return ""; + StringBuilder sb = new StringBuilder(); + while (sb.length() < width) sb.append(caption); + return sb.substring(0, Math.max(caption.length(), Math.min(sb.length(), width))); + } + if (s.align() == 'c') { + int pad = Math.max(0, (width - caption.length()) / 2); + return " ".repeat(pad) + caption; + } + if (s.align() == 'r') { + int pad = Math.max(0, width - caption.length()); + return " ".repeat(pad) + caption; + } + return caption; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java new file mode 100644 index 0000000..14902b1 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java @@ -0,0 +1,1997 @@ +package eu.lixko.ts3j.client.net; + +import com.github.manevolent.ts3j.api.Client; +import com.github.manevolent.ts3j.command.CommandException; +import com.github.manevolent.ts3j.command.MultiCommand; +import com.github.manevolent.ts3j.command.SingleCommand; +import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; +import com.github.manevolent.ts3j.event.*; +import com.github.manevolent.ts3j.identity.LocalIdentity; +import com.github.manevolent.ts3j.identity.Uid; +import com.github.manevolent.ts3j.protocol.ProtocolRole; +import com.github.manevolent.ts3j.protocol.packet.PacketBody1VoiceWhisper; +import com.github.manevolent.ts3j.protocol.socket.client.LocalTeamspeakClientSocket; +import com.github.manevolent.ts3j.util.Ts3Crypt; +import eu.lixko.ts3j.client.audio.AudioBackend; +import eu.lixko.ts3j.client.audio.VoiceInput; +import eu.lixko.ts3j.client.audio.VoiceOutput; +import eu.lixko.ts3j.client.chatlog.ChatLogScope; +import eu.lixko.ts3j.client.chatlog.ChatLogStore; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.contacts.Contact; +import eu.lixko.ts3j.client.contacts.ContactStore; +import eu.lixko.ts3j.client.net.avatar.Avatar; +import eu.lixko.ts3j.client.net.avatar.AvatarNaming; +import eu.lixko.ts3j.client.net.avatar.AvatarRepository; +import eu.lixko.ts3j.client.net.filetransfer.FileTransfer; +import eu.lixko.ts3j.client.net.filetransfer.FileTransferManager; +import eu.lixko.ts3j.client.net.ban.BanEntry; +import eu.lixko.ts3j.client.net.ban.BanRule; +import eu.lixko.ts3j.client.net.filetransfer.RemoteFile; +import eu.lixko.ts3j.client.recording.VoiceRecorder; +import eu.lixko.ts3j.client.sound.SoundEvent; +import eu.lixko.ts3j.client.sound.SoundNotifier; +import eu.lixko.ts3j.client.text.TsLink; + +import java.io.File; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import java.util.function.Consumer; + +/** + * High-level facade that ties the ts3j protocol socket to the audio subsystem and + * the {@link ServerModel}, translating protocol events into {@link ConnectionListener} + * callbacks for the UI. + */ +public final class TeamspeakConnection implements TS3Listener { + + /** Upper bound for a group icon; anything larger is not an icon. Also used by {@link ChannelAdmin}. */ + static final int MAX_ICON_BYTES = 1024 * 1024; + + /** The longest reason the protocol carries with a kick. */ + public static final int KICK_REASON_LIMIT = 40; + /** The longest reason a complaint may carry. */ + public static final int COMPLAINT_REASON_LIMIT = 200; + /** The longest subject and body an offline message may carry, in characters. */ + public static final int OFFLINE_MESSAGE_SUBJECT_LIMIT = 200; + public static final int OFFLINE_MESSAGE_LIMIT = 4096; + /** What {@link #searchDatabaseClients} reports when the server will not let us search. */ + public static final String SEARCH_NOT_PERMITTED = + "You have no permission to search for users on this server, so you can only use contacts or unique IDs."; + + /** The protocol's reason ids for the two flavours of clientkick. */ + private static final int REASON_KICK_CHANNEL = 4; + private static final int REASON_KICK_SERVER = 5; + + private static final int ERROR_PERMISSIONS_CLIENT_INSUFFICIENT = 0x0a08; + private static final int ERROR_PERMISSIONS_INSUFFICIENT_GROUP_POWER = 0x0a09; + private static final int ERROR_PERMISSIONS_INSUFFICIENT_PERMISSION_POWER = 0x0a0a; + + /** Shortest gap between two "you are talking while muted" reminders. */ + private static final long MUTED_TALK_COOLDOWN_NANOS = 5_000_000_000L; + + /** + * How long the handshake and initial download may take. That download includes the whole + * channel list, which on a big server over a lossy link (mobile data) takes a while. + */ + private static final long CONNECT_TIMEOUT_MS = 30_000L; + + private final Settings settings; + private final AudioBackend audio; + private final ServerModel model = new ServerModel(); + /** Package-private: read directly by {@link ConnectionEventHandler}. */ + final ConnectionListener ui; + private final IconRepository icons; + private final AvatarRepository avatars; + /** Package-private: read directly by {@link ConnectionEventHandler}. */ + final SoundNotifier sounds; + /** Friends, blocked clients and their per-client filters; also read by {@link ConnectionEventHandler}. */ + final ContactStore contacts; + /** The {@link TS3Listener} side of this connection; see its class doc. */ + private final ConnectionEventHandler events = new ConnectionEventHandler(this); + /** Builds {@code getconnectioninfo} snapshots; also package-private for {@link ConnectionEventHandler}. */ + final ConnectionStatsCollector stats = new ConnectionStatsCollector(this); + /** Channel editing and the server's icon store; package-private for {@link ConnectionEventHandler}. */ + final ChannelAdmin channels = new ChannelAdmin(this); + /** The server's ban list, privilege keys, complaints and log; also package-private for {@link ConnectionEventHandler}. */ + final BanAdmin bans = new BanAdmin(this); + final PrivilegeKeyAdmin privilegeKeys = new PrivilegeKeyAdmin(this); + final ComplaintAdmin complaints = new ComplaintAdmin(this); + final ServerLogAdmin serverLog = new ServerLogAdmin(this); + /** Our offline message inbox; package-private for {@link ConnectionEventHandler}. */ + final OfflineMessageAdmin offlineMessages = new OfflineMessageAdmin(this); + private final AvatarAdmin avatarAdmin = new AvatarAdmin(this); + + /* + * Set up by the connect thread and torn down by whichever thread notices the end; read from + * the UI, event and action threads, so each reader copies the field before using it. + */ + /** Package-private: read directly by {@link ConnectionStatsCollector}. */ + volatile LocalTeamspeakClientSocket client; + /** The client whose whisper we heard last, to reply to; 0 for none yet. */ + private volatile int lastWhisperer; + private volatile VoiceInput microphone; + private volatile VoiceOutput playback; + private volatile LocalIdentity identity; + private volatile FileTransferManager fileTransfers; + private volatile ChatLogStore chatLogs; + /** The recording in progress; guarded by this connection. */ + private VoiceRecorder recorder; + /** + * Runs ts3j's event callbacks. Supplying it ourselves (rather than leaving ts3j to make + * its own) is what lets {@link #awaitEventsProcessed()} tell when everything the server + * has already sent has been handled. Closed together with the socket. + */ + private volatile ExecutorService eventExecutor; + /** Runs this connection's requests to the server; created on connect, shut down with the socket. */ + private volatile ExecutorService actions; + + private volatile boolean connected; + /** + * The connect in progress. A disconnect clears it and a newer connect replaces it, which + * tells a superseded attempt that is still failing not to clean up after itself. + */ + private volatile Object connectAttempt; + private volatile int selfClientId = -1; + /** Package-private: read directly by {@link ConnectionStatsCollector}. */ + volatile long connectedAtMs; + private volatile String serverHost; + private volatile int serverPort; + + /** + * Whether this connection owns the capture device. Only one connection may + * capture at a time, so the frontend hands the microphone to a single + * connection and the others keep their (idle) input pipeline. + */ + private volatile boolean microphoneActive; + + /** Speakers muted: only actions marked important are still heard. */ + private volatile boolean deafened; + /** Set while we are leaving on purpose, to tell a clean disconnect from a drop. */ + private volatile boolean leaving; + /** Guards against announcing the same disconnect from both the event and the teardown. */ + private volatile boolean disconnectAnnounced = true; + private volatile long lastMutedTalkNanos; + /** The server's error id for why the last connect was refused; 0 when it was not. */ + private volatile int connectErrorId; + + public TeamspeakConnection(Settings settings, AudioBackend audio, ConnectionListener ui, + SoundNotifier sounds, ContactStore contacts) { + this.settings = settings; + this.audio = audio; + this.ui = ui; + this.sounds = sounds; + this.contacts = contacts; + this.icons = new IconRepository(this::fetchIcon, ui::onIconsUpdated); + this.avatars = new AvatarRepository(this::fetchAvatar, ui::onInfoUpdated); + } + + public ServerModel getModel() { + return model; + } + + public boolean isConnected() { + return connected; + } + + public int getSelfClientId() { + return selfClientId; + } + + public VoiceInput getMicrophone() { + return microphone; + } + + public VoiceOutput getPlayback() { + return playback; + } + + /** + * The error id the server refused the last connect with ({@code 3329} for a ban, + * for one), or 0 when it was not refused or did not get that far. + */ + public int getConnectErrorId() { + return connectErrorId; + } + + /** The identity this connection authenticated with. */ + public LocalIdentity getIdentity() { + return identity; + } + + /** Address this connection was last asked to connect to. */ + public String getServerHost() { + return serverHost == null ? "" : serverHost; + } + + public int getServerPort() { + return serverPort; + } + + /** + * Gives this connection the capture device, or takes it away. Capturing only + * starts once connected; calling this before or during a connect is fine, the + * requested state is applied as soon as the microphone exists. + */ + public synchronized void setMicrophoneActive(boolean active) { + microphoneActive = active; + applyMicrophoneState(); + } + + public boolean isMicrophoneActive() { + return microphoneActive; + } + + /** Starts or stops capture to match {@link #microphoneActive}. */ + private synchronized void applyMicrophoneState() { + VoiceInput mic = microphone; + if (mic == null || !connected) return; + try { + if (microphoneActive) mic.start(); + else mic.stop(); + } catch (Exception e) { + ui.onError("Microphone unavailable: " + rootMessage(e)); + } + pushInputHardware(); + } + + /** + * Reports whether the capture device is actually available on this connection, so + * other clients see "Microphone Disabled" rather than plain silence while another + * tab holds it. {@code clientinit} always claims hardware input, so this is what + * corrects that once tabs start sharing one microphone. + */ + private void pushInputHardware() { + boolean hardware = microphoneActive; + updateSelf(self -> self.inputHardware = hardware); + selfUpdate(cmd -> + cmd.add(new CommandSingleParameter("client_input_hardware", hardware ? "1" : "0")), + "Microphone hardware status update failed"); + } + + // ---- connection lifecycle ---- + + /** + * Connects in the background, joining a specific channel instead of the server's + * default one. + * + * @param phoneticNickname how text-to-speech should say the nickname; may be empty + * @param identity identity to authenticate with; see {@link eu.lixko.ts3j.client.config.IdentityStore} + * @param channel channel path ("Lobby/Games") or "/<channelId>"; null/empty for the default channel + * @param channelPassword password for that channel, or null if it has none + */ + public void connect(String address, int port, String nickname, String phoneticNickname, String password, + LocalIdentity identity, String channel, String channelPassword) { + new Thread(() -> doConnect(address, port, nickname, phoneticNickname, password, identity, channel, + channelPassword), "ts3j-connect").start(); + } + + private void doConnect(String address, int port, String nickname, String phoneticNickname, String password, + LocalIdentity withIdentity, String channel, String channelPassword) { + Object attempt = new Object(); + connectAttempt = attempt; + connectErrorId = 0; + // A socket or audio line an earlier connect left behind must not outlive it. + connected = false; + safeCleanup(); + try { + identity = withIdentity; + serverHost = address; + serverPort = port; + + model.clear(); + lastWhisperer = 0; + playback = audio.createOutput(settings); + playback.setMasterVolume(settings.effectiveOutputVolume()); + playback.setReceiveBuffer(settings.receiveBuffer); + playback.setTalkListener((clientId, talking) -> { + ClientEntry c = model.getClient(clientId); + if (c != null) c.talking = talking; + if (c != null && inOwnChannel(c.channelId)) { + sound(talking ? SoundEvent.SPECIAL_MIC_CLICK_OTHER_ON + : SoundEvent.SPECIAL_MIC_CLICK_OTHER_OFF, clientVars(clientId, null)); + } + ui.onTalkStateChanged(clientId, talking); + }); + + microphone = audio.createInput(settings); + microphone.setTalkListener(talking -> { + if (selfClientId >= 0) { + ClientEntry c = model.getClient(selfClientId); + if (c != null) c.talking = talking; + sound(talking ? SoundEvent.SPECIAL_MIC_CLICK_SELF_ON + : SoundEvent.SPECIAL_MIC_CLICK_SELF_OFF); + ui.onTalkStateChanged(selfClientId, talking); + } + }); + microphone.setMutedTalkListener(this::onTalkingWhileMuted); + + client = new LocalTeamspeakClientSocket(); + eventExecutor = Executors.newSingleThreadExecutor(r -> { + Thread t = new Thread(r, "ts3j-events"); + t.setDaemon(true); + return t; + }); + client.setCommandExecutorService(eventExecutor); + actions = Executors.newCachedThreadPool(r -> { + Thread t = new Thread(r, "ts3j-action"); + t.setDaemon(true); + return t; + }); + client.setIdentity(identity); + client.setNickname(nickname); + setIfPresent("client.nickname_phonetic", phoneticNickname); + client.setHWID("ts3jswing-" + Integer.toHexString(nickname.hashCode())); + client.addListener(this); + client.addListener(events); + client.setVoiceHandler(playback::handleVoice); + client.setWhisperHandler(whisper -> { + if (!isWhisperAllowed(whisper.getClientId())) return; + lastWhisperer = whisper.getClientId(); + playback.handleWhisper(whisper); + }); + client.setExceptionHandler(t -> { + // A late packet dispatched after close() rejects on the shut-down + // command executor; harmless during teardown. + if (t instanceof java.util.concurrent.RejectedExecutionException) return; + ui.onError("Network error: " + messageChain(t)); + }); + + applyClientVersion(); + applyDefaultChannel(channel, channelPassword); + + ui.onStatus("Connecting to " + address + ":" + port + "…"); + client.connect(new InetSocketAddress(address, port), + (password == null || password.isEmpty()) ? null : password, + CONNECT_TIMEOUT_MS); + + // Protocol connection established; anything past this point is best-effort. + selfClientId = client.getClientId(); + // Our own row usually arrives among the enter-view events the connect + // handshake carries, i.e. before our id was known here, so it has to be + // marked once it is. + ClientEntry ourselves = model.getClient(selfClientId); + if (ourselves != null) { + ourselves.self = true; + model.enteredChannel(ourselves.channelId); + } + fileTransfers = new FileTransferManager(client, () -> serverHost); + client.setMicrophone(microphone); + icons.retryFailed(); + avatars.retryFailed(); + connected = true; + connectedAtMs = System.currentTimeMillis(); + leaving = false; + disconnectAnnounced = false; + deafened = false; + offlineMessages.reset(); + loadChatLogs(); + ui.onConnected(); + requestPermissionNames(); + requestSelfPowers(); + + ui.onStatus("Retrieving channels…"); + syncAll(); + ui.onModelChanged(); + joinDefaultChannelIfNeeded(channel, channelPassword); + ui.onStatus("Connected to " + model.getServerName()); + sound(SoundEvent.CONNECTION_CONNECTED, serverVars()); + unreadMessagesChanged(0); + + // Only captures if this connection holds the microphone. + applyMicrophoneState(); + } catch (Exception e) { + // Whoever took over reports on their own; cleaning up here would tear down what a newer + // connect has set up in the meantime. + if (connectAttempt != attempt) return; + connected = false; + connectErrorId = refusalId(e); + String failure = "Connection failed: " + rootMessage(e) + versionHint(e); + ui.onError(failure); + safeCleanup(); + // Report the failed attempt as a disconnect too, so the UI leaves the + // "connecting" state and the tab becomes reusable. The status keeps saying why. + ui.onDisconnected("connection failed"); + ui.onStatus(failure); + } + } + + private static int refusalId(Throwable e) { + for (Throwable t = e; t != null; t = t.getCause()) { + if (t instanceof CommandException refusal) return refusal.getErrorId(); + } + return 0; + } + + /** + * "client is modified" is what a server answers when it does not accept the reported + * version: too old for its minimum, not a version it knows for that platform, or a + * signature that does not belong to the two. Easy to run into after editing them by + * hand, and the bare message does not point anywhere. + */ + private String versionHint(Exception e) { + if (!settings.customVersion) return ""; + String message = rootMessage(e); + return message != null && message.contains("client is modified") + ? " — the server did not accept the custom client version; pick a newer one" + + " of the listed versions in Options." + : ""; + } + + /** + * Reports the version and operating system the user configured, which is what + * other clients see in the info panel. Each field falls back to the library's + * built-in one when left empty; the signature has to match the version and + * platform it was issued for, or a server may refuse the connection. + */ + private void applyClientVersion() { + if (!settings.customVersion) return; + setIfPresent("client.version_string", settings.clientVersion); + setIfPresent("client.version_platform", settings.clientPlatform); + setIfPresent("client.version_sign", settings.clientVersionSign); + } + + private void setIfPresent(String option, String value) { + if (value != null && !value.isBlank()) client.setOption(option, value.trim()); + } + + /** + * Asks the server, as part of {@code clientinit}, to place us in a specific + * channel right away instead of the default one. This is the path a real client + * takes for bookmarks, and it avoids being briefly visible in the wrong channel. + */ + private void applyDefaultChannel(String channel, String channelPassword) { + String path = normaliseChannelRef(channel); + if (path == null) return; + client.setOption("client.default_channel", path); + if (channelPassword != null && !channelPassword.isEmpty()) { + client.setOption("client.default_channel_password", Ts3Crypt.hashPassword(channelPassword)); + } + } + + /** + * Fallback for when {@code clientinit} did not put us in the requested channel: + * the path may not have matched exactly, or the channel may have been created + * after the bookmark was saved. Resolves the reference against the now-known + * channel list and moves there. + */ + private void joinDefaultChannelIfNeeded(String channel, String channelPassword) { + if (normaliseChannelRef(channel) == null) return; + LocalTeamspeakClientSocket sock = client; + if (sock == null || !connected) return; // already left again + ChannelNode target = model.findChannelByPath(channel); + if (target == null) { + ui.onError("Channel \"" + channel.trim() + "\" not found on this server."); + return; + } + if (currentChannelId() == target.id) return; // clientinit already put us there + try { + sock.joinChannel(target.id, (channelPassword == null || channelPassword.isEmpty()) + ? null : channelPassword); + } catch (Exception e) { + if (!connected) return; + error("Could not join channel \"" + target.name + "\": ", e); + } + } + + /** + * The channel we are in, taken from the model and, if the client list was not + * readable, asked from the server directly. + * + * @return the channel id, or -1 when unknown + */ + private int currentChannelId() { + ClientEntry self = model.getClient(selfClientId); + if (self != null) return self.channelId; + try { + return client.getClientInfo(selfClientId).getChannelId(); + } catch (Exception e) { + return -1; + } + } + + /** + * @return the channel reference in {@code clientinit} form ("/<id>" for a + * numeric id, otherwise the path), or null when no channel was requested + */ + private static String normaliseChannelRef(String channel) { + if (channel == null) return null; + String path = channel.trim(); + while (path.startsWith("/")) path = path.substring(1); + while (path.endsWith("/")) path = path.substring(0, path.length() - 1); + if (path.isEmpty()) return null; + return path.chars().allMatch(Character::isDigit) ? "/" + path : path; + } + + /** + * Completes the model once connected. Channels and clients already arrived as events + * during {@code connect()}, complete, as the official client gets them. The + * {@code channellist}/{@code clientlist} query commands must not be used to re-read + * them: their rows lack groups, unique ids and away state, and they count heavily + * against the server's flood protection. + */ + private void syncAll() { + try { + client.subscribeAll(); + } catch (Exception e) { + ui.onStatus("Limited subscription: " + rootMessage(e)); + } + // The name comes with initserver; servergetvariables never reports it. + model.setServerName(client.getServerName()); + model.putServerProperties(client.getServerProperties()); + model.setDefaultChannelGroupId( + (int) safeLong(client.getServerProperties().get("virtualserver_default_channel_group"))); + } + + public void disconnect() { + new Thread(() -> disconnectBlocking("Leaving"), "ts3j-disconnect").start(); + } + + /** + * Disconnect synchronously on the calling thread, notifying the UI. Used both + * by the async {@link #disconnect()} and by shutdown paths (Ctrl+C, window + * close) where the JVM must not exit before the leave notification is sent. + */ + public void disconnectBlocking(String reason) { + connectAttempt = null; + leaving = true; + try { + if (client != null) client.disconnect(reason); + } catch (Exception ignored) { + } finally { + safeCleanup(); + connected = false; + announceDisconnect(true); + ui.onDisconnected("You disconnected"); + ui.onStatus("Disconnected"); + } + } + + /** + * Plays the disconnect sound once per connection: leaving on purpose is a + * different action from having the connection drop underneath us, and both the + * socket event and our own teardown can arrive. + */ + private void announceDisconnect(boolean deliberate) { + if (disconnectAnnounced) return; + disconnectAnnounced = true; + sound(deliberate || leaving ? SoundEvent.CONNECTION_DISCONNECTED + : SoundEvent.CONNECTION_LOST_CONNECTION, serverVars()); + } + + /** Reminds the user, at most every few seconds, that the microphone is muted. */ + private void onTalkingWhileMuted() { + if (!settings.mutedTalkWarning) return; + long now = System.nanoTime(); + if (now - lastMutedTalkNanos < MUTED_TALK_COOLDOWN_NANOS) return; + lastMutedTalkNanos = now; + sound(SoundEvent.SPECIAL_TALKING_WHILE_MUTED); + } + + private synchronized void safeCleanup() { + // Finishes the files; there is no server left to tell. + VoiceRecorder rec = recorder; + if (rec != null) { + detachRecorder(); + rec.stop(); + } + VoiceInput mic = microphone; + VoiceOutput out = playback; + LocalTeamspeakClientSocket sock = client; + FileTransferManager ft = fileTransfers; + ExecutorService events = eventExecutor; + ExecutorService pool = actions; + eventExecutor = null; + actions = null; + microphone = null; + playback = null; + client = null; + fileTransfers = null; + chatLogs = null; + selfClientId = -1; + stats.clear(); + + if (ft != null) { + try { + ft.shutdown(); + } catch (Exception ignored) { + } + } + + if (mic != null) { + try { + mic.stop(); + } catch (Exception ignored) { + } + } + if (out != null) { + try { + out.shutdown(); + } catch (Exception ignored) { + } + } + if (sock != null) { + try { + sock.close(); + } catch (Exception ignored) { + } + } + if (events != null) events.shutdownNow(); + if (pool != null) pool.shutdownNow(); + } + + // ---- self actions ---- + + public void setMicMuted(boolean muted) { + VoiceInput mic = microphone; + if (mic != null) mic.setMuted(muted); + sound(muted ? SoundEvent.SOUND_CAPTURE_MUTED : SoundEvent.SOUND_CAPTURE_UNMUTED); + pushSelfFlags(); + } + + /** + * TS3's "Local Mic Mute": silences capture without touching the {@code client_input_muted} + * status the server (and other clients) see, and without a mute/unmute sound. + */ + public void setMicLocalMuted(boolean muted) { + VoiceInput mic = microphone; + if (mic != null) mic.setLocalMuted(muted); + } + + public void setDeafened(boolean deaf) { + // Announce muting while we can still be heard, and unmuting once we can again. + if (deaf) sound(SoundEvent.SOUND_PLAYBACK_MUTED); + deafened = deaf; + VoiceOutput out = playback; + if (out != null) out.setDeafened(deaf); + if (!deaf) sound(SoundEvent.SOUND_PLAYBACK_UNMUTED); + pushSelfFlags(); + } + + private void pushSelfFlags() { + VoiceInput mic = microphone; + VoiceOutput out = playback; + if (mic == null || out == null) return; + boolean micMuted = mic.isMuted(); + boolean deaf = out.isDeafened(); + updateSelf(self -> { + self.inputMuted = micMuted; + self.outputMuted = deaf; + }); + + // Publish the input/output muted flags to the server so others see them. These + // are runtime status, not editable client-database properties, so they go out + // through clientupdate (like nickname/away), not clientedit. + selfUpdate(cmd -> { + cmd.add(new CommandSingleParameter("client_input_muted", micMuted ? "1" : "0")); + cmd.add(new CommandSingleParameter("client_output_muted", deaf ? "1" : "0")); + }, "Mute status update failed"); + } + + public void joinChannel(int channelId, String password) { + act("Could not join channel: ", sock -> + sock.joinChannel(channelId, (password == null || password.isEmpty()) ? null : password)); + } + + /** Moves another client (or ourselves) into a channel. */ + public void moveClient(int clientId, int channelId, String password) { + act("Could not move client: ", sock -> sock.clientMove(clientId, channelId, + (password == null || password.isEmpty()) ? null : password)); + } + + /** Kicks a client out of its channel, back into the server's default one. */ + public void kickFromChannel(int clientId, String reason) { + kick(clientId, REASON_KICK_CHANNEL, reason, "Could not kick client from the channel: "); + } + + /** Kicks a client off the server entirely. */ + public void kickFromServer(int clientId, String reason) { + kick(clientId, REASON_KICK_SERVER, reason, "Could not kick client from the server: "); + } + + private void kick(int clientId, int reasonId, String reason, String errorPrefix) { + act(errorPrefix, sock -> { + SingleCommand cmd = new SingleCommand("clientkick", ProtocolRole.CLIENT); + cmd.add(new CommandSingleParameter("clid", Integer.toString(clientId))); + cmd.add(new CommandSingleParameter("reasonid", Integer.toString(reasonId))); + if (reason != null && !reason.isEmpty()) { + cmd.add(new CommandSingleParameter("reasonmsg", reason)); + } + sock.executeCommand(cmd).complete(); + }); + } + + /** + * Bans a client from the server. + * + * @param seconds how long the ban lasts, or 0 for a permanent one + */ + public void banClient(int clientId, long seconds, String reason) { + act("Could not ban client: ", sock -> sock.banClient(clientId, + seconds <= 0 ? null : (int) Math.min(seconds, Integer.MAX_VALUE), + reason == null || reason.isEmpty() ? null : reason)); + } + + /** + * Re-parents and repositions a channel. + * + * @param orderPredecessorId the channel this one should sit below among its new + * siblings, or 0 to place it first + */ + public void moveChannel(int channelId, int newParentId, int orderPredecessorId) { + ChannelNode channel = model.getChannel(channelId); + // The server refuses channelmove within the same parent ("already member of + // channel"); sorting among the same siblings is an edit of channel_order. + boolean reorder = channel != null && channel.parentId == newParentId; + act("Could not move channel: ", sock -> { + SingleCommand cmd; + if (reorder) { + cmd = new SingleCommand("channeledit", ProtocolRole.CLIENT); + cmd.add(new CommandSingleParameter("cid", Integer.toString(channelId))); + cmd.add(new CommandSingleParameter("channel_order", Integer.toString(orderPredecessorId))); + } else { + cmd = new SingleCommand("channelmove", ProtocolRole.CLIENT); + cmd.add(new CommandSingleParameter("cid", Integer.toString(channelId))); + cmd.add(new CommandSingleParameter("cpid", Integer.toString(newParentId))); + cmd.add(new CommandSingleParameter("order", Integer.toString(orderPredecessorId))); + } + sock.executeCommand(cmd).complete(); + }); + } + + /** + * Asks the server to (re-)send its permission definitions, which arrive as a burst + * of {@code notifypermissionlist} events — the only way to learn permission names, + * since {@code notifyclientneededpermissions} (which resolves our own power for + * them) only ever reports numeric ids. Needed for {@link ServerModel#selfPermissionValue} + * to work; harmless if it's slow or fails, since group-assignment eligibility just + * won't be known yet. + */ + private void requestPermissionNames() { + // Best-effort: the menus fall back to treating unresolved permissions as 0. + attempt(sock -> sock.executeCommand(new SingleCommand("permissionlist", ProtocolRole.CLIENT)).complete()); + } + + /** + * Asks for our own {@link ServerModel#UNREPORTED_PERMISSIONS}, which {@code notifyclientneededpermissions} + * never carries. Asking needs {@code b_client_permissionoverview_own}; refused, we take them + * as none, which is what the groups that lack the one usually have of the others. + */ + void requestSelfPowers() { + List rows = new ArrayList<>(); + for (String name : ServerModel.UNREPORTED_PERMISSIONS) { + rows.add(new SingleCommand("permget", ProtocolRole.CLIENT, new CommandSingleParameter("permsid", name))); + } + submit(sock -> { + Map powers = new HashMap<>(); + for (SingleCommand answer : sock.executeCommand(new MultiCommand("permget", ProtocolRole.CLIENT, rows)).get()) { + Map fields = answer.toMap(); + String name = fields.get("permsid"); + String value = fields.get("permvalue"); + if (name != null && value != null) powers.put(name, Integer.parseInt(value)); + } + model.setUnreportedPermissions(powers); + }, e -> model.setUnreportedPermissions(Map.of())); + } + + /** Assigns or removes a server group for a client (by database id, as {@code servergroupaddclient} needs). */ + public void setClientServerGroup(int clientDatabaseId, int groupId, boolean assign) { + act("Could not " + (assign ? "assign" : "remove") + " server group: ", sock -> { + if (assign) sock.serverGroupAddClient(groupId, clientDatabaseId); + else sock.serverGroupRemoveClient(groupId, clientDatabaseId); + }); + } + + /** Assigns a channel group for a client in the channel it currently sits in. */ + public void setClientChannelGroup(int clientDatabaseId, int channelId, int groupId) { + act("Could not set channel group: ", sock -> { + SingleCommand cmd = new SingleCommand("setclientchannelgroup", ProtocolRole.CLIENT); + cmd.add(new CommandSingleParameter("cgid", Integer.toString(groupId))); + cmd.add(new CommandSingleParameter("cid", Integer.toString(channelId))); + cmd.add(new CommandSingleParameter("cldbid", Integer.toString(clientDatabaseId))); + sock.executeCommand(cmd).complete(); + }); + } + + /** + * Subscribes to (or unsubscribes from) a set of channels in one command. The model + * is left alone: the server answers with the subscription events that update it. + */ + public void setChannelsSubscribed(Collection channelIds, boolean subscribed) { + if (channelIds.isEmpty()) return; + List ids = List.copyOf(channelIds); + String name = subscribed ? "channelsubscribe" : "channelunsubscribe"; + act(subscribed ? "Could not subscribe: " : "Could not unsubscribe: ", sock -> { + List parts = new ArrayList<>(ids.size()); + for (int id : ids) { + parts.add(new SingleCommand(name, ProtocolRole.CLIENT, + new CommandSingleParameter("cid", Integer.toString(id)))); + } + sock.executeCommand(new MultiCommand(name, ProtocolRole.CLIENT, parts)).complete(); + }); + } + + public void sendChannelMessage(String text) { + act("Message failed: ", sock -> { + ClientEntry self = model.getClient(selfClientId); + int cid = self != null ? self.channelId : 0; + sock.sendChannelMessage(cid, text); + persistOutgoingChat(ConnectionListener.ChatScope.CHANNEL, 0, "", text); + sound(SoundEvent.CHAT_SENT_MESSAGE_CHANNEL, channelVars(cid, null)); + }); + } + + public void sendServerMessage(String text) { + act("Message failed: ", sock -> { + sock.sendServerMessage(text); + persistOutgoingChat(ConnectionListener.ChatScope.SERVER, 0, "", text); + sound(SoundEvent.CHAT_SENT_MESSAGE_SERVER, serverVars()); + }); + } + + public void sendPrivateMessage(int clientId, String text) { + act("Message failed: ", sock -> { + sock.sendPrivateMessage(clientId, text); + ClientEntry peer = model.getClient(clientId); + String peerUid = peer != null ? peer.uniqueId : ""; + if (peerUid == null || peerUid.isBlank()) { + try { + Client info = sock.getClientInfo(clientId); + if (info != null) peerUid = info.getUniqueIdentifier(); + } catch (Exception ignored) { + } + } + persistOutgoingChat(ConnectionListener.ChatScope.PRIVATE, clientId, peerUid, text); + sound(SoundEvent.CHAT_SENT_MESSAGE_CLIENT, clientVars(clientId, null)); + }); + } + + public void poke(int clientId, String message) { + act("Poke failed: ", sock -> { + sock.clientPoke(clientId, message); + sound(SoundEvent.OTHER_SENT_POKE, clientVars(clientId, null)); + }); + } + + public void setAway(boolean away, String message) { + sound(away ? SoundEvent.STATUS_SET_AWAY : SoundEvent.STATUS_SET_PRESENT); + updateSelf(self -> { + self.away = away; + self.awayMessage = away && message != null ? message : ""; + }); + selfUpdate(cmd -> { + cmd.add(new CommandSingleParameter("client_away", away ? "1" : "0")); + cmd.add(new CommandSingleParameter("client_away_message", away && message != null ? message : "")); + }, "Away update failed"); + } + + public void setChannelCommander(boolean commander) { + updateSelf(self -> self.channelCommander = commander); + selfUpdate(cmd -> + cmd.add(new CommandSingleParameter("client_is_channel_commander", commander ? "1" : "0")), + "Channel commander update failed"); + } + + /** @param message the reason shown to moderators; ignored when withdrawing the request */ + public void setTalkRequest(boolean request, String message) { + updateSelf(self -> self.talkRequest = request); + selfUpdate(cmd -> { + cmd.add(new CommandSingleParameter("client_talk_request", request ? "1" : "0")); + if (request) cmd.add(new CommandSingleParameter("client_talk_request_msg", message)); + }, "Talk power request failed"); + } + + public void setPhoneticNickname(String phoneticNickname) { + updateSelf(self -> self.phoneticNickname = phoneticNickname); + selfUpdate(cmd -> cmd.add(new CommandSingleParameter("client_nickname_phonetic", phoneticNickname)), + "Setting phonetic nickname failed"); + } + + // ---- recording ---- + + /** + * Starts recording what we hear on this server, our own voice included, and tells the + * server so: other clients see that they are being recorded. + */ + public synchronized VoiceRecorder startRecording(VoiceRecorder.Mode mode, Path file) throws IOException { + VoiceOutput out = playback; + VoiceInput mic = microphone; + if (!connected || out == null || mic == null) throw new IllegalStateException("Not connected"); + if (recorder != null) throw new IllegalStateException("Already recording"); + + Map names = new HashMap<>(); + for (ClientEntry c : model.allClients()) { + if (!c.uniqueId.isEmpty()) names.putIfAbsent(c.uniqueId, c.nickname); + } + VoiceRecorder rec = VoiceRecorder.start(mode, file, audio.opus(), names); + recorder = rec; + out.setVoiceTap((clientId, pcm, frames) -> { + ClientEntry c = model.getClient(clientId); + if (c != null) rec.offer(c.uniqueId, c.nickname, pcm, 1, frames); + }); + mic.setMonitorListener((pcm, channels) -> { + ClientEntry self = model.getClient(selfClientId); + if (self != null) rec.offer(getSelfUniqueId(), self.nickname, pcm, channels, pcm.length / channels); + }); + // A recording that fails to write ends by itself. + rec.whenDone().whenComplete((files, error) -> { + if (error != null) end(rec, true); + }); + publishRecording(true); + return rec; + } + + /** + * Stops the recording, if any; its files are finished in the background. + * + * @return the recording's files once written, or null if nothing was recording + */ + public CompletableFuture> stopRecording() { + return stopRecording(true); + } + + /** @param announce whether to tell the server; pointless when about to leave it */ + public CompletableFuture> stopRecording(boolean announce) { + VoiceRecorder rec = getRecorder(); + return rec != null && end(rec, announce) ? rec.stop() : null; + } + + /** Ends {@code rec} if it is still the one recording. */ + private boolean end(VoiceRecorder rec, boolean announce) { + synchronized (this) { + if (recorder != rec) return false; + detachRecorder(); + } + if (announce && connected) publishRecording(false); + return true; + } + + public synchronized VoiceRecorder getRecorder() { + return recorder; + } + + private synchronized void detachRecorder() { + recorder = null; + VoiceOutput out = playback; + VoiceInput mic = microphone; + if (out != null) out.setVoiceTap(null); + if (mic != null) mic.setMonitorListener(null); + } + + private void publishRecording(boolean recording) { + selfUpdate(cmd -> cmd.add(new CommandSingleParameter("client_is_recording", recording ? "1" : "0")), + "Recording status update failed"); + } + + /** + * Applies a change of our own state to the local model. The server sends + * {@code notifyclientupdated} to the other clients only, so without this + * our own row would keep its old icons until something else refreshed it. + */ + private void updateSelf(java.util.function.Consumer change) { + ClientEntry self = model.getClient(selfClientId); + if (self == null) return; + change.accept(self); + ui.onModelChanged(); + } + + /** Sends a {@code clientupdate} for the local client in the background. */ + private void selfUpdate(java.util.function.Consumer fill, String errorLabel) { + act(errorLabel + ": ", sock -> { + SingleCommand cmd = new SingleCommand("clientupdate", ProtocolRole.CLIENT); + fill.accept(cmd); + sock.executeCommand(cmd).complete(); + }); + } + + public double getPingMillis() { + try { + LocalTeamspeakClientSocket sock = client; + return sock != null ? sock.getPing().getKey() * 1000.0 : -1; + } catch (Exception e) { + return -1; + } + } + + public void setNickname(String nickname) { + act("Rename failed: ", sock -> sock.setNickname(nickname)); + } + + /* + * Info lookups use the commands the official client does. channelinfo/clientinfo would + * answer directly, but they are query commands that count heavily against the server's + * flood protection: clicking through the tree gets every command refused within seconds. + */ + + /** + * Asks for a channel's description. The answer arrives as a channel edit, see + * {@link ConnectionEventHandler#onChannelEdit}. + */ + public void requestChannelInfo(int channelId) { + requestInfo("channelgetdescription", "cid", channelId); + } + + /** + * Asks for a client's version and platform, the only details the enter-view event + * lacks. The answer arrives as a client update, see {@link ConnectionEventHandler#onClientChanged}. + */ + public void requestClientInfo(int clientId) { + requestInfo("clientgetvariables", "clid", clientId); + } + + /** May be refused for lack of permission; the details then stay as they are. */ + private void requestInfo(String command, String idParameter, int id) { + attempt(sock -> sock.executeCommand(new SingleCommand(command, ProtocolRole.CLIENT, + new CommandSingleParameter(idParameter, Integer.toString(id)))).complete()); + } + + /** + * Reads a client's description straight from the server, so an editor opens on the + * live text instead of whatever an earlier info request cached. + */ + public void requestClientDescription(int clientId, BiConsumer callback) { + run(callback, () -> { + Client c = socket().getClientInfo(clientId); + String description = c == null ? "" : orEmpty(c.get("client_description")); + ClientEntry e = model.getClient(clientId); + if (e != null) e.description = description; + return description; + }); + } + + /** + * Changes a client's description. Unlike the nickname or the away state, this is not + * a {@code clientupdate} property even for ourselves: the server only takes it + * through {@code clientedit}, gated by {@code b_client_modify_own_description}. + * + * @param callback given {@code null} on success, or the failure message + */ + public void setClientDescription(int clientId, String description, Consumer callback) { + boolean self = clientId == selfClientId; + run((ignored, error) -> callback.accept(error), () -> { + SingleCommand cmd = new SingleCommand("clientedit", ProtocolRole.CLIENT); + cmd.add(new CommandSingleParameter("clid", Integer.toString(clientId))); + cmd.add(new CommandSingleParameter("client_description", description)); + socket().executeCommand(cmd).complete(); + // Only the other clients are told about our own update, so the local entry + // (and the info panel showing it) has to be caught up here. + if (self) { + ClientEntry e = model.getClient(clientId); + if (e != null) e.description = description; + ui.onInfoUpdated(); + } + return null; + }); + } + + // ---- privilege keys ---- + + /** Reads the server's privilege keys, delivering them (or a failure message) off the UI thread. */ + public void requestPrivilegeKeys(BiConsumer, String> callback) { + run(callback, privilegeKeys::list); + } + + /** + * Creates a privilege key for a server group, or for a channel group in {@code channelId}. + * + * @param callback given the new key, or the failure message + */ + public void addPrivilegeKey(boolean channelGroup, int groupId, int channelId, String description, + BiConsumer callback) { + run(callback, () -> privilegeKeys.add(channelGroup, groupId, channelId, description)); + } + + /** + * Deletes privilege keys one by one, stopping at the first the server refuses. + * + * @param callback given {@code null} on success, or the failure message + */ + public void deletePrivilegeKeys(Collection tokens, Consumer callback) { + run((ignored, error) -> callback.accept(error), () -> { + for (String token : tokens) privilegeKeys.delete(token); + return null; + }); + } + + /** @param callback given {@code null} on success, or the failure message */ + public void usePrivilegeKey(String token, Consumer callback) { + run((ignored, error) -> callback.accept(error), () -> { + privilegeKeys.use(token); + return null; + }); + } + + // ---- complaints ---- + + /** Complains about an online client to the server's admins. */ + public void complain(ClientEntry client, String reason) { + act("Failed to send complaint: ", sock -> { + complaints.add(client.databaseId, reason); + log("Complaint sent."); + }); + } + + /** Reads the server's complaints, delivering them (or a failure message) off the UI thread. */ + public void requestComplaints(BiConsumer, String> callback) { + run(callback, complaints::list); + } + + /** + * Removes every complaint about each of {@code targetDbIds}, then each of {@code single}, + * stopping at the first the server refuses. + * + * @param callback given {@code null} on success, or the failure message + */ + public void deleteComplaints(Collection targetDbIds, Collection single, + Consumer callback) { + run((ignored, error) -> callback.accept(error), () -> { + for (int target : targetDbIds) complaints.deleteAll(target); + for (Complaint complaint : single) complaints.delete(complaint); + return null; + }); + } + + // ---- offline messages ---- + + /** Unread messages in our offline message inbox on this server. */ + public int unreadOfflineMessages() { + ClientEntry self = model.getClient(selfClientId); + return self == null ? 0 : self.unreadMessages; + } + + /** Whether the server lets us send offline messages. */ + public boolean canSendOfflineMessages() { + return model.permits("b_client_offline_textmessage_send"); + } + + /** Our unread count changed from {@code before}; more unread means new mail, which the log announces. */ + void unreadMessagesChanged(int before) { + int unread = unreadOfflineMessages(); + if (unread > before) { + String count = unread == 1 ? "1 unread offline message" : unread + " unread offline messages"; + log("You have " + TsLink.offlineMessagesBBCode(count)); + } + ui.onUnreadMessagesChanged(unread); + } + + /** Lists our offline message inbox, delivering it (or a failure message) off the UI thread. */ + public void requestOfflineMessages(BiConsumer, String> callback) { + run(callback, offlineMessages::list); + } + + /** Reads a message's body, delivering it (or a failure message) off the UI thread. */ + public void requestOfflineMessageBody(int messageId, BiConsumer callback) { + run(callback, () -> offlineMessages.body(messageId)); + } + + /** + * Marks messages read or unread, stopping at the first the server refuses. + * + * @param callback given {@code null} on success, or the failure message + */ + public void markOfflineMessages(Collection messageIds, boolean read, Consumer callback) { + run((ignored, error) -> callback.accept(error), () -> { + for (int id : messageIds) offlineMessages.setRead(id, read); + return null; + }); + } + + /** @param callback given {@code null} on success, or the failure message */ + public void deleteOfflineMessages(Collection messageIds, Consumer callback) { + run((ignored, error) -> callback.accept(error), () -> { + for (int id : messageIds) offlineMessages.delete(id); + return null; + }); + } + + /** + * Sends one offline message to each recipient, stopping at the first the server refuses. + * + * @param callback given {@code null} on success, or the failure message + */ + public void sendOfflineMessage(Collection recipientUids, String subject, String message, + Consumer callback) { + run((ignored, error) -> callback.accept(error), () -> { + for (String uid : recipientUids) offlineMessages.send(uid, subject, message); + log("Offline message sent."); + return null; + }); + } + + /** Looks a client up by unique id; delivers {@code null} when the server has never seen them. */ + public void lookupDatabaseClient(String uniqueId, BiConsumer callback) { + run(callback, () -> offlineMessages.lookupUid(uniqueId)); + } + + /** + * Finds clients whose last nickname contains {@code nickname}. + * + * @param callback given the matches, or {@link #SEARCH_NOT_PERMITTED} or another failure message + */ + public void searchDatabaseClients(String nickname, BiConsumer, String> callback) { + run(callback, () -> { + try { + return offlineMessages.search(nickname); + } catch (CommandException e) { + if (isPermissionError(e)) throw new IllegalStateException(SEARCH_NOT_PERMITTED); + throw e; + } + }); + } + + // ---- server log ---- + + /** + * Reads the server's newest log lines, or with {@code olderFrom} > 0 the ones before an + * earlier page's, delivering them (or a failure message) off the UI thread. + */ + public void requestServerLog(long olderFrom, BiConsumer callback) { + run(callback, () -> serverLog.read(olderFrom)); + } + + // ---- bans ---- + + /** Reads the server's ban list, delivering it (or a failure message) off the UI thread. */ + public void requestBanList(BiConsumer, String> callback) { + run(callback, bans::list); + } + + /** @param callback given {@code null} on success, or the failure message */ + public void addBan(BanRule rule, Consumer callback) { + run((ignored, error) -> callback.accept(error), () -> { + bans.add(rule); + return null; + }); + } + + /** + * Rewrites an existing ban. + * + * @param callback given {@code null} on success, or the failure message + */ + public void replaceBan(int banId, BanRule rule, Consumer callback) { + run((ignored, error) -> callback.accept(error), () -> { + bans.replace(banId, rule); + return null; + }); + } + + /** + * Deletes bans one by one, stopping at the first the server refuses. + * + * @param callback given {@code null} on success, or the failure message + */ + public void deleteBans(Collection banIds, Consumer callback) { + run((ignored, error) -> callback.accept(error), () -> { + for (int id : banIds) bans.delete(id); + return null; + }); + } + + /** + * Our own unique identifier on this server, which is how the server names us as a + * ban's creator; empty while not connected. + */ + // ---- contacts ---- + + public ContactStore getContacts() { + return contacts; + } + + /** The name a client is shown under: its contact's custom name where it has one. */ + public String displayName(ClientEntry client) { + return contacts.displayName(client.uniqueId, client.nickname); + } + + /** + * Whether a whisper from a client is played, per the global whisper policy and the + * client's contact entry. A client that has already left is judged by the policy alone. + */ + boolean isWhisperAllowed(int clientId) { + Settings.WhisperPolicy policy = settings.whisperPolicy; + if (policy == Settings.WhisperPolicy.NOBODY) return false; + ClientEntry c = model.getClient(clientId); + Contact contact = c == null ? null : contacts.find(c.uniqueId); + if (contact != null) return contact.whisperAllowed; + return policy == Settings.WhisperPolicy.ALLOW_UNLESS_DENIED; + } + + /** + * Applies a client's contact entry to its playback — the automatic mute and the + * volume modifier — and records the sighting. Called when the client appears. + */ + void applyContact(ClientEntry client) { + Contact contact = applyContactPlayback(client); + if (contact != null) contacts.markSeen(client.uniqueId, model.getServerName(), serverHost + ":" + serverPort); + } + + private Contact applyContactPlayback(ClientEntry client) { + if (client == null || client.self) return null; + Contact contact = contacts.find(client.uniqueId); + VoiceOutput out = playback; + if (contact != null && out != null) { + if (contact.automute) out.setClientMuted(client.id, true); + out.setClientVolume(client.id, contact.volumeGain()); + } + return contact; + } + + /** + * Re-applies every contact entry to the clients on the server, after the list changed. + * A client that just became a contact is also marked as seen. One seen before keeps + * where it was seen: with it on two servers, each re-application would claim it for its + * own server, which is a change that triggers the other's re-application, and so on. + */ + public void applyContacts() { + if (!connected) return; + for (ClientEntry c : model.allClients()) { + Contact contact = applyContactPlayback(c); + if (contact != null && contact.lastSeen == null) { + contacts.markSeen(c.uniqueId, model.getServerName(), serverHost + ":" + serverPort); + } + } + } + + /** Remembers a per-client volume, in the contact entry when the client has one. */ + public void setClientVolumeModifier(ClientEntry client, double decibels) { + VoiceOutput out = playback; + if (out != null) out.setClientVolume(client.id, Math.pow(10.0, decibels / 20.0)); + Contact contact = contacts.find(client.uniqueId); + if (contact == null) return; + contact.hasVolumeModifier = decibels != 0; + contact.volumeModifier = decibels; + contacts.put(contact); + } + + public double getClientVolumeModifier(ClientEntry client) { + VoiceOutput out = playback; + if (out == null) return 0; + double gain = out.getClientVolume(client.id); + return gain <= 0 ? -60 : 20.0 * Math.log10(gain); + } + + public String getSelfUniqueId() { + ClientEntry self = model.getClient(selfClientId); + if (self != null && !self.uniqueId.isEmpty()) return self.uniqueId; + LocalIdentity id = identity; + return id == null ? "" : id.getUid().toBase64(); + } + + // ---- channel administration ---- + + /** + * Reads a channel's editable properties, delivering them (or a failure message) to + * {@code callback} off the UI thread. + */ + public void requestChannelSettings(int channelId, BiConsumer callback) { + run(callback, () -> channels.readSettings(channelId)); + } + + /** + * Reads the permissions set directly on a channel, as name/value pairs. Fails when the + * server does not let us look at them. + */ + public void requestChannelPermissions(int channelId, + BiConsumer, String> callback) { + run(callback, () -> channels.readPermissions(channelId)); + } + + /** + * Applies an edited channel: its changed properties first, then its needed-power + * permissions. + * + * @param callback given {@code null} on success, or the failure message + */ + public void applyChannelEdit(int channelId, Map changes, + Map setPermissions, + Collection removePermissions, + Consumer callback) { + run((ignored, error) -> callback.accept(error), () -> { + channels.edit(channelId, changes); + channels.writePermissions(channelId, setPermissions, removePermissions); + if (changes.containsKey("channel_description")) { + ChannelNode node = model.getChannel(channelId); + // the server does not notify the invoker of their own description change + if (node != null && node.descriptionLoaded) { + node.descriptionLoaded = false; + requestChannelInfo(channelId); + } + } + return null; + }); + } + + /** + * Creates a channel below {@code parentId} (0 being the top level) and gives it the + * channel permissions it was created with. + * + * @param callback given the new channel's id, or the failure message. A channel whose + * permissions could not be set still exists, and is reported as an error + * saying so. + */ + public void createChannel(int parentId, Map properties, + Map permissions, + BiConsumer callback) { + run(callback, () -> { + int channelId = channels.create(parentId, properties); + try { + channels.writePermissions(channelId, permissions, List.of()); + } catch (Exception e) { + throw new IllegalStateException("The channel was created, but its permissions" + + " could not be set: " + rootMessage(e)); + } + return channelId; + }); + } + + /** + * Deletes a channel; with {@code force}, also one that has sub-channels or clients in it. + * + * @param callback given {@code null} on success, or the failure message + */ + public void deleteChannel(int channelId, boolean force, Consumer callback) { + run((ignored, error) -> callback.accept(error), () -> { + channels.delete(channelId, force); + return null; + }); + } + + /** The ids of the icons uploaded to this virtual server. */ + public void requestServerIcons(BiConsumer, String> callback) { + run(callback, channels::listIcons); + } + + /** Uploads an image as a server icon and reports the new icon's id. */ + public void uploadIcon(File source, BiConsumer callback) { + run(callback, () -> channels.uploadIcon(source)); + } + + /** Deletes a server icon; {@code callback} is given {@code null} on success. */ + public void deleteIcon(long iconId, Consumer callback) { + run((ignored, error) -> callback.accept(error), () -> { + channels.deleteIcon(iconId); + return null; + }); + } + + /** A request made on the socket of the connection it was issued on. */ + private interface Action { + void run(LocalTeamspeakClientSocket sock) throws Exception; + } + + /** Work that produces a value or an error message. */ + private interface Job { + T call() throws Exception; + } + + /** Sends a request in the background, reporting a failure as {@code errorPrefix} and the reason. */ + private void act(String errorPrefix, Action action) { + submit(action, e -> error(errorPrefix, e)); + } + + /** Sends a request in the background whose failure nobody needs to hear about. */ + private void attempt(Action action) { + submit(action, e -> { + }); + } + + private void submit(Action action, Consumer onFailure) { + LocalTeamspeakClientSocket sock = client; + ExecutorService pool = actions; + if (sock == null || pool == null || !connected) return; + try { + pool.execute(() -> { + try { + action.run(sock); + } catch (Exception e) { + // Leaving fails whatever was still in flight; that is no error to report. + if (client == sock && connected) onFailure.accept(e); + } + }); + } catch (RejectedExecutionException ignored) { + // disconnected in the meantime + } + } + + /** + * Runs a blocking server request in the background and hands the result — or the + * failure message — to {@code callback}, which therefore never runs on the UI thread. + */ + private void run(BiConsumer callback, Job job) { + ExecutorService pool = actions; + if (pool == null || client == null || !connected) { + callback.accept(null, "Not connected"); + return; + } + try { + pool.execute(() -> { + try { + callback.accept(job.call(), null); + } catch (Exception e) { + callback.accept(null, connected ? rootMessage(e) : "Not connected"); + } + }); + } catch (RejectedExecutionException e) { + callback.accept(null, "Not connected"); + } + } + + /** The live socket. Package-private for {@link ChannelAdmin}. */ + LocalTeamspeakClientSocket socket() { + LocalTeamspeakClientSocket sock = client; + if (sock == null || !connected) throw new IllegalStateException("Not connected"); + return sock; + } + + /** Package-private for {@link ChannelAdmin} and {@link ConnectionStatsCollector}. */ + FileTransferManager fileTransfers() { + return fileTransfers; + } + + /** + * Blocks until ts3j has finished dispatching every event it had already queued, so a + * caller that just saw a command complete can be sure the notifications the server sent + * alongside it have been handled. Must not be called from the event thread itself. + */ + void awaitEventsProcessed() { + ExecutorService events = eventExecutor; + if (events == null) return; + try { + events.submit(() -> { + }).get(5, TimeUnit.SECONDS); + } catch (Exception ignored) { + // A shutting-down or wedged event thread just means the caller gets what arrived. + } + } + + // ---- icons ---- + + /** Group icons for this server: bundled defaults plus the server's own uploads. */ + public IconRepository getIcons() { + return icons; + } + + /** Reads an icon out of the virtual server's file repository (channel 0). */ + private byte[] fetchIcon(long iconId) throws Exception { + FileTransferManager ft = fileTransfers; + if (ft == null) throw new IllegalStateException("Not connected"); + return ft.downloadToMemory(0, "", "/icon_" + iconId, MAX_ICON_BYTES); + } + + // ---- avatars ---- + + /** Client avatars for this server, downloaded on demand. */ + public AvatarRepository getAvatars() { + return avatars; + } + + /** The avatar a client currently shows, or {@code null} if none or not yet available. */ + public Avatar avatarOf(ClientEntry client) { + return client == null ? null : avatars.get(client.uniqueId, client.avatarFlag); + } + + /** How large an avatar this server lets us upload, in bytes. */ + public int maxAvatarBytes() { + return avatarAdmin.maxUploadBytes(); + } + + /** + * Uploads an image as our avatar and publishes it to the other clients. + * + * @param callback given {@code null} on success, or the failure message + */ + public void setAvatar(File source, Consumer callback) { + run((flag, error) -> { + if (error == null) updateSelf(self -> self.avatarFlag = flag); + callback.accept(error); + }, () -> avatarAdmin.upload(source)); + } + + /** Withdraws our avatar; {@code callback} is given {@code null} on success. */ + public void removeAvatar(Consumer callback) { + run((ignored, error) -> { + if (error == null) updateSelf(self -> self.avatarFlag = ""); + callback.accept(error); + }, () -> { + avatarAdmin.remove(); + return null; + }); + } + + /** Deletes another client's avatar; {@code callback} is given {@code null} on success. */ + public void removeAvatarOf(ClientEntry client, Consumer callback) { + run((ignored, error) -> callback.accept(error), () -> { + avatarAdmin.removeOther(client.uniqueId); + return null; + }); + } + + /** Reads a client's avatar out of the virtual server's file repository (channel 0). */ + private byte[] fetchAvatar(String uniqueId) throws Exception { + FileTransferManager ft = fileTransfers; + if (ft == null) throw new IllegalStateException("Not connected"); + String name = AvatarNaming.fileName(uniqueId); + if (name == null) throw new IllegalArgumentException("Not a client unique id: " + uniqueId); + return ft.downloadToMemory(0, "", "/" + name, AvatarAdmin.MAX_AVATAR_DOWNLOAD_BYTES); + } + + // ---- whisper ---- + + /** Sends the microphone's voice to {@code targets} as a whisper, or to our channel again with null. */ + public void setWhisperTargets(Whisper.Targets targets) { + LocalTeamspeakClientSocket sock = client; + if (sock == null) return; + if (targets == null) { + sock.setWhisperTarget(null); + return; + } + PacketBody1VoiceWhisper.WhisperTargetMultiple target = new PacketBody1VoiceWhisper.WhisperTargetMultiple(); + target.setChannelIds(targets.channelIds()); + target.setClientIds(targets.clientIds()); + sock.setWhisperTarget(target); + } + + /** The client who whispered to us last, if still on the server. */ + public ClientEntry lastWhisperer() { + int id = lastWhisperer; + return id == 0 ? null : model.getClient(id); + } + + // ---- file transfers ---- + + /** Whether a live connection capable of file transfers is available. */ + public boolean canTransferFiles() { + return connected && fileTransfers != null; + } + + /** + * Lists the files under {@code path} in a channel's repository. Blocking; call + * off the UI thread. Throws if not connected or the server denies the request. + */ + public java.util.List listFiles(int channelId, String channelPassword, String path) + throws Exception { + FileTransferManager ft = fileTransfers; + if (ft == null) throw new IllegalStateException("Not connected"); + return ft.list(channelId, channelPassword, path); + } + + public void createDirectory(int channelId, String channelPassword, String dirPath) throws Exception { + FileTransferManager ft = fileTransfers; + if (ft == null) throw new IllegalStateException("Not connected"); + ft.createDirectory(channelId, channelPassword, dirPath); + } + + public void deleteFile(int channelId, String channelPassword, String fullPath) throws Exception { + FileTransferManager ft = fileTransfers; + if (ft == null) throw new IllegalStateException("Not connected"); + ft.delete(channelId, channelPassword, fullPath); + } + + public void renameFile(int channelId, String channelPassword, String oldFullPath, String newFullPath) + throws Exception { + FileTransferManager ft = fileTransfers; + if (ft == null) throw new IllegalStateException("Not connected"); + ft.rename(channelId, channelPassword, oldFullPath, newFullPath); + } + + /** Begins downloading a channel file to {@code target}; progress arrives via {@code listener}. */ + public FileTransfer downloadFile(int channelId, String channelPassword, String remoteFullPath, + File target, FileTransfer.Listener listener) { + FileTransferManager ft = fileTransfers; + if (ft == null) throw new IllegalStateException("Not connected"); + return ft.download(channelId, channelPassword, remoteFullPath, target, announcing(listener)); + } + + /** Begins uploading {@code source} into a channel; progress arrives via {@code listener}. */ + public FileTransfer uploadFile(int channelId, String channelPassword, String remoteFullPath, + File source, boolean overwrite, FileTransfer.Listener listener) { + FileTransferManager ft = fileTransfers; + if (ft == null) throw new IllegalStateException("Not connected"); + return ft.upload(channelId, channelPassword, remoteFullPath, source, overwrite, announcing(listener)); + } + + /** + * Wraps a transfer listener so the completion and failure sounds play once the + * transfer finishes, whoever is watching it. + */ + private FileTransfer.Listener announcing(FileTransfer.Listener listener) { + java.util.concurrent.atomic.AtomicBoolean announced = new java.util.concurrent.atomic.AtomicBoolean(); + return transfer -> { + FileTransfer.State state = transfer.getState(); + if (state != FileTransfer.State.CANCELLED && transfer.isDone() + && announced.compareAndSet(false, true)) { + sound(state == FileTransfer.State.COMPLETED + ? SoundEvent.OTHER_FILETRANSFER_COMPLETE + : SoundEvent.OTHER_FILETRANSFER_FAILED, serverVars()); + } + if (listener != null) listener.onTransferChanged(transfer); + }; + } + + // ---- connection info ---- + + /** + * Fetches connection statistics for a client and delivers them to + * {@code callback} (invoked off the Swing EDT — the callback is responsible + * for marshalling). For the local client the figures are read from the live + * local packet counters; for a remote client they are requested from the + * server via {@code getconnectioninfo}, enriched with {@code clientinfo} for + * version, platform and idle time. May be called repeatedly to poll. + */ + public void requestConnectionInfo(int clientId, Consumer callback) { + if (client == null || !connected) return; + stats.request(clientId, callback); + } + + // ---- events not handled by ConnectionEventHandler ---- + + /** + * Kept here rather than in {@link ConnectionEventHandler}: teardown needs + * {@link #safeCleanup()} and the {@code connected}/announced flags this class + * already owns, so routing it through the event handler would only add an + * extra hop back into private lifecycle state. + */ + @Override + public void onDisconnected(DisconnectedEvent e) { + connected = false; + safeCleanup(); + announceDisconnect(false); + String reason = orEmpty(e.getReasonMessage()); + ui.onDisconnected(reason); + ui.onStatus(reason.isEmpty() ? "Disconnected" : "Disconnected: " + reason); + } + + // ---- sound notifications ---- + + /** + * Plays the sound pack's entry for an action. Muting is passed along so the + * notifier can drop everything the user did not mark as important. Package-private: + * also called by {@link ConnectionEventHandler}. + */ + void sound(SoundEvent event) { + sounds.fire(event, deafened); + } + + void sound(SoundEvent event, Map variables) { + sounds.fire(event, deafened, variables); + } + + private void loadChatLogs() { + chatLogs = null; + if (!settings.chatLogs) return; + try { + String uniqueId = serverUniqueId(); + if (uniqueId == null) { + ui.onStatus("Chat logs unavailable: the server's unique id is not known"); + return; + } + String dir = settings.chatLogDir == null ? "" : settings.chatLogDir.trim(); + // Android < API 34 lacks Path.of; original: + // ChatLogStore logs = new ChatLogStore(dir.isEmpty() ? ChatLogStore.defaultRoot() : Path.of(dir), uniqueId); + ChatLogStore logs = new ChatLogStore(dir.isEmpty() ? ChatLogStore.defaultRoot() : Paths.get(dir), uniqueId); + chatLogs = logs; + logs.begin(); + List serverHistory = logs.serverHtmlHistory(); + List channelHistory = logs.channelHtmlHistory(); + ui.onChatHistory(ConnectionListener.ChatScope.SERVER, serverHistory); + ui.onChatHistory(ConnectionListener.ChatScope.CHANNEL, channelHistory); + ui.onStatus("Loaded chat logs from " + logs.serverDir() + + " (" + serverHistory.size() + " server, " + channelHistory.size() + " channel)"); + } catch (Exception e) { + chatLogs = null; + ui.onStatus("Chat logs unavailable: " + rootMessage(e)); + } + } + + /** + * The server's unique identifier, worked out from its key as TeamSpeak does (a guest is + * never told it); {@code null} before the server has introduced itself. + */ + public String serverUniqueId() { + LocalTeamspeakClientSocket client = this.client; + if (client == null) return null; + Uid uid = client.getServerUid(); + return uid == null ? null : uid.toBase64(); + } + + public void loadPrivateChatHistory(int clientId, String uniqueId) { + ChatLogStore logs = chatLogs; + if (logs == null || uniqueId == null || uniqueId.isBlank()) return; + try { + ClientEntry c = model.getClient(clientId); + ui.onPrivateChatHistory(clientId, c != null ? c.nickname : "Client " + clientId, + logs.privateHtmlHistory(uniqueId)); + } catch (IOException e) { + ui.onStatus("Private chat log unavailable: " + rootMessage(e)); + } + } + + void persistIncomingChat(ConnectionListener.ChatScope scope, int fromClientId, String fromUniqueId, + String fromName, String message) { + ChatLogStore logs = chatLogs; + if (logs == null) return; + try { + logs.appendMessage(toLogScope(scope), false, fromClientId, fromUniqueId, fromName, message); + } catch (IOException e) { + ui.onStatus("Could not write chat log: " + rootMessage(e)); + } + } + + private void persistOutgoingChat(ConnectionListener.ChatScope scope, int peerClientId, String peerUniqueId, + String message) { + ChatLogStore logs = chatLogs; + if (logs == null) return; + try { + ClientEntry self = model.getClient(selfClientId); + String uid = identity != null ? identity.getUid().toBase64() : ""; + String name = self != null ? self.nickname : settings.nickname; + if (scope == ConnectionListener.ChatScope.PRIVATE) { + if (peerUniqueId == null || peerUniqueId.isBlank()) return; + logs.appendPrivateMessage(peerUniqueId, true, selfClientId, uid, name, message); + } else { + logs.appendMessage(toLogScope(scope), true, selfClientId, uid, name, message); + } + } catch (IOException e) { + ui.onStatus("Could not write chat log: " + rootMessage(e)); + } + } + + private static ChatLogScope toLogScope(ConnectionListener.ChatScope scope) { + return switch (scope) { + case SERVER -> ChatLogScope.SERVER; + case CHANNEL -> ChatLogScope.CHANNEL; + case PRIVATE -> ChatLogScope.PRIVATE; + }; + } + + /** Records a line in the server tab's log, the way native TS3 reports server activity. */ + void log(String message) { + if (!connected) return; + ChatLogStore logs = chatLogs; + if (logs == null) { + ui.onServerLog(message); + return; + } + try { + ui.onServerLogHtml(logs.appendServerEvent(message)); + } catch (IOException e) { + ui.onServerLog(message); + ui.onStatus("Could not write server log: " + rootMessage(e)); + } + } + + String channelName(int channelId) { + ChannelNode ch = model.getChannel(channelId); + return ch != null ? ch.name : "channel #" + channelId; + } + + /** + * A channel's name as the log wants it: TeamSpeak's own {@code channel://} link, which + * the chat log turns into the same clickable entry a dragged-in channel produces. A + * channel we no longer know (a deleted one, say) is named in plain text instead. + */ + String channelLink(int channelId) { + ChannelNode ch = model.getChannel(channelId); + return ch != null ? TsLink.channelBBCode(channelId, ch.name) : channelName(channelId); + } + + /** The same for a client, named by the model. */ + String clientLink(int clientId) { + ClientEntry c = model.getClient(clientId); + return c != null ? clientLink(clientId, c.uniqueId, c.nickname) : "Client " + clientId; + } + + /** The same for a client an event describes, which may already be gone from the model. */ + String clientLink(int clientId, String uniqueId, String nickname) { + if (clientId <= 0 || nickname == null || nickname.isEmpty()) return orEmpty(nickname); + return TsLink.clientBBCode(clientId, orEmpty(uniqueId), nickname); + } + + /** The placeholder values a pack may reference for an action involving a client. */ + Map clientVars(int clientId, String fallbackName) { + ClientEntry c = model.getClient(clientId); + Map vars = SoundNotifier.vars( + "servername", model.getServerName(), + "clientname", c != null ? c.nickname : orEmpty(fallbackName), + "clientuid", c != null ? c.uniqueId : ""); + if (c != null) { + ChannelNode ch = model.getChannel(c.channelId); + if (ch != null) vars.put("channelname", ch.name); + } + return vars; + } + + Map channelVars(int channelId, String invokerName) { + ChannelNode ch = model.getChannel(channelId); + return SoundNotifier.vars( + "servername", model.getServerName(), + "channelname", ch != null ? ch.name : "", + "clientname", orEmpty(invokerName)); + } + + Map serverVars() { + return SoundNotifier.vars("servername", model.getServerName()); + } + + /** Reports a failure to the UI and plays the matching server sound. */ + private void error(String prefix, Exception e) { + sound(isPermissionError(e) + ? SoundEvent.SERVER_INSUFFICIENT_PERMISSIONS + : SoundEvent.SERVER_ERROR, serverVars()); + ui.onError(prefix + rootMessage(e)); + } + + /** Whether the server refused for lack of permission, wherever in the cause chain it said so. */ + static boolean isPermissionError(Throwable t) { + for (Throwable c = t; c != null; c = c.getCause() == c ? null : c.getCause()) { + if (c instanceof CommandException ce) { + int id = ce.getErrorId(); + return id == ERROR_PERMISSIONS_CLIENT_INSUFFICIENT + || id == ERROR_PERMISSIONS_INSUFFICIENT_GROUP_POWER + || id == ERROR_PERMISSIONS_INSUFFICIENT_PERMISSION_POWER; + } + } + return false; + } + + /** Whether the client is in the channel we are in ourselves. Package-private: also + * used by {@link ConnectionEventHandler}. */ + boolean inOwnChannel(int channelId) { + ClientEntry self = model.getClient(selfClientId); + return self != null && self.channelId == channelId; + } + + // ---- helpers ---- + + /** Package-private: also used by {@link ConnectionEventHandler}. */ + static long safeLong(BaseEvent e, String key) { + return safeLong(e.get(key)); + } + + /** @return the parsed value, or 0 when it is absent or not a number */ + private static long safeLong(String value) { + try { + return value == null ? 0 : Long.parseLong(value.trim()); + } catch (NumberFormatException ex) { + return 0; + } + } + + /** Package-private: also used by {@link ConnectionEventHandler} and {@link ConnectionStatsCollector}. */ + static String orEmpty(String s) { + return s == null ? "" : s; + } + + /** Every message along the cause chain, outermost first: network errors are vague without context. */ + private static String messageChain(Throwable t) { + StringBuilder chain = new StringBuilder(); + for (Throwable c = t; c != null; c = c.getCause() == c ? null : c.getCause()) { + String m = c.getMessage(); + if (m == null || chain.indexOf(m) >= 0) continue; + if (chain.length() > 0) chain.append(": "); + chain.append(m); + } + return chain.length() > 0 ? chain.toString() : t.getClass().getSimpleName(); + } + + private static String rootMessage(Throwable t) { + Throwable r = t; + while (r.getCause() != null && r.getCause() != r) r = r.getCause(); + String m = r.getMessage(); + return m != null ? m : r.getClass().getSimpleName(); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TreeMatch.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TreeMatch.java new file mode 100644 index 0000000..b3ab8ca --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TreeMatch.java @@ -0,0 +1,22 @@ +package eu.lixko.ts3j.client.net; + +import eu.lixko.ts3j.client.text.TextQuery; + +/** What finding in the server tree matches a client or a channel on. */ +public final class TreeMatch { + + private TreeMatch() { + } + + /** A client by their nickname, or by the name the contacts give them ({@code null} for none). */ + public static boolean client(TextQuery query, String nickname, String contactName) { + return query.matches(nickname) || (contactName != null && query.matches(contactName)); + } + + /** A channel by its name; a spacer by its caption, unless that only repeats to fill the row. */ + public static boolean channel(TextQuery query, String name) { + Spacers.Spacer spacer = Spacers.parse(name); + if (spacer == null) return query.matches(name); + return spacer.align() != '*' && query.matches(spacer.caption()); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Whisper.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Whisper.java new file mode 100644 index 0000000..f87c15c --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/Whisper.java @@ -0,0 +1,76 @@ +package eu.lixko.ts3j.client.net; + +import eu.lixko.ts3j.client.config.WhisperList; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +/** + * Where the microphone whispers to instead of talking in our channel: channels and clients, + * found on the server by reference so they follow renames, moves and reconnects. + */ +public final class Whisper { + + /** What the whisper is shown as: the list's, the channel's or the client's name. */ + public final String label; + /** Channel references as {@link ServerModel#findChannelByPath} reads them. */ + private final List channels; + private final List clientUniqueIds; + + private Whisper(String label, List channels, List clientUniqueIds) { + this.label = label; + this.channels = channels; + this.clientUniqueIds = clientUniqueIds; + } + + public static Whisper toChannel(ChannelNode channel) { + return new Whisper(channel.name, List.of("/" + channel.id), List.of()); + } + + public static Whisper toClient(ClientEntry client) { + return new Whisper(client.nickname, List.of(), List.of(client.uniqueId)); + } + + public static Whisper of(WhisperList list) { + List uids = new ArrayList<>(); + for (WhisperList.Client c : list.clients) uids.add(c.uniqueId()); + return new Whisper(list.name, List.copyOf(list.channels), uids); + } + + /** Who hears it on the server as it is now; what is not there is left out. */ + public Targets resolve(ServerModel model) { + Set channelIds = new LinkedHashSet<>(); + for (String ref : channels) { + ChannelNode c = model.findChannelByPath(ref); + if (c != null) channelIds.add(c.id); + } + Set clientIds = new LinkedHashSet<>(); + for (String uid : clientUniqueIds) { + ClientEntry c = model.findClientByUniqueId(uid); + if (c != null) clientIds.add(c.id); + } + return new Targets(channelIds.stream().mapToInt(Integer::intValue).toArray(), + clientIds.stream().mapToInt(Integer::intValue).toArray()); + } + + /** The channel and client ids a whisper goes to. */ + public record Targets(int[] channelIds, int[] clientIds) { + + public boolean isEmpty() { + return channelIds.length == 0 && clientIds.length == 0; + } + + @Override + public boolean equals(Object o) { + return o instanceof Targets t && Arrays.equals(channelIds, t.channelIds) && Arrays.equals(clientIds, t.clientIds); + } + + @Override + public int hashCode() { + return 31 * Arrays.hashCode(channelIds) + Arrays.hashCode(clientIds); + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/avatar/Avatar.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/avatar/Avatar.java new file mode 100644 index 0000000..00c0cd5 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/avatar/Avatar.java @@ -0,0 +1,17 @@ +package eu.lixko.ts3j.client.net.avatar; + +import java.io.File; + +/** + * A downloaded avatar: its bytes, container format and the on-disk copy for views that + * can only reference images by URL. + * + * @param flag the MD5 the server advertises for it ({@code client_flag_avatar}) + * @param file the cached copy, or {@code null} if the disk cache is unavailable + */ +public record Avatar(String flag, byte[] data, ImageFormat format, File file) { + + public boolean isAnimated() { + return format == ImageFormat.GIF; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/avatar/AvatarNaming.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/avatar/AvatarNaming.java new file mode 100644 index 0000000..7d2abc9 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/avatar/AvatarNaming.java @@ -0,0 +1,67 @@ +package eu.lixko.ts3j.client.net.avatar; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; + +/** + * How TeamSpeak names and identifies avatars. + * + *

    An avatar lives in the virtual server's file repository (channel 0) as + * {@code /avatar_}, where the name is the client's unique identifier — the + * base64 of a 20-byte SHA-1 — decoded and re-encoded as forty letters {@code a}–{@code p} + * (one per nibble, high nibble first). This is what the client library calls + * {@code identityStringToFilename}, recovered from the official client. + * + *

    The {@code client_flag_avatar} property carries the MD5 of the file's bytes, so a + * changed avatar is detectable without re-downloading. + */ +public final class AvatarNaming { + + private static final char[] NIBBLES = "abcdefghijklmnop".toCharArray(); + + private AvatarNaming() { + } + + /** + * @return the repository file name ({@code avatar_…}) of a client's avatar, without + * the leading slash, or {@code null} if the unique id is not a valid one + */ + public static String fileName(String uniqueId) { + byte[] hash; + try { + hash = Base64.getDecoder().decode(uniqueId.trim()); + } catch (IllegalArgumentException | NullPointerException e) { + return null; + } + if (hash.length != 20) return null; + StringBuilder sb = new StringBuilder("avatar_"); + for (byte b : hash) { + sb.append(NIBBLES[(b >> 4) & 0xF]).append(NIBBLES[b & 0xF]); + } + return sb.toString(); + } + + /** The lowercase hex MD5 that TeamSpeak publishes as {@code client_flag_avatar}. */ + public static String flag(byte[] avatar) { + try { + byte[] digest = MessageDigest.getInstance("MD5").digest(avatar); + StringBuilder sb = new StringBuilder(32); + for (byte b : digest) sb.append(String.format("%02x", b)); + return sb.toString(); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + /** Whether the flag looks like an MD5 (the server also passes junk through unchanged). */ + public static boolean isFlag(String flag) { + if (flag == null || flag.length() != 32) return false; + for (byte c : flag.getBytes(StandardCharsets.US_ASCII)) { + boolean hex = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); + if (!hex) return false; + } + return true; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/avatar/AvatarRepository.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/avatar/AvatarRepository.java new file mode 100644 index 0000000..1c3f2b1 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/avatar/AvatarRepository.java @@ -0,0 +1,148 @@ +package eu.lixko.ts3j.client.net.avatar; + +import eu.lixko.ts3j.client.config.AppDirs; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * Supplies client avatars, downloading each from the server's file repository once + * and caching it in memory and on disk. + * + *

    Avatars are identified by their {@code client_flag_avatar} MD5 rather than by + * client, so a client changing their picture simply asks for a new flag, and two + * clients with the same picture share one download. A file whose MD5 does not match + * the advertised flag is discarded, as the official client does. + * + *

    Lookups never block: {@link #get} returns {@code null} while an avatar is still + * being fetched and the listener is notified once it becomes available. + */ +public final class AvatarRepository { + + /** Downloads {@code /avatar_} of the given client from channel 0. */ + public interface Fetcher { + byte[] fetchAvatar(String uniqueId) throws Exception; + } + + private final Fetcher fetcher; + private final Runnable onAvatarLoaded; + private final File cacheDir; + private final Map avatars = new ConcurrentHashMap<>(); + private final Set pending = ConcurrentHashMap.newKeySet(); + private final Set failed = ConcurrentHashMap.newKeySet(); + private final ExecutorService downloads = Executors.newSingleThreadExecutor(r -> { + Thread t = new Thread(r, "ts3j-avatars"); + t.setDaemon(true); + return t; + }); + + /** + * @param onAvatarLoaded run (off the UI thread) whenever a previously missing + * avatar has arrived, so the view can repaint + */ + public AvatarRepository(Fetcher fetcher, Runnable onAvatarLoaded) { + this(fetcher, onAvatarLoaded, new File(AppDirs.profile(), "avatars")); + } + + /** @param cacheDir where downloaded avatars are kept between sessions */ + public AvatarRepository(Fetcher fetcher, Runnable onAvatarLoaded, File cacheDir) { + this.fetcher = fetcher; + this.onAvatarLoaded = onAvatarLoaded; + this.cacheDir = cacheDir; + } + + /** + * @param uniqueId the client whose avatar is wanted + * @param flag the MD5 the client currently advertises; empty means no avatar + * @return the avatar, or {@code null} if the client has none, it is still loading + * or it is unavailable. An avatar that is not cached yet starts downloading. + */ + public Avatar get(String uniqueId, String flag) { + if (!AvatarNaming.isFlag(flag)) return null; + String key = flag.toLowerCase(); + + Avatar cached = avatars.get(key); + if (cached != null) return cached; + + Avatar fromDisk = readDiskCache(key); + if (fromDisk != null) { + avatars.put(key, fromDisk); + return fromDisk; + } + if (uniqueId != null && !uniqueId.isEmpty() && !failed.contains(key) && pending.add(key)) { + downloads.execute(() -> download(uniqueId, key)); + } + return null; + } + + /** Records an avatar we just uploaded ourselves, so it shows without a round trip. */ + public Avatar put(byte[] data) { + String flag = AvatarNaming.flag(data); + Avatar avatar = new Avatar(flag, data, ImageFormat.detect(data), writeDiskCache(flag, data)); + avatars.put(flag, avatar); + failed.remove(flag); + return avatar; + } + + /** Forgets download failures so avatars can be retried on the next reconnect. */ + public void retryFailed() { + failed.clear(); + } + + public void shutdown() { + downloads.shutdownNow(); + } + + private void download(String uniqueId, String flag) { + try { + byte[] data = fetcher.fetchAvatar(uniqueId); + if (data == null || data.length == 0 || !AvatarNaming.flag(data).equals(flag)) { + failed.add(flag); + return; + } + avatars.put(flag, new Avatar(flag, data, ImageFormat.detect(data), writeDiskCache(flag, data))); + if (onAvatarLoaded != null) onAvatarLoaded.run(); + } catch (IllegalStateException e) { + // Not connected (yet); leave it retryable. + } catch (Exception e) { + // Missing or permission-denied avatars are common; don't ask again. + failed.add(flag); + } finally { + pending.remove(flag); + } + } + + private Avatar readDiskCache(String flag) { + for (ImageFormat format : ImageFormat.values()) { + File file = new File(cacheDir, flag + "." + format.extension); + if (!file.isFile()) continue; + try { + byte[] data = Files.readAllBytes(file.toPath()); + if (AvatarNaming.flag(data).equals(flag)) return new Avatar(flag, data, format, file); + } catch (IOException ignored) { + // fall through and re-download + } + } + return null; + } + + private File writeDiskCache(String flag, byte[] data) { + ImageFormat format = ImageFormat.detect(data); + if (format == null) return null; // nothing we could display later anyway + File file = new File(cacheDir, flag + "." + format.extension); + try { + //noinspection ResultOfMethodCallIgnored + cacheDir.mkdirs(); + Files.write(file.toPath(), data); + return file; + } catch (IOException e) { + return null; // the in-memory cache still serves this session + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/avatar/ImageFormat.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/avatar/ImageFormat.java new file mode 100644 index 0000000..5a0cb07 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/avatar/ImageFormat.java @@ -0,0 +1,22 @@ +package eu.lixko.ts3j.client.net.avatar; + +/** The image container formats TeamSpeak accepts for avatars, told apart by their magic bytes. */ +public enum ImageFormat { + PNG("png"), JPEG("jpg"), GIF("gif"), BMP("bmp"); + + public final String extension; + + ImageFormat(String extension) { + this.extension = extension; + } + + /** @return the format of {@code data}, or {@code null} if it is none of the supported ones */ + public static ImageFormat detect(byte[] data) { + if (data == null || data.length < 6) return null; + if ((data[0] & 0xFF) == 0x89 && data[1] == 'P' && data[2] == 'N' && data[3] == 'G') return PNG; + if ((data[0] & 0xFF) == 0xFF && (data[1] & 0xFF) == 0xD8) return JPEG; + if (data[0] == 'G' && data[1] == 'I' && data[2] == 'F' && data[3] == '8') return GIF; + if (data[0] == 'B' && data[1] == 'M') return BMP; + return null; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ban/BanEntry.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ban/BanEntry.java new file mode 100644 index 0000000..6e1c930 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ban/BanEntry.java @@ -0,0 +1,107 @@ +package eu.lixko.ts3j.client.net.ban; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** One entry of the server's ban list, as a {@code notifybanlist} event describes it. */ +public final class BanEntry { + + public final int id; + /** The regular expression matched against a joining client's IP, or empty. */ + public final String ip; + /** The regular expression matched against a joining client's nickname, or empty. */ + public final String name; + public final String uid; + public final String mytsid; + /** The nickname the banned client last used, where the server knew one. */ + public final String lastNickname; + public final long createdEpochSeconds; + /** How long the ban lasts from its creation, or 0 when it never expires. */ + public final long durationSeconds; + public final String invokerName; + public final int invokerDatabaseId; + public final String invokerUid; + public final String reason; + /** How many connection attempts the ban has blocked so far. */ + public final int enforcements; + + public BanEntry(int id, String ip, String name, String uid, String mytsid, String lastNickname, + long createdEpochSeconds, long durationSeconds, String invokerName, + int invokerDatabaseId, String invokerUid, String reason, int enforcements) { + this.id = id; + this.ip = orEmpty(ip); + this.name = orEmpty(name); + this.uid = orEmpty(uid); + this.mytsid = orEmpty(mytsid); + this.lastNickname = orEmpty(lastNickname); + this.createdEpochSeconds = createdEpochSeconds; + this.durationSeconds = Math.max(0, durationSeconds); + this.invokerName = orEmpty(invokerName); + this.invokerDatabaseId = invokerDatabaseId; + this.invokerUid = orEmpty(invokerUid); + this.reason = orEmpty(reason); + this.enforcements = enforcements; + } + + /** Reads an entry off a {@code notifybanlist} event's fields. */ + public static BanEntry from(Map fields) { + return new BanEntry( + parseInt(fields.get("banid"), -1), + fields.get("ip"), fields.get("name"), fields.get("uid"), fields.get("mytsid"), + fields.get("lastnickname"), + parseLong(fields.get("created"), 0), parseLong(fields.get("duration"), 0), + fields.get("invokername"), parseInt(fields.get("invokercldbid"), 0), + fields.get("invokeruid"), fields.get("reason"), + parseInt(fields.get("enforcements"), 0)); + } + + public boolean isPermanent() { + return durationSeconds == 0; + } + + /** When the ban lifts, in seconds since the epoch; meaningless for a permanent one. */ + public long expiresEpochSeconds() { + return createdEpochSeconds + durationSeconds; + } + + /** Whether {@code uid} (a client's unique identifier) created this ban. */ + public boolean createdBy(String uid) { + return uid != null && !uid.isEmpty() && uid.equals(invokerUid); + } + + /** What the ban matches, as the official list sums it up: {@code name=…, ip=…, uid=… (last nickname), mytsid=…}. */ + public String targets() { + List parts = new ArrayList<>(4); + if (!name.isEmpty()) parts.add("name=" + name); + if (!ip.isEmpty()) parts.add("ip=" + ip); + if (!uid.isEmpty()) parts.add("uid=" + uid + (lastNickname.isEmpty() ? "" : " (" + lastNickname + ")")); + if (!mytsid.isEmpty()) parts.add("mytsid=" + mytsid); + return String.join(", ", parts); + } + + /** The entry's targets and settings as a rule, which is what editing starts from. */ + public BanRule toRule() { + return new BanRule(ip, name, uid, mytsid, durationSeconds, reason); + } + + private static String orEmpty(String s) { + return s == null ? "" : s; + } + + private static int parseInt(String value, int fallback) { + try { + return value == null || value.isEmpty() ? fallback : Integer.parseInt(value.trim()); + } catch (NumberFormatException e) { + return fallback; + } + } + + private static long parseLong(String value, long fallback) { + try { + return value == null || value.isEmpty() ? fallback : Long.parseLong(value.trim()); + } catch (NumberFormatException e) { + return fallback; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ban/BanPattern.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ban/BanPattern.java new file mode 100644 index 0000000..7ad01bb --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ban/BanPattern.java @@ -0,0 +1,126 @@ +package eu.lixko.ts3j.client.net.ban; + +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; + +/** + * The notations a ban's IP and name may be typed in, and their translation to and from + * the regular expressions the server actually matches — the official client's + * "Interpret IP/Name as" choice. + * + *

    A wildcard pattern is the text with {@code *} standing for a run of characters + * and everything else taken literally; a fixed string is taken literally throughout. + * In an IP a wildcard covers one address group (decimal for IPv4, hexadecimal for + * IPv6), in a name it covers anything. + */ +public enum BanPattern { + + WILDCARD_IPV4("Wildcard ipv4", "[0-9]+"), + WILDCARD_IPV6("Wildcard ipv6", "[0-9a-fA-F]+"), + FIXED_STRING("Fixed String", null), + REGULAR_EXPRESSION("Regular Expression", null); + + private static final String NAME_WILDCARD = ".*"; + private static final String META = "\\.[]{}()+?|^$*"; + + private final String label; + /** What one {@code *} in an IP stands for; {@code null} where the notation has no wildcards. */ + private final String ipWildcard; + + BanPattern(String label, String ipWildcard) { + this.label = label; + this.ipWildcard = ipWildcard; + } + + public String label() { + return label; + } + + /** The regular expression an IP written in this notation stands for. */ + public String ipToRegex(String text) { + return toRegex(text, ipWildcard); + } + + /** The regular expression a nickname written in this notation stands for. */ + public String nameToRegex(String text) { + return toRegex(text, ipWildcard == null ? null : NAME_WILDCARD); + } + + private String toRegex(String text, String wildcard) { + if (text == null) return ""; + if (this == REGULAR_EXPRESSION) return text; + StringBuilder out = new StringBuilder(text.length() + 8); + for (int i = 0; i < text.length(); i++) { + char c = text.charAt(i); + if (c == '*' && wildcard != null) out.append(wildcard); + else if (META.indexOf(c) >= 0) out.append('\\').append(c); + else out.append(c); + } + return out.toString(); + } + + /** + * Whether {@code regex} is something the server will accept as a pattern; an + * unparsable expression fails the whole {@code banadd}. + */ + public static boolean isValidRegex(String regex) { + if (regex == null || regex.isEmpty()) return true; + try { + Pattern.compile(regex); + return true; + } catch (PatternSyntaxException e) { + return false; + } + } + + /** A pattern written back in one of the friendlier notations, where that is possible. */ + public static final class Decoded { + public final BanPattern pattern; + public final String ip; + public final String name; + + Decoded(BanPattern pattern, String ip, String name) { + this.pattern = pattern; + this.ip = ip; + this.name = name; + } + } + + /** + * Finds the friendliest notation that reproduces an existing ban's IP and name + * expressions exactly, so an editor can show them the way they were most likely + * typed; anything it cannot round-trip is shown as the raw regular expression. + */ + public static Decoded decode(String ipRegex, String nameRegex) { + String ip = ipRegex == null ? "" : ipRegex; + String name = nameRegex == null ? "" : nameRegex; + for (BanPattern p : new BanPattern[] {WILDCARD_IPV4, WILDCARD_IPV6, FIXED_STRING}) { + String ipText = p.fromRegex(ip, p.ipWildcard); + String nameText = p.fromRegex(name, p.ipWildcard == null ? null : NAME_WILDCARD); + if (ipText != null && nameText != null + && p.ipToRegex(ipText).equals(ip) && p.nameToRegex(nameText).equals(name)) { + return new Decoded(p, ipText, nameText); + } + } + return new Decoded(REGULAR_EXPRESSION, ip, name); + } + + /** Inverts {@link #toRegex}; {@code null} where the expression is not in this notation. */ + private String fromRegex(String regex, String wildcard) { + StringBuilder out = new StringBuilder(regex.length()); + for (int i = 0; i < regex.length(); i++) { + if (wildcard != null && regex.startsWith(wildcard, i)) { + out.append('*'); + i += wildcard.length() - 1; + } else if (regex.charAt(i) == '\\') { + if (i + 1 >= regex.length() || META.indexOf(regex.charAt(i + 1)) < 0) return null; + out.append(regex.charAt(++i)); + } else if (META.indexOf(regex.charAt(i)) >= 0) { + return null; + } else { + out.append(regex.charAt(i)); + } + } + return out.toString(); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ban/BanRule.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ban/BanRule.java new file mode 100644 index 0000000..617abfa --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ban/BanRule.java @@ -0,0 +1,44 @@ +package eu.lixko.ts3j.client.net.ban; + +/** + * What a ban is made of, as {@code banadd} takes it: any combination of an IP pattern, + * a nickname pattern, a unique identifier and a myTeamSpeak id, with a duration and a + * reason. The patterns are regular expressions — see {@link BanPattern} for turning + * friendlier notations into them. + */ +public final class BanRule { + + /** The longest reason the server stores with a ban. */ + public static final int REASON_LIMIT = 80; + + public final String ipRegex; + public final String nameRegex; + public final String uid; + public final String mytsid; + /** The ban's length in seconds, or 0 for a permanent one. */ + public final long durationSeconds; + public final String reason; + + public BanRule(String ipRegex, String nameRegex, String uid, String mytsid, + long durationSeconds, String reason) { + this.ipRegex = trimmed(ipRegex); + this.nameRegex = trimmed(nameRegex); + this.uid = trimmed(uid); + this.mytsid = trimmed(mytsid); + this.durationSeconds = Math.max(0, durationSeconds); + this.reason = trimmed(reason); + } + + /** A rule with nothing to match bans nobody; the server rejects it. */ + public boolean hasTarget() { + return !ipRegex.isEmpty() || !nameRegex.isEmpty() || !uid.isEmpty() || !mytsid.isEmpty(); + } + + public boolean isPermanent() { + return durationSeconds == 0; + } + + private static String trimmed(String s) { + return s == null ? "" : s.trim(); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ban/BanUnit.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ban/BanUnit.java new file mode 100644 index 0000000..52c3a76 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ban/BanUnit.java @@ -0,0 +1,45 @@ +package eu.lixko.ts3j.client.net.ban; + +/** + * The units a ban's length is given in, as the official client asks for it: an amount of + * seconds, minutes, hours or days, or permanent, which takes no amount. + */ +public enum BanUnit { + + SECONDS("seconds", 1), + MINUTES("minutes", 60), + HOURS("hours", 3600), + DAYS("days", 86400), + PERMANENT("permanent", 0); + + private final String label; + private final long seconds; + + BanUnit(String label, long seconds) { + this.label = label; + this.seconds = seconds; + } + + public String label() { + return label; + } + + /** The length of {@code amount} of this unit in seconds; 0 when permanent. */ + public long toSeconds(long amount) { + return amount * seconds; + } + + /** The largest unit that divides {@code seconds} evenly; a length of 0 or less is permanent. */ + public static BanUnit largestFor(long seconds) { + if (seconds <= 0) return PERMANENT; + for (int i = PERMANENT.ordinal() - 1; i > 0; i--) { + if (seconds % values()[i].seconds == 0) return values()[i]; + } + return SECONDS; + } + + /** How many of this unit {@code seconds} is; 0 when permanent. */ + public long amountOf(long seconds) { + return this == PERMANENT ? 0 : seconds / this.seconds; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/filetransfer/FileTransfer.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/filetransfer/FileTransfer.java new file mode 100644 index 0000000..33462ec --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/filetransfer/FileTransfer.java @@ -0,0 +1,156 @@ +package eu.lixko.ts3j.client.net.filetransfer; + +import java.io.File; + +/** + * An observable handle for a single in-flight (or finished) file transfer. Created + * by {@link FileTransferManager}; the actual byte copy runs on a background thread + * and mutates this object, notifying a {@link Listener} on every change so a UI can + * render live progress. All mutating methods are package-private — callers only read. + */ +public final class FileTransfer { + + public enum Direction {UPLOAD, DOWNLOAD} + + public enum State { + /** Announced to the server, file connection not yet established. */ + PENDING, + /** Bytes are actively being transferred. */ + ACTIVE, + COMPLETED, + FAILED, + CANCELLED + } + + /** Notified (off the UI thread) whenever this transfer's progress or state changes. */ + public interface Listener { + void onTransferChanged(FileTransfer transfer); + } + + private final Direction direction; + private final int channelId; + private final String remoteName; + private final File localFile; + private final Listener listener; + + private volatile long totalBytes; + private volatile long transferredBytes; + private volatile State state = State.PENDING; + private volatile String errorMessage; + private volatile boolean cancelRequested; + + private final long startedAtMs = System.currentTimeMillis(); + private volatile long finishedAtMs; + + FileTransfer(Direction direction, int channelId, String remoteName, File localFile, + long totalBytes, Listener listener) { + this.direction = direction; + this.channelId = channelId; + this.remoteName = remoteName; + this.localFile = localFile; + this.totalBytes = totalBytes; + this.listener = listener; + } + + // ---- read-only accessors ---- + + public Direction getDirection() { + return direction; + } + + public int getChannelId() { + return channelId; + } + + public String getRemoteName() { + return remoteName; + } + + public File getLocalFile() { + return localFile; + } + + public long getTotalBytes() { + return totalBytes; + } + + public long getTransferredBytes() { + return transferredBytes; + } + + public State getState() { + return state; + } + + public String getErrorMessage() { + return errorMessage; + } + + public boolean isDone() { + State s = state; + return s == State.COMPLETED || s == State.FAILED || s == State.CANCELLED; + } + + /** Completion fraction in [0, 1], or 0 when the total size is unknown. */ + public double getProgress() { + long total = totalBytes; + if (total <= 0) return isDone() && state == State.COMPLETED ? 1.0 : 0.0; + double p = (double) transferredBytes / total; + return p < 0 ? 0 : (p > 1 ? 1 : p); + } + + /** Average speed in bytes per second over the transfer's lifetime, or 0 if not measurable. */ + public double getAverageSpeed() { + long end = isDone() ? finishedAtMs : System.currentTimeMillis(); + long elapsed = Math.max(1, end - startedAtMs); + return transferredBytes * 1000.0 / elapsed; + } + + /** Requests cancellation; the transfer thread aborts at the next chunk boundary. */ + public void cancel() { + cancelRequested = true; + } + + boolean isCancelRequested() { + return cancelRequested; + } + + // ---- package-private mutators, called by FileTransferManager ---- + + void setTotalBytes(long totalBytes) { + this.totalBytes = totalBytes; + } + + void addTransferred(long delta) { + transferredBytes += delta; + fireChanged(); + } + + void markActive() { + state = State.ACTIVE; + fireChanged(); + } + + void markCompleted() { + finishedAtMs = System.currentTimeMillis(); + state = State.COMPLETED; + fireChanged(); + } + + void markCancelled() { + finishedAtMs = System.currentTimeMillis(); + state = State.CANCELLED; + fireChanged(); + } + + void markFailed(String message) { + finishedAtMs = System.currentTimeMillis(); + errorMessage = message; + state = State.FAILED; + fireChanged(); + } + + private void fireChanged() { + if (listener != null) listener.onTransferChanged(this); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/filetransfer/FileTransferManager.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/filetransfer/FileTransferManager.java new file mode 100644 index 0000000..67977d2 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/filetransfer/FileTransferManager.java @@ -0,0 +1,522 @@ +package eu.lixko.ts3j.client.net.filetransfer; + +import com.github.manevolent.ts3j.api.FileTransferParameters; +import com.github.manevolent.ts3j.command.SingleCommand; +import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; +import com.github.manevolent.ts3j.event.TS3Listener; +import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent; +import com.github.manevolent.ts3j.protocol.ProtocolRole; +import com.github.manevolent.ts3j.protocol.socket.client.LocalTeamspeakClientSocket; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Supplier; + +/** + * Implements the TeamSpeak 3 channel file-transfer protocol on top of a connected + * {@link LocalTeamspeakClientSocket}. + * + *

    Directory operations ({@link #list}, {@link #createDirectory}, {@link #delete}, + * {@link #rename}) are ordinary control commands and run synchronously on the caller's + * thread. Byte transfers ({@link #download}, {@link #upload}) are two-phase: an + * {@code ftinit*} control command negotiates a one-time key, host and port, after which + * a raw TCP connection to the server's file port carries the bytes. That copy runs on a + * background thread and reports through the returned {@link FileTransfer} handle. + */ +public final class FileTransferManager { + + private static final int CONNECT_TIMEOUT_MS = 15_000; + /** How long a download may go without receiving anything before it counts as failed. */ + private static final int STALL_TIMEOUT_MS = 30_000; + private static final int BUFFER_SIZE = 64 * 1024; + /** How long to wait for the server's {@code notifystart*} reply after an {@code ftinit*}. */ + private static final long NEGOTIATE_TIMEOUT_MS = 15_000; + + /** TeamSpeak error id returned by {@code ftgetfilelist} for an empty directory. */ + private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501; + /** How long to wait for the server to finish listing a directory. */ + private static final long LIST_TIMEOUT_MS = 15_000; + + private final LocalTeamspeakClientSocket socket; + /** Host we are connected to, used when the server reports no dedicated file-transfer host. */ + private final Supplier fallbackHost; + private final AtomicInteger clientTransferId = new AtomicInteger(1); + /** Every byte moved so far, for the connection info's transfer rate. */ + private final AtomicLong bytesSent = new AtomicLong(); + private final AtomicLong bytesReceived = new AtomicLong(); + private final ExecutorService transferPool = Executors.newCachedThreadPool(r -> { + Thread t = new Thread(r, "ts3j-filetransfer"); + t.setDaemon(true); + return t; + }); + + /** + * In-flight {@code ftinit*} negotiations keyed by our {@code clientftfid}. The server + * answers an init out-of-band with a {@code notifystart*} (success) or a + * {@code notifystatusfiletransfer} (failure) event, which {@link #ftEventListener} + * routes back to the waiting transfer thread. + */ + private final Map>> pendingInits = new ConcurrentHashMap<>(); + + /** + * The {@code ftgetfilelist} in progress. The server answers that command with a + * {@code notifyfilelist} event per entry and a closing {@code notifyfilelistfinished} + * rather than with rows of the command's own reply, so the entries are collected here + * until the listing ends. One listing may be in flight at a time. + */ + private volatile FileListRequest fileListRequest; + private final TS3Listener ftEventListener = new TS3Listener() { + @Override + public void onUnknownEvent(UnknownTeamspeakEvent e) { + handleFileTransferEvent(e); + } + }; + + public FileTransferManager(LocalTeamspeakClientSocket socket, Supplier fallbackHost) { + this.socket = socket; + this.fallbackHost = fallbackHost; + socket.addListener(ftEventListener); + } + + public long bytesSent() { + return bytesSent.get(); + } + + public long bytesReceived() { + return bytesReceived.get(); + } + + // ---- directory operations ---- + + /** + * Lists the files and subdirectories directly under {@code path} in the given + * channel's repository. Returns an empty list for an empty directory. + * + *

    Blocks until the server has sent the whole listing, so it must not be called from + * the event thread that delivers it. + */ + public List list(int channelId, String channelPassword, String path) + throws Exception { + String directory = path == null || path.isEmpty() ? "/" : path; + SingleCommand cmd = new SingleCommand("ftgetfilelist", ProtocolRole.CLIENT, + new CommandSingleParameter("cid", Integer.toString(channelId)), + new CommandSingleParameter("cpw", channelPassword == null ? "" : channelPassword), + new CommandSingleParameter("path", directory)); + + FileListRequest request = new FileListRequest(channelId, directory); + fileListRequest = request; + try { + socket.executeCommand(cmd).complete(); + // The command's reply only acknowledges it; the entries are events, and the + // server marks their end with notifyfilelistfinished. + request.finished.get(LIST_TIMEOUT_MS, TimeUnit.MILLISECONDS); + } catch (com.github.manevolent.ts3j.command.CommandException e) { + if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e; + } catch (TimeoutException e) { + throw new IOException("The server did not finish listing " + directory); + } finally { + fileListRequest = null; + } + return new ArrayList<>(request.files); + } + + /** Collects one {@code notifyfilelist} entry for the listing in flight. */ + private void collectListEntry(Map row) { + FileListRequest request = fileListRequest; + if (request == null) return; + String cid = row.get("cid"); + if (cid != null && !cid.isEmpty() && parseLong(cid) != request.channelId) return; + String name = row.get("name"); + if (name == null || name.isEmpty()) return; + request.files.add(new RemoteFile( + name, + row.getOrDefault("path", request.path), + parseLong(row.get("size")), + "0".equals(row.get("type")), + parseLong(row.get("datetime")))); + } + + /** Creates a new directory at {@code dirPath} (a full path such as {@code /new}). */ + public void createDirectory(int channelId, String channelPassword, String dirPath) + throws Exception { + SingleCommand cmd = new SingleCommand("ftcreatedir", ProtocolRole.CLIENT, + new CommandSingleParameter("cid", Integer.toString(channelId)), + new CommandSingleParameter("cpw", channelPassword == null ? "" : channelPassword), + new CommandSingleParameter("dirname", dirPath)); + socket.executeCommand(cmd).complete(); + } + + /** Deletes a file or (recursively) a directory at {@code fullPath}. */ + public void delete(int channelId, String channelPassword, String fullPath) + throws Exception { + SingleCommand cmd = new SingleCommand("ftdeletefile", ProtocolRole.CLIENT, + new CommandSingleParameter("cid", Integer.toString(channelId)), + new CommandSingleParameter("cpw", channelPassword == null ? "" : channelPassword), + new CommandSingleParameter("name", fullPath)); + socket.executeCommand(cmd).complete(); + } + + /** Renames or moves a file within the same channel. */ + public void rename(int channelId, String channelPassword, String oldFullPath, String newFullPath) + throws Exception { + SingleCommand cmd = new SingleCommand("ftrenamefile", ProtocolRole.CLIENT, + new CommandSingleParameter("cid", Integer.toString(channelId)), + new CommandSingleParameter("cpw", channelPassword == null ? "" : channelPassword), + new CommandSingleParameter("oldname", oldFullPath), + new CommandSingleParameter("newname", newFullPath)); + socket.executeCommand(cmd).complete(); + } + + // ---- byte transfers ---- + + /** + * Starts downloading {@code remoteFullPath} from the channel to {@code target}. + * Returns immediately with a handle whose progress the caller can observe; the + * copy proceeds on a background thread. + */ + public FileTransfer download(int channelId, String channelPassword, String remoteFullPath, + File target, FileTransfer.Listener listener) { + FileTransfer transfer = new FileTransfer(FileTransfer.Direction.DOWNLOAD, channelId, + fileName(remoteFullPath), target, -1, listener); + transferPool.execute(() -> runDownload(channelId, channelPassword, remoteFullPath, transfer)); + return transfer; + } + + /** + * Starts uploading {@code source} into the channel at {@code remoteFullPath}. + * Returns immediately with a handle whose progress the caller can observe. + */ + public FileTransfer upload(int channelId, String channelPassword, String remoteFullPath, + File source, boolean overwrite, FileTransfer.Listener listener) { + FileTransfer transfer = new FileTransfer(FileTransfer.Direction.UPLOAD, channelId, + fileName(remoteFullPath), source, source.length(), listener); + transferPool.execute(() -> runUpload(channelId, channelPassword, remoteFullPath, source, overwrite, transfer)); + return transfer; + } + + /** + * Downloads a small file straight into memory, blocking until it is complete. + * Intended for icons and other assets that never reach the disk. + */ + public byte[] downloadToMemory(int channelId, String channelPassword, String remoteFullPath, + int maxBytes) throws Exception { + int ftfid = clientTransferId.getAndIncrement(); + SingleCommand cmd = new SingleCommand("ftinitdownload", ProtocolRole.CLIENT, + new CommandSingleParameter("clientftfid", Integer.toString(ftfid)), + new CommandSingleParameter("name", remoteFullPath), + new CommandSingleParameter("cid", Integer.toString(channelId)), + new CommandSingleParameter("cpw", channelPassword == null ? "" : channelPassword), + new CommandSingleParameter("seekpos", "0"), + new CommandSingleParameter("proto", "0")); + + FileTransferParameters params = negotiate(ftfid, cmd); + long size = params.getFileSize(); + if (size <= 0 || size > maxBytes) { + throw new IOException("Unexpected file size " + size + " for " + remoteFullPath); + } + + byte[] data = new byte[(int) size]; + try (Socket fileSocket = openFileSocket(params); + InputStream in = new BufferedInputStream(fileSocket.getInputStream())) { + sendKey(fileSocket, params); + int offset = 0; + while (offset < data.length) { + int read = in.read(data, offset, data.length - offset); + if (read < 0) throw new IOException("File server closed the connection early"); + offset += read; + bytesReceived.addAndGet(read); + } + } + return data; + } + + private void runDownload(int channelId, String channelPassword, String remoteFullPath, + FileTransfer transfer) { + try { + int ftfid = clientTransferId.getAndIncrement(); + SingleCommand cmd = new SingleCommand("ftinitdownload", ProtocolRole.CLIENT, + new CommandSingleParameter("clientftfid", Integer.toString(ftfid)), + new CommandSingleParameter("name", remoteFullPath), + new CommandSingleParameter("cid", Integer.toString(channelId)), + new CommandSingleParameter("cpw", channelPassword == null ? "" : channelPassword), + new CommandSingleParameter("seekpos", "0"), + new CommandSingleParameter("proto", "0")); + + FileTransferParameters params = negotiate(ftfid, cmd); + long size = params.getFileSize(); + transfer.setTotalBytes(size); + + try (Socket fileSocket = openFileSocket(params); + InputStream in = new BufferedInputStream(fileSocket.getInputStream()); + OutputStream fileOut = new BufferedOutputStream(new FileOutputStream(transfer.getLocalFile()))) { + + sendKey(fileSocket, params); + transfer.markActive(); + + byte[] buffer = new byte[BUFFER_SIZE]; + long remaining = size; + while (remaining > 0) { + if (transfer.isCancelRequested()) { + transfer.markCancelled(); + deleteQuietly(transfer.getLocalFile()); + return; + } + int want = (int) Math.min(buffer.length, remaining); + int read = in.read(buffer, 0, want); + if (read < 0) throw new IOException("File server closed the connection early"); + fileOut.write(buffer, 0, read); + remaining -= read; + bytesReceived.addAndGet(read); + transfer.addTransferred(read); + } + } + transfer.markCompleted(); + } catch (Exception e) { + transfer.markFailed(rootMessage(e)); + deleteQuietly(transfer.getLocalFile()); + } + } + + private void runUpload(int channelId, String channelPassword, String remoteFullPath, + File source, boolean overwrite, FileTransfer transfer) { + try { + long size = source.length(); + int ftfid = clientTransferId.getAndIncrement(); + SingleCommand cmd = new SingleCommand("ftinitupload", ProtocolRole.CLIENT, + new CommandSingleParameter("clientftfid", Integer.toString(ftfid)), + new CommandSingleParameter("name", remoteFullPath), + new CommandSingleParameter("cid", Integer.toString(channelId)), + new CommandSingleParameter("cpw", channelPassword == null ? "" : channelPassword), + new CommandSingleParameter("size", Long.toString(size)), + new CommandSingleParameter("overwrite", overwrite ? "1" : "0"), + new CommandSingleParameter("resume", "0"), + new CommandSingleParameter("proto", "0")); + + FileTransferParameters params = negotiate(ftfid, cmd); + // The server may already hold a prefix of the file (resume); start after it. + long seekpos = params.getMap().containsKey("seekpos") ? params.getLong("seekpos") : 0; + if (seekpos < 0 || seekpos > size) seekpos = 0; + + try (Socket fileSocket = openFileSocket(params); + InputStream fileIn = new BufferedInputStream(new FileInputStream(source)); + OutputStream out = new BufferedOutputStream(fileSocket.getOutputStream())) { + + sendKey(fileSocket, params); + transfer.markActive(); + + if (seekpos > 0) { + skipFully(fileIn, seekpos); + transfer.addTransferred(seekpos); + } + + byte[] buffer = new byte[BUFFER_SIZE]; + long remaining = size - seekpos; + while (remaining > 0) { + if (transfer.isCancelRequested()) { + transfer.markCancelled(); + return; + } + int want = (int) Math.min(buffer.length, remaining); + int read = fileIn.read(buffer, 0, want); + if (read < 0) break; // file shorter than announced; stop + out.write(buffer, 0, read); + remaining -= read; + bytesSent.addAndGet(read); + transfer.addTransferred(read); + } + out.flush(); + } + transfer.markCompleted(); + } catch (Exception e) { + transfer.markFailed(rootMessage(e)); + } + } + + /** + * Sends an {@code ftinit*} command and returns the negotiated parameters. The server + * acknowledges the command itself, then reports the transfer's key/host/port + * asynchronously via a {@code notifystart*} event (or a {@code notifystatusfiletransfer} + * on refusal), which {@link #handleFileTransferEvent} feeds back through {@code pendingInits}. + */ + private FileTransferParameters negotiate(int clientTransferId, SingleCommand cmd) throws Exception { + CompletableFuture> future = new CompletableFuture<>(); + pendingInits.put(clientTransferId, future); + try { + // Await the command-level acknowledgement; a hard error (e.g. bad path) throws here. + socket.executeCommand(cmd).complete(); + Map result; + try { + result = future.get(NEGOTIATE_TIMEOUT_MS, TimeUnit.MILLISECONDS); + } catch (ExecutionException e) { + Throwable cause = e.getCause(); + throw cause instanceof Exception ? (Exception) cause : e; + } catch (TimeoutException e) { + throw new IOException("Timed out waiting for the server to start the transfer"); + } + FileTransferParameters params = new FileTransferParameters(result); + String key = params.getFileTransferKey(); + if (key == null || key.isEmpty()) throw new IOException("Server refused the file transfer"); + return params; + } finally { + pendingInits.remove(clientTransferId); + } + } + + /** + * Routes an incoming file-transfer notification to the negotiation that is waiting for + * it. {@code notifystartdownload}/{@code notifystartupload} carry the key, host and port; + * {@code notifystatusfiletransfer} signals a non-zero status (a refusal) before the + * transfer starts. + */ + private void handleFileTransferEvent(UnknownTeamspeakEvent e) { + String command = e.getCommand(); + if (command == null) return; + Map map = e.getMap(); + if (command.equals("notifyfilelist")) { + collectListEntry(map); + return; + } + if (command.equals("notifyfilelistfinished")) { + FileListRequest request = fileListRequest; + if (request != null) request.finished.complete(null); + return; + } + Integer ftfid = tryParseInt(map.get("clientftfid")); + if (ftfid == null) return; + CompletableFuture> future = pendingInits.get(ftfid); + if (future == null) return; + + if (command.equals("notifystartdownload") || command.equals("notifystartupload")) { + future.complete(map); + } else if (command.equals("notifystatusfiletransfer")) { + int status = (int) parseLong(map.get("status")); + if (status != 0) { + String msg = map.get("msg"); + future.completeExceptionally( + new IOException(msg != null && !msg.isEmpty() ? msg : "File transfer failed (status " + status + ")")); + } + } + } + + private Socket openFileSocket(FileTransferParameters params) throws IOException { + Socket socket = new Socket(); + socket.connect(new InetSocketAddress(resolveHost(params.getFileServerHost()), + params.getFileServerPort()), CONNECT_TIMEOUT_MS); + socket.setSoTimeout(STALL_TIMEOUT_MS); + return socket; + } + + /** Sends the negotiated one-time key that authorises this connection to the file port. */ + private static void sendKey(Socket fileSocket, FileTransferParameters params) throws IOException { + OutputStream out = fileSocket.getOutputStream(); + out.write(params.getFileTransferKey().getBytes(StandardCharsets.US_ASCII)); + out.flush(); + } + + /** + * Picks the host to reach the file server. The {@code ip} the server reports may be + * a comma-separated list, empty, or a wildcard; in those cases fall back to the host + * we are already connected to. + */ + private String resolveHost(String reported) { + if (reported != null) { + String first = reported.split(",")[0].trim(); + if (!first.isEmpty() && !first.startsWith("0.0.0.0")) return first; + } + return fallbackHost.get(); + } + + private static void deleteQuietly(File file) { + if (file != null && file.isFile()) { + //noinspection ResultOfMethodCallIgnored + file.delete(); + } + } + + private static void skipFully(InputStream in, long n) throws IOException { + long remaining = n; + while (remaining > 0) { + long skipped = in.skip(remaining); + if (skipped <= 0) { + if (in.read() < 0) throw new IOException("Unexpected end of file while seeking"); + skipped = 1; + } + remaining -= skipped; + } + } + + public void shutdown() { + socket.removeListener(ftEventListener); + for (CompletableFuture> future : pendingInits.values()) { + future.completeExceptionally(new IOException("Disconnected")); + } + pendingInits.clear(); + transferPool.shutdownNow(); + } + + // ---- helpers ---- + + private static String fileName(String fullPath) { + int slash = fullPath.lastIndexOf('/'); + return slash < 0 ? fullPath : fullPath.substring(slash + 1); + } + + private static long parseLong(String s) { + if (s == null || s.isEmpty()) return 0; + try { + return Long.parseLong(s.trim()); + } catch (NumberFormatException e) { + return 0; + } + } + + private static Integer tryParseInt(String s) { + if (s == null || s.isEmpty()) return null; + try { + return Integer.parseInt(s.trim()); + } catch (NumberFormatException e) { + return null; + } + } + + private static String rootMessage(Throwable t) { + Throwable r = t; + while (r.getCause() != null && r.getCause() != r) r = r.getCause(); + String m = r.getMessage(); + return m != null ? m : r.getClass().getSimpleName(); + } + + /** One in-flight {@code ftgetfilelist} and the entries received for it so far. */ + private static final class FileListRequest { + final int channelId; + final String path; + final List files = new java.util.concurrent.CopyOnWriteArrayList<>(); + final CompletableFuture finished = new CompletableFuture<>(); + + FileListRequest(int channelId, String path) { + this.channelId = channelId; + this.path = path; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/filetransfer/RemoteFile.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/filetransfer/RemoteFile.java new file mode 100644 index 0000000..a7cc388 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/filetransfer/RemoteFile.java @@ -0,0 +1,49 @@ +package eu.lixko.ts3j.client.net.filetransfer; + +/** + * One entry in a channel's file repository, as returned by {@code ftgetfilelist}. + * A UI-facing value type that keeps the reusable core free of ts3j API classes. + */ +public final class RemoteFile { + + private final String name; + /** Parent directory path, always ending in {@code /} (e.g. {@code /} or {@code /sub/}). */ + private final String parentPath; + private final long size; + private final boolean directory; + private final long lastModifiedEpochSec; + + public RemoteFile(String name, String parentPath, long size, boolean directory, long lastModifiedEpochSec) { + this.name = name; + this.parentPath = parentPath == null || parentPath.isEmpty() ? "/" : parentPath; + this.size = size; + this.directory = directory; + this.lastModifiedEpochSec = lastModifiedEpochSec; + } + + public String getName() { + return name; + } + + public String getParentPath() { + return parentPath; + } + + /** Full server path including the file name, e.g. {@code /sub/clip.ogg}. */ + public String getFullPath() { + String base = parentPath.endsWith("/") ? parentPath : parentPath + "/"; + return base + name; + } + + public long getSize() { + return size; + } + + public boolean isDirectory() { + return directory; + } + + public long getLastModifiedEpochSec() { + return lastModifiedEpochSec; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/proto/ProtobufReader.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/proto/ProtobufReader.java new file mode 100644 index 0000000..26ab961 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/proto/ProtobufReader.java @@ -0,0 +1,107 @@ +package eu.lixko.ts3j.client.proto; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +/** + * Minimal protocol-buffers wire-format cursor: walks a message field by field + * without needing a compiled schema. Callers switch on {@link #fieldNumber()} + * and pull the value with the accessor matching the field's declared type; + * anything else is skipped with {@link #skip()}. + */ +public final class ProtobufReader { + + private static final int VARINT = 0; + private static final int FIXED64 = 1; + private static final int LENGTH_DELIMITED = 2; + private static final int FIXED32 = 5; + + private final byte[] data; + private final int end; + private int pos; + private int fieldNumber; + private int wireType; + + public ProtobufReader(byte[] data) { + this(data, 0, data.length); + } + + private ProtobufReader(byte[] data, int start, int end) { + this.data = data; + this.pos = start; + this.end = end; + } + + /** Advances to the next field; {@code false} at the end of the message. */ + public boolean next() throws IOException { + if (pos >= end) return false; + long tag = readVarint(); + fieldNumber = (int) (tag >>> 3); + wireType = (int) (tag & 7); + if (fieldNumber == 0) throw new IOException("Invalid protobuf tag"); + return true; + } + + public int fieldNumber() { + return fieldNumber; + } + + public long readVarint() throws IOException { + long result = 0; + for (int shift = 0; shift < 64; shift += 7) { + if (pos >= end) throw new IOException("Truncated protobuf varint"); + int b = data[pos++]; + result |= (long) (b & 0x7F) << shift; + if ((b & 0x80) == 0) return result; + } + throw new IOException("Malformed protobuf varint"); + } + + public boolean readBool() throws IOException { + return readVarint() != 0; + } + + public String readString() throws IOException { + int length = readLength(); + String s = new String(data, pos, length, StandardCharsets.UTF_8); + pos += length; + return s; + } + + public byte[] readBytes() throws IOException { + int length = readLength(); + byte[] out = new byte[length]; + System.arraycopy(data, pos, out, 0, length); + pos += length; + return out; + } + + /** A reader positioned over an embedded message; this reader moves past it. */ + public ProtobufReader readMessage() throws IOException { + int length = readLength(); + ProtobufReader nested = new ProtobufReader(data, pos, pos + length); + pos += length; + return nested; + } + + public void skip() throws IOException { + switch (wireType) { + case VARINT -> readVarint(); + case FIXED64 -> pos += 8; + case LENGTH_DELIMITED -> { + int length = readLength(); + pos += length; + } + case FIXED32 -> pos += 4; + default -> throw new IOException("Unsupported protobuf wire type " + wireType); + } + if (pos > end) throw new IOException("Truncated protobuf message"); + } + + private int readLength() throws IOException { + if (wireType != LENGTH_DELIMITED) throw new IOException("Field " + fieldNumber + " is not length-delimited"); + long length = readVarint(); + if (length < 0 || pos + length > end) throw new IOException("Truncated protobuf message"); + return (int) length; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/proto/ProtobufWriter.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/proto/ProtobufWriter.java new file mode 100644 index 0000000..b289eb4 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/proto/ProtobufWriter.java @@ -0,0 +1,47 @@ +package eu.lixko.ts3j.client.proto; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; + +/** Builds a protocol-buffers message field by field; the counterpart of {@link ProtobufReader}. */ +public final class ProtobufWriter { + + private final ByteArrayOutputStream out = new ByteArrayOutputStream(); + + public ProtobufWriter varint(int field, long value) { + tag(field, 0); + rawVarint(value); + return this; + } + + public ProtobufWriter string(int field, String value) { + return bytes(field, value.getBytes(StandardCharsets.UTF_8)); + } + + public ProtobufWriter bytes(int field, byte[] value) { + tag(field, 2); + rawVarint(value.length); + out.write(value, 0, value.length); + return this; + } + + public ProtobufWriter message(int field, ProtobufWriter message) { + return bytes(field, message.toByteArray()); + } + + public byte[] toByteArray() { + return out.toByteArray(); + } + + private void tag(int field, int wireType) { + rawVarint(((long) field << 3) | wireType); + } + + private void rawVarint(long value) { + while ((value & ~0x7FL) != 0) { + out.write((int) (value & 0x7F) | 0x80); + value >>>= 7; + } + out.write((int) value); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/MixdownSink.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/MixdownSink.java new file mode 100644 index 0000000..55ca371 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/MixdownSink.java @@ -0,0 +1,85 @@ +package eu.lixko.ts3j.client.recording; + +import eu.lixko.ts3j.client.audio.VoiceFormat; +import eu.lixko.ts3j.client.audio.ogg.OpusHeaders; +import eu.lixko.ts3j.client.audio.opus.OpusCodec; +import eu.lixko.ts3j.client.audio.opus.OpusEncoder; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.TreeMap; + +/** Mixes every speaker down onto one mono track, written to the file as it goes. */ +final class MixdownSink implements RecordingSink { + + private static final int BITRATE = 64_000; + /** How long a frame waits for the other speakers' frames of the same moment before it is mixed. */ + private static final int MIX_DELAY_FRAMES = 25; + + private final Path file; + private final OpusEncoder encoder; + private final OggOpusStream stream; + /** Frames not yet mixed, by their place on the timeline. */ + private final TreeMap pending = new TreeMap<>(); + private long mixed; + + MixdownSink(Path file, OpusCodec opus) throws IOException { + this.file = file; + this.encoder = RecordingEncoders.mono(opus, BITRATE); + try { + this.stream = new OggOpusStream(file, OpusHeaders.mono(OggOpusStream.PRE_SKIP, VoiceFormat.SAMPLE_RATE), + OpusHeaders.tags(opus.version(), List.of())); + } catch (IOException e) { + encoder.close(); + throw e; + } + } + + @Override + public void write(Track track, long index, float[] frame) { + if (index < mixed) return; // too late to be mixed in + pending.merge(index, frame, (sum, more) -> { + for (int i = 0; i < sum.length; i++) sum[i] += more[i]; + return sum; + }); + } + + @Override + public void advance(long now) throws IOException { + mixUpTo(now - MIX_DELAY_FRAMES); + } + + private void mixUpTo(long end) throws IOException { + for (; mixed < end; mixed++) { + float[] frame = pending.remove(mixed); + if (frame == null) { + frame = RecordingEncoders.SILENT_FRAME; + } else { + for (int i = 0; i < frame.length; i++) frame[i] = Math.max(-1f, Math.min(1f, frame[i])); + } + stream.write(encoder.encode(frame)); + } + } + + @Override + public List finish(long end) throws IOException { + long frames = pending.isEmpty() ? end : Math.max(end, pending.lastKey() + 1); + frames = Math.max(frames, mixed); + mixUpTo(frames); + // One more frame brings out what the encoder's delay still holds. + stream.write(encoder.encode(RecordingEncoders.SILENT_FRAME)); + stream.finish(frames); + encoder.close(); + return List.of(file); + } + + @Override + public void abort() { + try { + stream.close(); + } catch (IOException ignored) { + } + encoder.close(); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/MultitrackSink.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/MultitrackSink.java new file mode 100644 index 0000000..27c2e21 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/MultitrackSink.java @@ -0,0 +1,242 @@ +package eu.lixko.ts3j.client.recording; + +import eu.lixko.ts3j.client.audio.VoiceFormat; +import eu.lixko.ts3j.client.audio.ogg.OpusHeaders; +import eu.lixko.ts3j.client.audio.ogg.SelfDelimitedOpus; +import eu.lixko.ts3j.client.audio.opus.OpusCodec; +import eu.lixko.ts3j.client.audio.opus.OpusEncoder; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Gives every speaker a channel of their own: one uncoupled mono Opus stream each, up to + * {@link OpusHeaders#MAX_DISCRETE_CHANNELS} to a file. How many channels a file has goes in + * its header, so tracks are encoded into spool files as the recording runs and only put + * together into the Ogg files once it stops. A track is silent from the start of the + * recording until its speaker first speaks. + */ +final class MultitrackSink implements RecordingSink { + + private static final int BITRATE = 48_000; + /** Pauses up to this long are encoded as they are; longer ones are filled with a stock silent packet. */ + private static final int ENCODED_PAUSE_FRAMES = 50; + /** + * Frames of silence a fresh encoder encodes before its first speech: its first packets + * after the stock silence come out faded in. + */ + private static final int PRIMING_FRAMES = 5; + + private final Path file; + private final OpusCodec opus; + private final Path spoolDir; + private final byte[] silence; + /** In the order speakers first spoke, which is the order of the channels. */ + private final Map spools = new LinkedHashMap<>(); + + MultitrackSink(Path file, OpusCodec opus) throws IOException { + this.file = file; + this.opus = opus; + this.silence = RecordingEncoders.silentPacket(opus, BITRATE); + Path dir = file.toAbsolutePath().getParent(); + this.spoolDir = Files.createTempDirectory(dir, "." + file.getFileName() + "-"); + } + + @Override + public void write(Track track, long index, float[] frame) throws IOException { + Spool spool = spools.get(track); + if (spool == null) { + spool = new Spool(Math.max(0, index - PRIMING_FRAMES), spoolDir.resolve(spools.size() + ".spool")); + spools.put(track, spool); + } + spool.write(index, frame); + } + + @Override + public void advance(long now) { + } + + @Override + public List finish(long end) throws IOException { + long frames = end; + for (Spool spool : spools.values()) frames = Math.max(frames, spool.next); + for (Spool spool : spools.values()) spool.close(); + // Every track reaches one frame past the end, the encoder's delay. + long total = frames + 1; + + List tracks = new ArrayList<>(spools.keySet()); + List files = new ArrayList<>(); + int perFile = OpusHeaders.MAX_DISCRETE_CHANNELS; + // Even nobody speaking leaves a file behind, as long as the recording ran. + for (int first = 0; first < Math.max(1, tracks.size()); first += perFile) { + Path path = first == 0 ? file : numbered(file, first / perFile + 1); + mux(tracks.subList(first, Math.min(tracks.size(), first + perFile)), path, total, frames); + files.add(path); + } + deleteSpools(); + return files; + } + + /** {@code name.ogg} becomes {@code name-2.ogg}. */ + private static Path numbered(Path file, int number) { + String name = file.getFileName().toString(); + int dot = name.lastIndexOf('.'); + String numbered = dot > 0 + ? name.substring(0, dot) + "-" + number + name.substring(dot) + : name + "-" + number; + return file.resolveSibling(numbered); + } + + private void mux(List tracks, Path path, long total, long frames) throws IOException { + int channels = Math.max(1, tracks.size()); + byte[] head = channels == 1 + ? OpusHeaders.mono(OggOpusStream.PRE_SKIP, VoiceFormat.SAMPLE_RATE) + : OpusHeaders.discrete(channels, OggOpusStream.PRE_SKIP, VoiceFormat.SAMPLE_RATE); + List comments = new ArrayList<>(); + for (int i = 0; i < tracks.size(); i++) { + comments.add("CHANNEL" + (i + 1) + "_NAME=" + tracks.get(i).name); + comments.add("CHANNEL" + (i + 1) + "_UID=" + tracks.get(i).speakerId); + } + + List readers = new ArrayList<>(); + try (OggOpusStream stream = new OggOpusStream(path, head, OpusHeaders.tags(opus.version(), comments))) { + for (Track track : tracks) readers.add(new SpoolReader(spools.get(track))); + List packets = new ArrayList<>(channels); + for (long f = 0; f < total; f++) { + packets.clear(); + for (SpoolReader reader : readers) packets.add(reader.packetAt(f)); + if (packets.isEmpty()) packets.add(silence); + stream.write(SelfDelimitedOpus.join(packets)); + } + stream.finish(frames); + } finally { + for (SpoolReader reader : readers) reader.close(); + } + } + + @Override + public void abort() { + for (Spool spool : spools.values()) { + try { + spool.close(); + } catch (IOException ignored) { + } + } + deleteSpools(); + } + + private void deleteSpools() { + for (Spool spool : spools.values()) { + try { + Files.deleteIfExists(spool.path); + } catch (IOException ignored) { + } + } + try { + Files.deleteIfExists(spoolDir); + } catch (IOException ignored) { + } + } + + /** + * One track's packets from its first frame on. Each entry is a packet's length and bytes, + * or a negative count of frames of silence. + */ + private final class Spool { + final long start; + final Path path; + private final DataOutputStream out; + /** The frame after the last one written. */ + long next; + /** Encodes the current talk burst; a new burst after a long pause gets a fresh one. */ + private OpusEncoder encoder; + + Spool(long start, Path path) throws IOException { + this.start = start; + this.next = start; + this.path = path; + this.out = new DataOutputStream(new BufferedOutputStream(Files.newOutputStream(path), 1 << 14)); + } + + void write(long index, float[] frame) throws IOException { + if (index - next > ENCODED_PAUSE_FRAMES) { + endBurst(); + int silent = (int) (index - next - PRIMING_FRAMES); + out.writeInt(-silent); + next += silent; + } + while (next < index) packet(encoder().encode(RecordingEncoders.SILENT_FRAME)); + packet(encoder().encode(frame)); + } + + private OpusEncoder encoder() { + if (encoder == null) encoder = RecordingEncoders.mono(opus, BITRATE); + return encoder; + } + + private void packet(byte[] packet) throws IOException { + out.writeInt(packet.length); + out.write(packet); + next++; + } + + /** Lets the encoder play out the audio its delay still holds. */ + private void endBurst() throws IOException { + if (encoder == null) return; + packet(encoder.encode(RecordingEncoders.SILENT_FRAME)); + encoder.close(); + encoder = null; + } + + void close() throws IOException { + try { + endBurst(); + } finally { + out.close(); + } + } + } + + private final class SpoolReader implements AutoCloseable { + private final Spool spool; + private final DataInputStream in; + private int silentFrames; + + SpoolReader(Spool spool) throws IOException { + this.spool = spool; + this.in = new DataInputStream(new BufferedInputStream(Files.newInputStream(spool.path), 1 << 14)); + } + + /** Must be asked for every frame in turn. */ + byte[] packetAt(long frame) throws IOException { + if (frame < spool.start || frame >= spool.next) return silence; + if (silentFrames > 0) { + silentFrames--; + return silence; + } + int length = in.readInt(); + if (length < 0) { + silentFrames = -length - 1; + return silence; + } + return in.readNBytes(length); + } + + @Override + public void close() { + try { + in.close(); + } catch (IOException ignored) { + } + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/OggOpusStream.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/OggOpusStream.java new file mode 100644 index 0000000..0a135af --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/OggOpusStream.java @@ -0,0 +1,55 @@ +package eu.lixko.ts3j.client.recording; + +import eu.lixko.ts3j.client.audio.VoiceFormat; +import eu.lixko.ts3j.client.audio.ogg.OggPageWriter; +import eu.lixko.ts3j.client.audio.ogg.OpusHeaders; + +import java.io.BufferedOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.concurrent.ThreadLocalRandom; + +/** An Ogg Opus file written a 20 ms packet at a time. */ +final class OggOpusStream implements AutoCloseable { + + static final int PRE_SKIP = OpusHeaders.LIBOPUS_PRE_SKIP; + + private final OutputStream file; + private final OggPageWriter ogg; + /** The latest packet, held back until it is known whether it ends the stream. */ + private byte[] held; + private long packets; + + OggOpusStream(Path path, byte[] head, byte[] tags) throws IOException { + file = new BufferedOutputStream(Files.newOutputStream(path), 1 << 16); + ogg = new OggPageWriter(file, ThreadLocalRandom.current().nextInt()); + ogg.write(head, 0); + ogg.flush(); + ogg.write(tags, 0); + ogg.flush(); + } + + void write(byte[] packet) throws IOException { + if (held != null) ogg.write(held, packets * VoiceFormat.FRAME_SIZE); + held = packet; + packets++; + } + + /** + * Ends the stream after {@code frames} frames of audio; the packets written must reach + * past them by the encoder's delay. + */ + void finish(long frames) throws IOException { + if (held != null) ogg.write(held, PRE_SKIP + frames * VoiceFormat.FRAME_SIZE); + held = null; + ogg.finish(); + file.close(); + } + + @Override + public void close() throws IOException { + file.close(); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/RecordingEncoders.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/RecordingEncoders.java new file mode 100644 index 0000000..8c719f3 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/RecordingEncoders.java @@ -0,0 +1,33 @@ +package eu.lixko.ts3j.client.recording; + +import eu.lixko.ts3j.client.audio.VoiceFormat; +import eu.lixko.ts3j.client.audio.opus.OpusCodec; +import eu.lixko.ts3j.client.audio.opus.OpusEncoder; + +/** The Opus encoders a recording's tracks are encoded with. */ +final class RecordingEncoders { + + static final float[] SILENT_FRAME = new float[VoiceFormat.FRAME_SIZE]; + + private RecordingEncoders() { + } + + static OpusEncoder mono(OpusCodec opus, int bitrate) { + OpusEncoder encoder = opus.createEncoder(VoiceFormat.SAMPLE_RATE, VoiceFormat.FRAME_SIZE, 1, + OpusCodec.Application.AUDIO); + encoder.setBitrate(bitrate); + encoder.setVbr(true); + encoder.setComplexity(10); + return encoder; + } + + /** A packet that decodes to a frame of silence, to stand in where a track has nothing. */ + static byte[] silentPacket(OpusCodec opus, int bitrate) { + try (OpusEncoder encoder = mono(opus, bitrate)) { + byte[] packet = null; + // Past the first frames, which still carry the encoder's start-up. + for (int i = 0; i < 4; i++) packet = encoder.encode(SILENT_FRAME); + return packet; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/RecordingSink.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/RecordingSink.java new file mode 100644 index 0000000..f84f177 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/RecordingSink.java @@ -0,0 +1,26 @@ +package eu.lixko.ts3j.client.recording; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; + +/** Where a recording's frames are encoded and stored; driven from the recorder's one thread. */ +interface RecordingSink { + + /** @param index the frame's place on the timeline, past every earlier frame of the track */ + void write(Track track, long index, float[] frame) throws IOException; + + /** The clock reached frame {@code now}; frames well behind it may be finalised. */ + void advance(long now) throws IOException; + + /** + * Writes everything out, ending the recording at frame {@code end} or after the last + * frame written, whichever is later. + * + * @return the files written + */ + List finish(long end) throws IOException; + + /** Gives up after a failure, releasing what is held. */ + void abort(); +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/Track.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/Track.java new file mode 100644 index 0000000..6e82a83 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/Track.java @@ -0,0 +1,49 @@ +package eu.lixko.ts3j.client.recording; + +import java.util.concurrent.TimeUnit; + +/** + * One speaker in a recording: where each of their frames goes on the recording's timeline. + * + *

    Frames arrive as they are played, 20 ms apart within a talk burst, so a burst is + * laid down back to back from where its first frame arrived; scheduling jitter then never + * tears holes into it. Only when the speaker's clock drifts too far from the recording's + * is the burst moved back into place. + */ +final class Track { + + /** A pause longer than this starts a new talk burst, placed afresh. */ + private static final long BURST_GAP_NANOS = TimeUnit.MILLISECONDS.toNanos(60); + /** How many frames a burst may run behind or ahead of the clock before it is moved. */ + private static final int MAX_DRIFT_FRAMES = 5; + + final String speakerId; + final String name; + + private long next = -1; + private long lastNanos; + + Track(String speakerId, String name) { + this.speakerId = speakerId; + this.name = name; + } + + /** + * @param due the frame the clock says was playing when the frame arrived + * @return where the frame goes, never before an earlier one; -1 to drop it, for a burst + * that has run too far ahead + */ + long place(long due, long nanos) { + long index; + if (next < 0 || nanos - lastNanos > BURST_GAP_NANOS) { + index = Math.max(next, due); + } else if (next - due > MAX_DRIFT_FRAMES) { + return -1; + } else { + index = due - next > MAX_DRIFT_FRAMES ? due : next; + } + next = index + 1; + lastNanos = nanos; + return index; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/VoiceRecorder.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/VoiceRecorder.java new file mode 100644 index 0000000..1dc65b1 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/recording/VoiceRecorder.java @@ -0,0 +1,171 @@ +package eu.lixko.ts3j.client.recording; + +import eu.lixko.ts3j.client.audio.VoiceFormat; +import eu.lixko.ts3j.client.audio.opus.OpusCodec; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.LongSupplier; + +/** + * Records voice into Ogg Opus: everyone mixed down onto one mono track, or every speaker + * on a channel of their own. Speakers are told apart by their unique id, so somebody who + * reconnects keeps their channel. + * + *

    Frames are handed in as they are played and encoded on a thread of the recorder's + * own; {@link #offer} never blocks, so it may be called from audio threads. + */ +public final class VoiceRecorder { + + public enum Mode { + /** All speakers mixed down to mono. */ + MIXED, + /** A channel per speaker, as many files as it takes. */ + MULTITRACK + } + + private static final int FRAME = VoiceFormat.FRAME_SIZE; + private static final long FRAME_NANOS = TimeUnit.SECONDS.toNanos(FRAME) / VoiceFormat.SAMPLE_RATE; + /** How often the writer looks at the clock while nobody speaks. */ + private static final long IDLE_POLL_MILLIS = 100; + + private record Frame(String speakerId, String nickname, long nanos, float[] mono) { + } + + private record Stop(long nanos) { + } + + private final Mode mode; + private final Path file; + private final Map namesAtStart; + private final RecordingSink sink; + private final LongSupplier clock; + private final long startNanos; + private final LinkedBlockingQueue queue = new LinkedBlockingQueue<>(); + private final AtomicBoolean stopped = new AtomicBoolean(); + private final CompletableFuture> done = new CompletableFuture<>(); + /** Touched only by the writer thread. */ + private final Map tracks = new HashMap<>(); + + /** + * Starts recording into {@code file}; a multitrack recording with more speakers than one + * file holds continues into {@code name-2.ogg} and so on. + * + * @param namesAtStart nicknames by unique id of everyone present now, which name their + * channels; later arrivals are named as they first speak + */ + public static VoiceRecorder start(Mode mode, Path file, OpusCodec opus, Map namesAtStart) + throws IOException { + return start(mode, file, opus, namesAtStart, System::nanoTime); + } + + /** @param clock nanoseconds, as {@link System#nanoTime} counts them */ + static VoiceRecorder start(Mode mode, Path file, OpusCodec opus, Map namesAtStart, + LongSupplier clock) throws IOException { + RecordingSink sink = mode == Mode.MIXED ? new MixdownSink(file, opus) : new MultitrackSink(file, opus); + VoiceRecorder recorder = new VoiceRecorder(mode, file, namesAtStart, sink, clock); + Thread writer = new Thread(recorder::run, "ts3j-recorder"); + writer.setDaemon(true); + writer.start(); + return recorder; + } + + private VoiceRecorder(Mode mode, Path file, Map namesAtStart, RecordingSink sink, + LongSupplier clock) { + this.clock = clock; + this.startNanos = clock.getAsLong(); + this.mode = mode; + this.file = file; + this.namesAtStart = Map.copyOf(namesAtStart); + this.sink = sink; + } + + public Mode mode() { + return mode; + } + + public Path file() { + return file; + } + + /** + * Takes a frame a speaker is being heard with. Copied, so the caller may reuse it. + * + * @param pcm interleaved samples in [-1, 1] + * @param frames samples per channel, at most one 20 ms frame + */ + public void offer(String speakerId, String nickname, float[] pcm, int channels, int frames) { + if (stopped.get() || frames <= 0 || speakerId == null || speakerId.isEmpty()) return; + long now = clock.getAsLong(); + float[] mono = new float[FRAME]; + int n = Math.min(frames, FRAME); + if (channels == 1) { + System.arraycopy(pcm, 0, mono, 0, n); + } else { + for (int i = 0; i < n; i++) { + float sum = 0; + for (int c = 0; c < channels; c++) sum += pcm[i * channels + c]; + mono[i] = sum / channels; + } + } + queue.add(new Frame(speakerId, nickname, now, mono)); + } + + /** + * Stops recording. The files are finished on the recorder's thread, which for a long + * multitrack recording takes a moment. + * + * @return the files written, once they are; failed if the recording could not be written + */ + public CompletableFuture> stop() { + if (stopped.compareAndSet(false, true)) queue.add(new Stop(clock.getAsLong())); + return done; + } + + /** Completes when the recording ends, whether stopped or failed. */ + public CompletableFuture> whenDone() { + return done; + } + + private void run() { + try { + while (true) { + Object item = queue.poll(IDLE_POLL_MILLIS, TimeUnit.MILLISECONDS); + if (item instanceof Stop stop) { + done.complete(sink.finish(frameAt(stop.nanos()))); + return; + } + // Frames are queued in the order they were played, so a frame's own time is + // as far as the clock may be trusted while more are still queued behind it. + if (item instanceof Frame frame) { + place(frame); + sink.advance(frameAt(frame.nanos())); + } else { + sink.advance(frameAt(clock.getAsLong())); + } + } + } catch (Throwable e) { + stopped.set(true); + sink.abort(); + done.completeExceptionally(e); + } + } + + private void place(Frame frame) throws IOException { + Track track = tracks.computeIfAbsent(frame.speakerId(), id -> + new Track(id, namesAtStart.getOrDefault(id, frame.nickname()))); + long index = track.place(frameAt(frame.nanos()), frame.nanos()); + if (index >= 0) sink.write(track, index, frame.mono()); + } + + private long frameAt(long nanos) { + return Math.max(0, (nanos - startNanos) / FRAME_NANOS); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/SelfState.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/SelfState.java new file mode 100644 index 0000000..538cdcb --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/SelfState.java @@ -0,0 +1,36 @@ +package eu.lixko.ts3j.client.session; + +/** + * The state of the local client on one server, as the tree shows it for any other + * client — the states are listed in the order the official client gives them + * priority, the strongest one first. + */ +public enum SelfState { + + DISCONNECTED("Not connected", null), + DEAFENED("Speakers muted", "OUTPUT_MUTED"), + MIC_MUTED("Microphone muted", "INPUT_MUTED"), + MIC_LOCAL_MUTED("Microphone locally muted", "INPUT_MUTED_LOCAL"), + AWAY("Away", "AWAY"), + COMMANDER_TALKING("Talking (channel commander)", "PLAYER_COMMANDER_ON"), + COMMANDER("Channel commander", "PLAYER_COMMANDER_OFF"), + TALKING("Talking", "PLAYER_ON"), + IDLE("Connected", "PLAYER_OFF"); + + private final String label; + private final String iconKey; + + SelfState(String label, String iconKey) { + this.label = label; + this.iconKey = iconKey; + } + + public String label() { + return label; + } + + /** The icon pack key the state is drawn with, or {@code null} for the app's own icon. */ + public String iconKey() { + return iconKey; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerLink.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerLink.java new file mode 100644 index 0000000..dd5d62b --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerLink.java @@ -0,0 +1,145 @@ +package eu.lixko.ts3j.client.session; + +import eu.lixko.ts3j.client.config.Bookmark; + +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.util.Locale; + +/** + * A {@code ts3server://} link, as web pages and chats hand them out: + * {@code ts3server://host[:port]?port=…&nickname=…&password=…&channel=A/B&cid=… + * &channelpassword=…&token=…&addbookmark=…}. Every parameter is optional. + */ +public final class ServerLink { + + public static final String SCHEME = "ts3server"; + private static final String PREFIX = SCHEME + "://"; + private static final int DEFAULT_PORT = 9987; + + public final String address; + public final int port; + /** Empty for the identity's or the global nickname. */ + public final String nickname; + public final String password; + /** A "/"-separated path or {@code "/"}, as {@link Bookmark#channel}; empty for the default channel. */ + public final String channel; + public final String channelPassword; + /** A privilege key to use once connected; empty for none. */ + public final String token; + /** A name to bookmark the server under, or empty when the link does not ask for a bookmark. */ + public final String bookmarkLabel; + + private ServerLink(String address, int port, String nickname, String password, String channel, + String channelPassword, String token, String bookmarkLabel) { + this.address = address; + this.port = port; + this.nickname = nickname; + this.password = password; + this.channel = channel; + this.channelPassword = channelPassword; + this.token = token; + this.bookmarkLabel = bookmarkLabel; + } + + /** Where a bookmark leads, as a link without a privilege key would. */ + public static ServerLink of(Bookmark b) { + return new ServerLink(b.address.trim(), b.port, orEmpty(b.nickname), orEmpty(b.password), orEmpty(b.channel), + orEmpty(b.channelPassword), "", ""); + } + + private static String orEmpty(String s) { + return s == null ? "" : s; + } + + public static boolean isLink(String href) { + return href != null && href.regionMatches(true, 0, PREFIX, 0, PREFIX.length()); + } + + /** Parses a link, or returns {@code null} if it is not one or names no server. */ + public static ServerLink parse(String href) { + if (!isLink(href)) return null; + String rest = href.substring(PREFIX.length()).trim(); + int query = rest.indexOf('?'); + String authority = query < 0 ? rest : rest.substring(0, query); + String params = query < 0 ? "" : rest.substring(query + 1); + int slash = authority.indexOf('/'); + if (slash >= 0) authority = authority.substring(0, slash); + + String host = authority; + int port = DEFAULT_PORT; + if (authority.startsWith("[")) { + int close = authority.indexOf(']'); + if (close < 0) return null; + host = authority.substring(1, close); + port = portAfter(authority.substring(close + 1), port); + } else if (authority.indexOf(':') == authority.lastIndexOf(':') && authority.indexOf(':') >= 0) { + host = authority.substring(0, authority.indexOf(':')); + port = portAfter(authority.substring(authority.indexOf(':')), port); + } + host = decode(host).trim(); + if (host.isEmpty()) return null; + + String nickname = "", password = "", channel = "", channelId = "", channelPassword = "", token = "", label = ""; + for (String pair : params.split("&")) { + int eq = pair.indexOf('='); + String key = (eq < 0 ? pair : pair.substring(0, eq)).toLowerCase(Locale.ROOT); + String value = eq < 0 ? "" : decode(pair.substring(eq + 1)); + switch (key) { + case "port" -> port = parsePort(value, port); + case "nickname" -> nickname = value.trim(); + case "password" -> password = value; + case "channel" -> channel = value.trim(); + case "cid" -> channelId = value.trim(); + case "channelpassword" -> channelPassword = value; + case "token" -> token = value.trim(); + case "addbookmark" -> label = value.trim(); + default -> { + } + } + } + // A channel id is exact, where a path may have been renamed since the link was made. + if (isChannelId(channelId)) channel = "/" + channelId; + return new ServerLink(host, port, nickname, password, channel, channelPassword, token, label); + } + + /** Whether this link leads to the server at {@code address}:{@code port}. */ + public boolean pointsAt(String address, int port) { + return this.port == port && address != null && this.address.equalsIgnoreCase(address.trim()); + } + + /** A bookmark of the server the link leads to, under the name it asks for, else its address. */ + public Bookmark toBookmark() { + Bookmark b = new Bookmark(bookmarkLabel.isEmpty() ? address : bookmarkLabel, address, port, nickname, password); + b.channel = channel; + b.channelPassword = channelPassword; + return b; + } + + /** A positive number; 0 names no channel. */ + private static boolean isChannelId(String s) { + return !s.isEmpty() && s.chars().allMatch(Character::isDigit) && s.chars().anyMatch(c -> c != '0'); + } + + private static int portAfter(String colonPort, int fallback) { + return colonPort.startsWith(":") ? parsePort(colonPort.substring(1), fallback) : fallback; + } + + private static int parsePort(String value, int fallback) { + try { + int port = Integer.parseInt(value.trim()); + return port > 0 && port <= 65535 ? port : fallback; + } catch (NumberFormatException e) { + return fallback; + } + } + + /** Percent-decodes; a '+' stays one, as TeamSpeak reads its links. */ + private static String decode(String s) { + try { + return URLDecoder.decode(s.replace("+", "%2B"), "UTF-8"); + } catch (UnsupportedEncodingException | IllegalArgumentException e) { + return s; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java new file mode 100644 index 0000000..8770da3 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java @@ -0,0 +1,844 @@ +package eu.lixko.ts3j.client.session; + +import eu.lixko.ts3j.client.audio.AudioBackend; +import eu.lixko.ts3j.client.config.Bookmark; +import eu.lixko.ts3j.client.config.IdentityEntry; +import eu.lixko.ts3j.client.config.IdentityStore; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.myts.ChatAttachment; +import eu.lixko.ts3j.client.myts.ChatAttachments; +import eu.lixko.ts3j.client.myts.MyTsException; +import eu.lixko.ts3j.client.contacts.ContactStore; +import eu.lixko.ts3j.client.net.ChannelNode; +import eu.lixko.ts3j.client.net.ClientEntry; +import eu.lixko.ts3j.client.net.ConnectionListener; +import eu.lixko.ts3j.client.net.ServerModel; +import eu.lixko.ts3j.client.net.TeamspeakConnection; +import eu.lixko.ts3j.client.net.Whisper; +import eu.lixko.ts3j.client.recording.VoiceRecorder; +import eu.lixko.ts3j.client.sound.SoundNotifier; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Collectors; + +/** + * One server connection and the local client's state on it, independent of any UI: the + * connection lifecycle, the microphone/speaker/away flags, chat sending and channel + * lookups. A frontend keeps one per server tab and hears from it through {@link Listener}. + * + *

    Listener callbacks arrive on connection threads, so frontends marshal them onto their + * UI thread. The getters may be called from any thread. + */ +public final class ServerSession { + + /** Everything a {@link ConnectionListener} hears, plus what the session adds. */ + public interface Listener extends ConnectionListener { + + /** + * The session's title, status, connecting state or self flags changed. Also + * delivers what {@link #onStatus} does, so frontends usually only need this one. + */ + void onSessionChanged(); + + /** A line for the chat's own log: connection progress, errors, pokes. */ + void onSystemMessage(String text); + + /** + * The local client sent a chat message. + * + * @param peerClientId the recipient of a private message, else 0 + * @param peerName the recipient's display name for a private message, else empty + */ + void onOwnChat(ChatScope scope, int peerClientId, String peerName, String text); + + /** + * The server's icon is known or changed (0: it has none), and is on its way to the + * icon cache, so bookmarks leading here can show it while not connected. + */ + default void onServerIconChanged(long iconId) { + } + } + + private final Settings settings; + private final IdentityStore identities; + private final Listener listener; + private final TeamspeakConnection conn; + + private volatile String title = "New connection"; + private volatile String status = "Not connected"; + private volatile boolean connecting; + /** Identity used for the current connection, so it can be saved into a bookmark. */ + private volatile String identityId = ""; + /** How the last connect was made, for {@link #reconnect}; null before the first one. */ + private volatile Target lastTarget; + /** The channel we were in when the connection last went, to return to on a reconnect. */ + private volatile String lastChannelPath = ""; + /** The server icon last reported through {@link Listener#onServerIconChanged}; -1 for none yet. */ + private volatile long serverIconId = -1; + /** The link whose privilege key to use once connected to its server; null for none. */ + private volatile ServerLink tokenLink; + + private record Target(String address, int port, String nickname, String password, String channelPassword) { + } + + private volatile boolean micMuted; + private volatile boolean micLocalMuted; + private volatile boolean deafened; + private volatile boolean away; + /** Away message currently published, empty when away carries no message. */ + private volatile String awayMessage = ""; + private volatile boolean commander; + /** Where the microphone whispers to; null when it talks in our channel. */ + private volatile Whisper whisper; + /** {@link #whisper} as last resolved on the server, to resend only when it changes. */ + private volatile Whisper.Targets whisperTargets; + + public ServerSession(Settings settings, IdentityStore identities, AudioBackend audio, + SoundNotifier sounds, ContactStore contacts, Listener listener) { + this.settings = settings; + this.identities = identities; + this.listener = listener; + this.conn = new TeamspeakConnection(settings, audio, new Events(), sounds, contacts); + } + + public TeamspeakConnection connection() { + return conn; + } + + /** The server's name once known, the address before that. */ + public String title() { + return title; + } + + public String status() { + return status; + } + + public boolean isConnected() { + return conn.isConnected(); + } + + /** Connected or still connecting — i.e. this session is not free for a new server. */ + public boolean isBusy() { + return connecting || conn.isConnected(); + } + + public String address() { + return conn.getServerHost(); + } + + public int port() { + return conn.getServerPort(); + } + + public String identityId() { + return identityId; + } + + /** + * A bookmark leading back here: this server under its name, with the nickname, password and + * identity of the last connect, joining {@code channel}. Null before a first connect. + */ + public Bookmark toBookmark(String channel) { + Target target = lastTarget; + if (target == null) return null; + Bookmark b = new Bookmark(title, target.address(), target.port(), target.nickname(), target.password()); + b.identityId = identityId; + b.channel = channel == null ? "" : channel; + return b; + } + + // ---- connection lifecycle ---- + + /** + * @param nickname this server's own nickname, as a bookmark may name; empty for the + * identity's, else the global one + * @param identityId identity to use, or empty for the default one + * @param channel channel path to join on connect, or empty for the default channel + * @param channelPassword password for that channel, if any + */ + public void connect(String address, int port, String nickname, String password, String identityId, + String channel, String channelPassword) { + synchronized (this) { + if (isBusy()) return; + connecting = true; + } + lastTarget = new Target(address, port, nickname, password, channelPassword); + lastChannelPath = channel == null ? "" : channel; + title = address + ":" + port; + listener.onSystemMessage("Connecting to " + address + ":" + port + + (channel == null || channel.isBlank() ? "" : " (channel \"" + channel + "\")") + " …"); + setStatus("Loading identity…"); + + // Resolving may have to generate a first identity, which takes a while. + new Thread(() -> { + final IdentityEntry entry; + try { + entry = identities.resolve(settings, identityId); + } catch (Exception e) { + connecting = false; + reportError("Could not load identity: " + e.getMessage()); + return; + } + this.identityId = entry.getId(); + listener.onSystemMessage("Using identity \"" + entry.getName() + "\"."); + conn.connect(address, port, nicknameFor(nickname, entry), entry.getPhoneticNickname(), password, + entry.getIdentity(), channel, channelPassword); + }, "identity-resolve").start(); + } + + /** Whether we are on the server a {@code ts3server://} link leads to. */ + public boolean isOn(ServerLink link) { + return conn.isConnected() && link.pointsAt(address(), port()); + } + + /** Does what a link to the server we are on asks: goes to its channel, uses its privilege key. */ + public void follow(ServerLink link) { + if (!isOn(link)) return; + ChannelNode target = link.channel.isEmpty() ? null : conn.getModel().findChannelByPath(link.channel); + ChannelNode current = currentChannel(); + if (target != null && (current == null || target.id != current.id)) { + conn.joinChannel(target.id, link.channelPassword.isEmpty() ? null : link.channelPassword); + } + tokenLink = link.token.isEmpty() ? null : link; + useConnectToken(); + } + + /** Connects where a {@code ts3server://} link leads, using its privilege key once on. */ + public void open(ServerLink link, String identityId) { + tokenLink = link.token.isEmpty() ? null : link; + switchTo(link.address, link.port, link.nickname, link.password, identityId, link.channel, link.channelPassword); + } + + private String nicknameFor(String serverNickname, IdentityEntry identity) { + if (serverNickname != null && !serverNickname.isBlank()) return serverNickname.trim(); + if (!identity.getNickname().isBlank()) return identity.getNickname(); + return settings.nickname; + } + + /** + * Replaces this session's connection: leaves the server it is on, then connects to the + * new one in its place — what left-clicking a bookmark does. + */ + public void switchTo(String address, int port, String nickname, String password, String identityId, + String channel, String channelPassword) { + if (!isBusy()) { + connect(address, port, nickname, password, identityId, channel, channelPassword); + return; + } + new Thread(() -> { + // Reports the disconnect before returning, which clears the connecting flag. + conn.disconnectBlocking("Switching servers"); + connect(address, port, nickname, password, identityId, channel, channelPassword); + }, "ts3j-switch-server").start(); + } + + /** + * Connects again to the server of the last connect, with the same identity, returning to + * the channel we were in — for a connection that dropped, or a network that changed. + * Leaves the server first if still on it. Does nothing before a first connect. + */ + public void reconnect() { + Target target = lastTarget; + if (target == null) return; + String channel = conn.isConnected() ? currentChannelPath() : lastChannelPath; + switchTo(target.address(), target.port(), target.nickname(), target.password(), identityId, + channel, target.channelPassword()); + } + + /** Leaves the server, or gives up a connect that is still under way. */ + public void disconnect() { + if (isBusy()) conn.disconnect(); + } + + /** Synchronous teardown for shutdown paths, so the server sees us leave and recordings are written. */ + public void shutdown() { + CompletableFuture> recording = conn.stopRecording(false); + if (isBusy()) conn.disconnectBlocking("Leaving"); + if (recording != null) { + try { + recording.join(); + } catch (RuntimeException ignored) { + // Already reported. + } + } + } + + /** + * {@link #shutdown()}s every session at once, so leaving takes as long as the slowest + * server rather than all of them together: a frontend may have little time left. + */ + public static void shutdownAll(List sessions) { + List leaving = new ArrayList<>(); + for (ServerSession s : sessions) { + Thread t = new Thread(s::shutdown, "ts3-leave"); + t.start(); + leaving.add(t); + } + for (Thread t : leaving) { + try { + t.join(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + } + } + + /** Releases the background resources of a session that is being thrown away. */ + public void dispose() { + conn.getIcons().shutdown(); + } + + // ---- self state ---- + + public boolean isMicMuted() { + return micMuted; + } + + public boolean isMicLocalMuted() { + return micLocalMuted; + } + + public boolean isDeafened() { + return deafened; + } + + public boolean isAway() { + return away; + } + + public String awayMessage() { + return awayMessage; + } + + public boolean isCommander() { + return commander; + } + + public void setMicMuted(boolean muted) { + micMuted = muted; + conn.setMicMuted(muted); + listener.onSessionChanged(); + } + + /** TS3's "Local Mic Mute": silences capture without publishing a status change. */ + public void setMicLocalMuted(boolean muted) { + micLocalMuted = muted; + conn.setMicLocalMuted(muted); + listener.onSessionChanged(); + } + + public void setDeafened(boolean deaf) { + deafened = deaf; + conn.setDeafened(deaf); + listener.onSessionChanged(); + } + + /** + * @param message the away message, or null to keep the one already set — the + * message outlives coming back, so toggling away again restores it + */ + public void setAway(boolean away, String message) { + this.away = away; + if (message != null) this.awayMessage = message; + conn.setAway(away, awayMessage); + listener.onSessionChanged(); + } + + public void setCommander(boolean commander) { + this.commander = commander; + conn.setChannelCommander(commander); + listener.onSessionChanged(); + } + + /** Hands the capture device to (or takes it from) this connection. */ + public void setMicrophoneActive(boolean active) { + conn.setMicrophoneActive(active); + } + + public void setNickname(String nickname) { + if (conn.isConnected()) conn.setNickname(nickname); + } + + public boolean isTalkRequested() { + ClientEntry self = self(); + return conn.isConnected() && self != null && self.talkRequest; + } + + /** @param message the reason shown to moderators, may be empty */ + public void requestTalkPower(String message) { + if (conn.isConnected()) conn.setTalkRequest(true, message); + } + + public void cancelTalkRequest() { + if (conn.isConnected()) conn.setTalkRequest(false, ""); + } + + public String phoneticNickname() { + ClientEntry self = self(); + return self == null ? "" : self.phoneticNickname; + } + + /** Applies to this server only; the identity keeps its own phonetic nickname for new connections. */ + public void setPhoneticNickname(String phoneticNickname) { + if (conn.isConnected()) conn.setPhoneticNickname(phoneticNickname); + } + + // ---- whisper ---- + + public Whisper whisper() { + return whisper; + } + + /** Whispers to {@code whisper} from now on, or talks in our channel again with null. */ + public void setWhisper(Whisper whisper) { + this.whisper = whisper; + whisperTargets = null; + if (whisper == null) conn.setWhisperTargets(null); + else updateWhisperTargets(); + listener.onSessionChanged(); + } + + /** Whether whispering finds nobody there now, so nobody hears it. */ + public boolean isWhisperingToNobody() { + Whisper.Targets targets = whisperTargets; + return whisper != null && targets != null && targets.isEmpty(); + } + + /** The client who whispered to us last, to whisper back to; null when none is on. */ + public ClientEntry lastWhisperer() { + return conn.isConnected() ? conn.lastWhisperer() : null; + } + + /** Follows the whisper's channels and clients around the server. */ + private void updateWhisperTargets() { + Whisper w = whisper; + if (w == null || !conn.isConnected()) return; + Whisper.Targets targets = w.resolve(conn.getModel()); + if (targets.equals(whisperTargets)) return; + boolean wasEmpty = isWhisperingToNobody(); + whisperTargets = targets; + conn.setWhisperTargets(targets); + if (targets.isEmpty() != wasEmpty) listener.onSessionChanged(); + } + + /** What the local client looks like on this server. */ + public SelfState selfState() { + if (!conn.isConnected()) return SelfState.DISCONNECTED; + if (deafened) return SelfState.DEAFENED; + if (micMuted) return SelfState.MIC_MUTED; + if (micLocalMuted) return SelfState.MIC_LOCAL_MUTED; + if (away) return SelfState.AWAY; + ClientEntry self = self(); + boolean talking = self != null && self.talking; + if (commander) return talking ? SelfState.COMMANDER_TALKING : SelfState.COMMANDER; + return talking ? SelfState.TALKING : SelfState.IDLE; + } + + /** Clears all flags on a fresh connection; the server starts us out clean, so nothing to publish. */ + private void resetSelfState() { + micMuted = false; + micLocalMuted = false; + deafened = false; + away = false; + awayMessage = ""; + commander = false; + } + + private ClientEntry self() { + return conn.getModel().getClient(conn.getSelfClientId()); + } + + // ---- recording ---- + + public boolean isRecording() { + return conn.getRecorder() != null; + } + + /** The recording in progress, or null. */ + public VoiceRecorder.Mode recordingMode() { + VoiceRecorder rec = conn.getRecorder(); + return rec == null ? null : rec.mode(); + } + + /** A file name for a recording started now, unique within {@code dir}. */ + public Path recordingFile(Path dir) { + String server = title.replaceAll("[\\\\/:*?\"<>|\\p{Cntrl}]", "_").strip(); + String name = (server.isEmpty() ? "recording" : server) + " " + + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss")); + Path file = dir.resolve(name + ".ogg"); + for (int n = 2; Files.exists(file); n++) file = dir.resolve(name + " (" + n + ").ogg"); + return file; + } + + public void startRecording(VoiceRecorder.Mode mode, Path file) { + if (!conn.isConnected() || isRecording()) return; + VoiceRecorder rec; + try { + Path dir = file.toAbsolutePath().getParent(); + if (dir != null) Files.createDirectories(dir); + rec = conn.startRecording(mode, file); + } catch (IOException | RuntimeException e) { + listener.onSystemMessage("Failed to start recording: " + e.getMessage()); + return; + } + boolean multitrack = mode == VoiceRecorder.Mode.MULTITRACK; + listener.onSystemMessage((multitrack ? "Started multitrack recording: " : "Started recording: ") + file); + rec.whenDone().whenComplete((files, error) -> { + if (error != null) { + Throwable cause = error.getCause() != null ? error.getCause() : error; + listener.onSystemMessage("Recording failed: " + cause.getMessage()); + } else { + listener.onSystemMessage((multitrack ? "Stopped multitrack recording: " : "Stopped recording: ") + + files.stream().map(Path::toString).collect(Collectors.joining(", "))); + } + listener.onSessionChanged(); + }); + listener.onSessionChanged(); + } + + /** Stops the recording; its files are finished in the background, then reported. */ + public void stopRecording() { + if (conn.stopRecording() != null) listener.onSessionChanged(); + } + + // ---- chat ---- + + /** + * Sends a chat message and reports it back through {@link Listener#onOwnChat}. + * + * @param clientId the recipient of a private message; ignored otherwise + */ + public void sendChat(ConnectionListener.ChatScope scope, int clientId, String text) { + if (!conn.isConnected()) { + listener.onSystemMessage("Not connected."); + return; + } + switch (scope) { + case SERVER -> { + conn.sendServerMessage(text); + listener.onOwnChat(scope, 0, "", text); + } + case PRIVATE -> { + conn.sendPrivateMessage(clientId, text); + listener.onOwnChat(scope, clientId, peerName(clientId), text); + } + default -> { + conn.sendChannelMessage(text); + listener.onOwnChat(scope, 0, "", text); + } + } + } + + /** + * Shares a file in a chat as TeamSpeak 6 does: stores it in this user's myTeamSpeak + * cloud storage, then sends the message pointing to it. Runs in the background; a failure + * is reported through {@link Listener#onSystemMessage}. + * + * @param data read and closed in the background + */ + public void sendAttachment(ConnectionListener.ChatScope scope, int clientId, ChatAttachments attachments, + InputStream data, long size, String fileName) { + String room = conn.serverUniqueId(); + if (!conn.isConnected() || room == null) { + closeQuietly(data); + listener.onSystemMessage("Not connected."); + return; + } + Thread t = new Thread(() -> { + try (InputStream in = data) { + ChatAttachment attachment = attachments.upload(in, size, fileName, room); + sendChat(scope, clientId, attachment.toMessage()); + } catch (IOException | MyTsException e) { + listener.onSystemMessage("Could not share " + fileName + ": " + e.getMessage()); + } + }, "ts3-attachment-upload"); + t.setDaemon(true); + t.start(); + } + + private static void closeQuietly(InputStream in) { + try { + in.close(); + } catch (IOException ignored) { + } + } + + private String peerName(int clientId) { + ClientEntry c = conn.getModel().getClient(clientId); + return c != null ? conn.displayName(c) : "Client " + clientId; + } + + // ---- channels ---- + + /** The channel we are in, or null when not connected. */ + public ChannelNode currentChannel() { + if (!conn.isConnected()) return null; + ClientEntry self = self(); + return self == null ? null : conn.getModel().getChannel(self.channelId); + } + + /** Path of the channel we are in, or empty when not connected. */ + public String currentChannelPath() { + if (!conn.isConnected()) return ""; + ClientEntry self = self(); + return self == null ? "" : conn.getModel().channelPath(self.channelId); + } + + /** Joins the channel at a "/"-separated path, as the hotkey action names it. */ + public void joinChannelPath(String path) { + if (!conn.isConnected() || path == null || path.isBlank()) return; + ChannelNode target = conn.getModel().findChannelByPath(path); + if (target != null) conn.joinChannel(target.id, null); + } + + /** Every channel of this server as a "/"-separated path, in the tree's own order. */ + public List channelPaths() { + List out = new ArrayList<>(); + if (!conn.isConnected()) return out; + for (ChannelNode root : conn.getModel().buildTree()) collectPaths(root, out); + return out; + } + + private void collectPaths(ChannelNode channel, List out) { + out.add(conn.getModel().channelPath(channel.id)); + for (ChannelNode child : channel.children) collectPaths(child, out); + } + + // ---- permissions ---- + + /** Whether the server grants us {@code b_client_ban_list}; offered while unknown. */ + public boolean canViewBanList() { + return permits("b_client_ban_list"); + } + + /** Whether the server grants us {@code b_client_complain_list}; offered while unknown. */ + public boolean canViewComplaints() { + return permits("b_client_complain_list"); + } + + /** Whether the server grants us {@code b_virtualserver_log_view}; offered while unknown. */ + public boolean canViewServerLog() { + return permits("b_virtualserver_log_view"); + } + + /** Whether the server grants us {@code b_virtualserver_token_list}; offered while unknown. */ + public boolean canListPrivilegeKeys() { + return permits("b_virtualserver_token_list"); + } + + /** Whether the server lets us upload an avatar ({@code i_client_max_avatar_filesize}); offered while unknown. */ + public boolean canSetAvatar() { + return permits("i_client_max_avatar_filesize"); + } + + /** Whether the server lets us delete other clients' avatars; offered while unknown. */ + public boolean canDeleteOtherAvatars() { + return permits("b_client_avatar_delete_other"); + } + + private boolean permits(String permission) { + return conn.isConnected() && conn.getModel().permits(permission); + } + + /** Whether we publish an avatar on this server. */ + public boolean hasAvatar() { + if (!conn.isConnected()) return false; + ClientEntry self = conn.getModel().getClient(conn.getSelfClientId()); + return self != null && !self.avatarFlag.isEmpty(); + } + + public boolean canMoveClients() { + return hasPower("i_client_move_power"); + } + + public boolean canKickFromChannel() { + return hasPower("i_client_kick_from_channel_power"); + } + + public boolean canKickFromServer() { + return hasPower("i_client_kick_from_server_power"); + } + + public boolean canBanClients() { + return hasPower("i_client_ban_power"); + } + + public boolean canCreateChannels() { + return permitsAny("b_channel_create_temporary", "b_channel_create_semi_permanent", + "b_channel_create_permanent"); + } + + public boolean canEditChannels() { + return permitsAny("b_channel_modify_name", "b_channel_modify_topic", "b_channel_modify_description", + "b_channel_modify_password", "b_channel_modify_codec", "b_channel_modify_maxclients"); + } + + public boolean canDeleteChannels() { + return permitsAny("b_channel_delete_temporary", "b_channel_delete_semi_permanent", + "b_channel_delete_permanent"); + } + + private boolean permitsAny(String... permissions) { + if (!conn.isConnected()) return false; + for (String p : permissions) { + if (conn.getModel().permits(p)) return true; + } + return false; + } + + /** + * Whether we have any of a power; whether it beats the client's needed power only the + * server knows, so it is left to refuse. + */ + private boolean hasPower(String power) { + return conn.isConnected() && conn.getModel().selfPower(power) != 0; + } + + // ---- connection events ---- + + private void setStatus(String text) { + status = text; + listener.onStatus(text); + listener.onSessionChanged(); + } + + private void reportError(String message) { + listener.onSystemMessage("Error: " + message); + listener.onError(message); + setStatus(message); + } + + private void useConnectToken() { + ServerLink link = tokenLink; + tokenLink = null; + Target target = lastTarget; + if (link == null || target == null || !link.pointsAt(target.address(), target.port())) return; + conn.usePrivilegeKey(link.token, error -> listener.onSystemMessage(error == null + ? "Privilege key used." : "Could not use the privilege key: " + error)); + } + + private void checkServerIcon() { + if (!conn.isConnected()) return; + long id = conn.getModel().serverIconId(); + if (id == serverIconId) return; + serverIconId = id; + conn.getIcons().get(id); + listener.onServerIconChanged(id); + } + + /** Applies what a connection event means for the session, then passes it on. */ + private final class Events implements ConnectionListener { + + @Override + public void onStatus(String text) { + setStatus(text); + } + + @Override + public void onConnected() { + connecting = false; + resetSelfState(); + listener.onConnected(); + listener.onSystemMessage("Connected."); + listener.onSessionChanged(); + checkServerIcon(); + useConnectToken(); + } + + @Override + public void onDisconnected(String reason) { + connecting = false; + // Channels and clients are this server's; another one has its own. + whisper = null; + whisperTargets = null; + serverIconId = -1; + conn.getModel().clear(); + listener.onDisconnected(reason); + listener.onSystemMessage("Disconnected" + (reason == null || reason.isEmpty() ? "." : ": " + reason)); + listener.onSessionChanged(); + } + + @Override + public void onModelChanged() { + // By the time a connection is reported gone, it no longer knows where we were. + String channel = currentChannelPath(); + if (!channel.isEmpty()) lastChannelPath = channel; + String name = conn.getModel().getServerName(); + if (conn.isConnected() && name != null && !name.isBlank() && !name.equals(title)) { + title = name; + listener.onSessionChanged(); + } + checkServerIcon(); + updateWhisperTargets(); + listener.onModelChanged(); + } + + @Override + public void onInfoUpdated() { + listener.onInfoUpdated(); + } + + @Override + public void onIconsUpdated() { + listener.onIconsUpdated(); + } + + /** Passes the sender on under their contact display name. */ + @Override + public void onChat(ChatScope scope, int fromClientId, String fromUniqueId, String fromName, String message) { + String name = conn.getContacts().displayName(fromUniqueId, fromName); + listener.onChat(scope, fromClientId, fromUniqueId, name, message); + } + + @Override + public void onChatHistory(ChatScope scope, List htmlEntries) { + listener.onChatHistory(scope, htmlEntries); + } + + @Override + public void onPrivateChatHistory(int clientId, String nickname, List htmlEntries) { + listener.onPrivateChatHistory(clientId, nickname, htmlEntries); + } + + @Override + public void onTalkStateChanged(int clientId, boolean talking) { + listener.onTalkStateChanged(clientId, talking); + } + + @Override + public void onError(String message) { + reportError(message); + } + + @Override + public void onPoke(String fromName, String message) { + listener.onSystemMessage("You were poked by " + fromName + ": " + message); + listener.onPoke(fromName, message); + } + + @Override + public void onServerLog(String message) { + listener.onServerLog(message); + } + + @Override + public void onServerLogHtml(String html) { + listener.onServerLogHtml(html); + } + + @Override + public void onUnreadMessagesChanged(int unread) { + listener.onUnreadMessagesChanged(unread); + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/Sessions.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/Sessions.java new file mode 100644 index 0000000..5bb63c0 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/Sessions.java @@ -0,0 +1,165 @@ +package eu.lixko.ts3j.client.session; + +import eu.lixko.ts3j.client.audio.VoiceInput; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * Every server the client is on, and what they share. Only one of them can capture with the + * microphone at a time, so it is handed from one to another here; the away state and the + * nickname are the user's own, so they can be set on every server at once. + * + *

    Driven from one thread, the frontend's. + */ +public final class Sessions { + + private final List sessions = new ArrayList<>(); + private final Runnable onMicrophoneMoved; + private ServerSession microphoneOwner; + /** + * Opens and closes capture lines, which can block briefly, off the frontend's thread. One + * thread, so quick successive hand-overs stop and start in the order they were made. + */ + private final ExecutorService handover = Executors.newSingleThreadExecutor(r -> { + Thread t = new Thread(r, "mic-handover"); + t.setDaemon(true); + return t; + }); + + /** @param onMicrophoneMoved told whenever the microphone changes hands */ + public Sessions(Runnable onMicrophoneMoved) { + this.onMicrophoneMoved = onMicrophoneMoved; + } + + public void add(ServerSession session) { + sessions.add(session); + } + + /** Forgets a session that is being closed; the microphone moves on if it had it. */ + public void remove(ServerSession session) { + sessions.remove(session); + if (microphoneOwner == session) microphoneOwner = null; + assignMicrophoneIfFree(); + } + + public boolean anyConnected() { + for (ServerSession s : sessions) { + if (s.isConnected()) return true; + } + return false; + } + + // ---- the microphone ---- + + /** The session capturing with the microphone, or null when none is. */ + public ServerSession microphoneOwner() { + return microphoneOwner; + } + + /** Moves the microphone to {@code session}, taking it from whoever held it. */ + public void giveMicrophoneTo(ServerSession session) { + if (microphoneOwner == session) return; + ServerSession previous = microphoneOwner; + microphoneOwner = session; + handover.execute(() -> { + if (previous != null) previous.setMicrophoneActive(false); + if (session != null) session.setMicrophoneActive(true); + }); + onMicrophoneMoved.run(); + } + + /** Gives the microphone to some connected session when nobody who could use it holds it. */ + public void assignMicrophoneIfFree() { + if (microphoneOwner != null && sessions.contains(microphoneOwner) && microphoneOwner.isConnected()) return; + ServerSession previous = microphoneOwner; + microphoneOwner = null; + for (ServerSession s : sessions) { + if (s.isConnected()) { + giveMicrophoneTo(s); + return; + } + } + if (previous != null) onMicrophoneMoved.run(); + } + + public void connected(ServerSession session) { + assignMicrophoneIfFree(); + } + + /** + * A disconnected session cannot capture; the microphone moves on if it had it. The session + * lets go of it too, or a reconnect would capture alongside whoever holds it by then. + */ + public void disconnected(ServerSession session) { + if (microphoneOwner == session) { + microphoneOwner = null; + handover.execute(() -> session.setMicrophoneActive(false)); + } + assignMicrophoneIfFree(); + } + + /** Opens the microphone while push-to-talk is held. */ + public void setPushToTalk(boolean talking) { + VoiceInput mic = microphoneOf(microphoneOwner); + if (mic != null) mic.setPushToTalk(talking); + } + + /** Transmits on the server holding the microphone while held, in any input mode. */ + public void setForceTransmit(boolean talking) { + VoiceInput mic = microphoneOf(microphoneOwner); + if (mic != null) mic.setForceTransmit(talking); + } + + /** Tells every connected microphone about a key press, as TS3 tells all its connections. */ + public void keyPressed() { + for (ServerSession s : sessions) { + VoiceInput mic = microphoneOf(s); + if (mic != null) mic.keyPressed(); + } + } + + private static VoiceInput microphoneOf(ServerSession session) { + return session == null || !session.isConnected() ? null : session.connection().getMicrophone(); + } + + // ---- the user's own state ---- + + public void setAwayEverywhere(boolean away, String message) { + for (ServerSession s : sessions) { + if (s.isConnected()) s.setAway(away, message); + } + } + + /** @return true when every connected server has us away, and there is one */ + public boolean isAwayEverywhere() { + boolean any = false; + for (ServerSession s : sessions) { + if (!s.isConnected()) continue; + any = true; + if (!s.isAway()) return false; + } + return any; + } + + /** The away message to suggest: {@code preferred}'s, else any server's that has one. */ + public String awayMessage(ServerSession preferred) { + if (preferred != null && !preferred.awayMessage().isEmpty()) return preferred.awayMessage(); + for (ServerSession s : sessions) { + if (s.isConnected() && !s.awayMessage().isEmpty()) return s.awayMessage(); + } + return ""; + } + + public void setNickname(String nickname) { + for (ServerSession s : sessions) s.setNickname(nickname); + } + + /** Leaves every server, waiting until each has been told. */ + public void shutdown() { + ServerSession.shutdownAll(new ArrayList<>(sessions)); + handover.shutdown(); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/NotificationSettings.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/NotificationSettings.java new file mode 100644 index 0000000..ce1bb72 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/NotificationSettings.java @@ -0,0 +1,91 @@ +package eu.lixko.ts3j.client.sound; + +import java.util.EnumSet; +import java.util.Properties; +import java.util.Set; + +/** + * Per-action notification configuration: whether an action makes a sound at all, + * and whether it is important — important actions are the only ones still + * heard while the speakers are muted. + * + *

    Only deviations from the defaults are persisted, so a pack gaining new events + * (or a default changing) does not need a migration. + */ +public final class NotificationSettings { + + private static final String PREFIX = "sound.event."; + private static final String ENABLED = ".enabled"; + private static final String IMPORTANT = ".important"; + + private final Set disabled = EnumSet.noneOf(SoundEvent.class); + private final Set important = EnumSet.noneOf(SoundEvent.class); + + public NotificationSettings() { + resetToDefaults(); + } + + public boolean isEnabled(SoundEvent event) { + return !disabled.contains(event); + } + + public void setEnabled(SoundEvent event, boolean enabled) { + if (enabled) disabled.remove(event); + else disabled.add(event); + } + + public boolean isImportant(SoundEvent event) { + return important.contains(event); + } + + public void setImportant(SoundEvent event, boolean value) { + if (value) important.add(event); + else important.remove(event); + } + + public void resetToDefaults() { + disabled.clear(); + important.clear(); + for (SoundEvent e : SoundEvent.values()) { + if (e.importantByDefault()) important.add(e); + if (!e.enabledByDefault()) disabled.add(e); + } + } + + public NotificationSettings copy() { + NotificationSettings copy = new NotificationSettings(); + copy.copyFrom(this); + return copy; + } + + public void copyFrom(NotificationSettings other) { + disabled.clear(); + disabled.addAll(other.disabled); + important.clear(); + important.addAll(other.important); + } + + public void load(Properties props) { + resetToDefaults(); + for (SoundEvent e : SoundEvent.values()) { + String enabled = props.getProperty(PREFIX + e.id() + ENABLED); + if (enabled != null) setEnabled(e, Boolean.parseBoolean(enabled)); + String flag = props.getProperty(PREFIX + e.id() + IMPORTANT); + if (flag != null) setImportant(e, Boolean.parseBoolean(flag)); + } + } + + public void store(Properties props) { + for (SoundEvent e : SoundEvent.values()) { + put(props, PREFIX + e.id() + ENABLED, isEnabled(e) != e.enabledByDefault(), + Boolean.toString(isEnabled(e))); + put(props, PREFIX + e.id() + IMPORTANT, isImportant(e) != e.importantByDefault(), + Boolean.toString(isImportant(e))); + } + } + + private static void put(Properties props, String key, boolean deviates, String value) { + if (deviates) props.setProperty(key, value); + else props.remove(key); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/OggOpusFile.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/OggOpusFile.java new file mode 100644 index 0000000..96efd43 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/OggOpusFile.java @@ -0,0 +1,148 @@ +package eu.lixko.ts3j.client.sound; + +import eu.lixko.ts3j.client.audio.VoiceFormat; +import eu.lixko.ts3j.client.audio.ogg.OggPageWriter; +import eu.lixko.ts3j.client.audio.ogg.OpusHeaders; +import eu.lixko.ts3j.client.audio.opus.OpusCodec; +import eu.lixko.ts3j.client.audio.opus.OpusDecoder; +import eu.lixko.ts3j.client.audio.opus.OpusEncoder; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Ogg Opus files (RFC 7845), the compact form of a sound pack's sounds: decoded to mono + * 48 kHz for playback, and written from it by {@link SoundPackConverter}. + */ +public final class OggOpusFile { + + public static final String EXTENSION = ".opus"; + + /** Opus always decodes at 48 kHz; 120 ms is the longest packet. */ + private static final int MAX_PACKET_SAMPLES = 5760; + private static final int FRAME_SAMPLES = VoiceFormat.FRAME_SIZE; + private static final int PRE_SKIP = OpusHeaders.LIBOPUS_PRE_SKIP; + + private OggOpusFile() { + } + + /** Decodes a file to mono samples in [-1, 1] at 48 kHz. */ + static float[] readMono(File file, OpusCodec opus) throws IOException { + List pages = pages(Files.readAllBytes(file.toPath())); + List packets = packets(pages); + if (packets.size() < 2) throw new IOException("no Opus stream"); + ByteBuffer head = ByteBuffer.wrap(packets.get(0)).order(ByteOrder.LITTLE_ENDIAN); + if (head.remaining() < 19 || !new String(packets.get(0), 0, 8, StandardCharsets.US_ASCII).equals("OpusHead")) { + throw new IOException("not an Opus stream"); + } + int channels = head.get(9) & 0xff; + int preSkip = head.getShort(10) & 0xffff; + if (channels < 1 || channels > 2) throw new IOException("unsupported channel count " + channels); + + float[] mono = new float[0]; + int length = 0; + float[] frame = new float[MAX_PACKET_SAMPLES * channels]; + try (OpusDecoder decoder = opus.createDecoder(VoiceFormat.SAMPLE_RATE, MAX_PACKET_SAMPLES, channels)) { + for (byte[] packet : packets.subList(2, packets.size())) { + int n = decoder.decode(packet, frame); + if (length + n > mono.length) mono = Arrays.copyOf(mono, Math.max(mono.length * 2, length + n)); + for (int i = 0; i < n; i++) { + float sum = 0; + for (int c = 0; c < channels; c++) sum += frame[i * channels + c]; + mono[length + i] = sum / channels; + } + length += n; + } + } + // The last page's granule position marks where the sound ends, past the padding. + long end = pages.get(pages.size() - 1).granule; + int stop = (int) Math.min(length, end >= preSkip ? end : length); + return stop <= preSkip ? new float[0] : Arrays.copyOfRange(mono, preSkip, stop); + } + + /** + * Encodes mono 48 kHz samples into a file. + * + * @param inputRate the rate the sound was recorded at, kept in the header for reference + */ + static void write(File file, float[] mono, int inputRate, OpusEncoder encoder) throws IOException { + List audio = new ArrayList<>(); + float[] frame = new float[FRAME_SAMPLES]; + // Encoded past the end by the encoder's delay, so the tail comes out whole. + int total = PRE_SKIP + mono.length; + for (int start = 0; start < total; start += FRAME_SAMPLES) { + Arrays.fill(frame, 0f); + if (start < mono.length) System.arraycopy(mono, start, frame, 0, Math.min(FRAME_SAMPLES, mono.length - start)); + audio.add(encoder.encode(frame)); + } + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + OggPageWriter ogg = new OggPageWriter(out, file.getName().hashCode()); + ogg.write(OpusHeaders.mono(PRE_SKIP, inputRate), 0); + ogg.flush(); + ogg.write(OpusHeaders.tags("ts3j", List.of()), 0); + ogg.flush(); + for (int i = 0; i < audio.size(); i++) { + // The last packet's position marks where the sound ends, short of the padding. + boolean end = i == audio.size() - 1; + ogg.write(audio.get(i), end ? total : (long) (i + 1) * FRAME_SAMPLES); + } + ogg.finish(); + Files.write(file.toPath(), out.toByteArray()); + } + + // ---- Ogg framing ---- + + private record Page(long granule, byte[] segments, byte[] data) { + } + + private static List pages(byte[] file) throws IOException { + List pages = new ArrayList<>(); + ByteBuffer in = ByteBuffer.wrap(file).order(ByteOrder.LITTLE_ENDIAN); + while (in.remaining() >= 27) { + int start = in.position(); + if (in.getInt() != 0x5367674f) throw new IOException("lost Ogg page sync"); // "OggS" + in.position(start + 6); + long granule = in.getLong(); + in.position(start + 26); + int count = in.get() & 0xff; + byte[] segments = new byte[count]; + in.get(segments); + int size = 0; + for (byte s : segments) size += s & 0xff; + if (size > in.remaining()) throw new IOException("truncated Ogg page"); + byte[] data = new byte[size]; + in.get(data); + pages.add(new Page(granule, segments, data)); + } + if (pages.isEmpty()) throw new IOException("not an Ogg file"); + return pages; + } + + /** Joins the pages' segments into packets; a packet may run on into the next page. */ + private static List packets(List pages) { + List packets = new ArrayList<>(); + ByteArrayOutputStream packet = new ByteArrayOutputStream(); + for (Page page : pages) { + int offset = 0; + for (byte segment : page.segments) { + int size = segment & 0xff; + packet.write(page.data, offset, size); + offset += size; + if (size < 255) { + packets.add(packet.toByteArray()); + packet.reset(); + } + } + } + return packets; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/PackSoundPlayer.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/PackSoundPlayer.java new file mode 100644 index 0000000..a33586f --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/PackSoundPlayer.java @@ -0,0 +1,229 @@ +package eu.lixko.ts3j.client.sound; + +import eu.lixko.ts3j.client.audio.AudioIo; +import eu.lixko.ts3j.client.audio.AudioPlayback; +import eu.lixko.ts3j.client.audio.VoiceFormat; +import eu.lixko.ts3j.client.audio.opus.OpusCodec; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +/** + * Plays sound-pack files (wave or Ogg Opus) on the configured playback device. + * + *

    All notification sounds share one playback line and are mixed together, so + * two events firing at once never fight over the device, and the line is dropped + * again after a long enough quiet spell. Files are decoded once, resampled to the + * device's 48 kHz and cached, so repeat events cost nothing but the mix. + */ +public final class PackSoundPlayer implements SoundPlayer { + + /** + * How long the playback line is held after the last sound. Opening it costs a + * device round-trip, which is audible as a lag before a sound the user just + * triggered, so it is kept around for a spell of quiet rather than per sound. + */ + private static final long IDLE_KEEP_OPEN_NANOS = 30_000_000_000L; + private static final long FRAME_NANOS = VoiceFormat.FRAME_SIZE * 1_000_000_000L / VoiceFormat.SAMPLE_RATE; + /** + * How far ahead of real time the mixer renders. The line would happily take a + * few hundred milliseconds at once, but anything written is fixed: a sound that + * fires while another plays can only join the mix past what is already queued, + * so the lead is kept to a couple of frames, enough to ride out scheduling jitter. + */ + private static final long LEAD_NANOS = 3 * FRAME_NANOS; + /** Sound files are small; this caps the decoded cache anyway. */ + private static final int MAX_CACHED_FILES = 64; + + /** A decoded, 48 kHz mono sound being rendered. */ + private static final class Voice { + final float[] pcm; + final double volume; + int position; + + Voice(float[] pcm, double volume) { + this.pcm = pcm; + this.volume = volume; + } + } + + private final Map cache = new LinkedHashMap<>(16, 0.75f, true) { + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > MAX_CACHED_FILES; + } + }; + + private final List voices = new ArrayList<>(); + private final Object lock = new Object(); + + private final AudioIo io; + private final OpusCodec opus; + private volatile String outputDevice; + private volatile boolean running = true; + private Thread mixer; + + public PackSoundPlayer(AudioIo io, OpusCodec opus, String outputDevice) { + this.io = io; + this.opus = opus; + this.outputDevice = outputDevice; + } + + @Override + public void setOutputDevice(String device) { + this.outputDevice = device == null ? "" : device; + } + + @Override + public void play(File file, double volume) { + if (file == null || !file.isFile() || volume <= 0) return; + float[] pcm; + try { + pcm = decode(file); + } catch (Exception e) { + return; // unplayable file: stay silent rather than break the action + } + if (pcm.length == 0) return; + + synchronized (lock) { + if (!running) return; + voices.add(new Voice(pcm, Math.min(1.0, volume))); + if (mixer == null) { + mixer = new Thread(this::mixLoop, "ts3j-sounds"); + mixer.setDaemon(true); + mixer.start(); + } + lock.notifyAll(); + } + } + + @Override + public void shutdown() { + synchronized (lock) { + running = false; + voices.clear(); + lock.notifyAll(); + } + } + + // ---- mixing ---- + + /** + * Renders the active sounds onto one line, idling (rather than writing silence) + * between them and giving the device back after {@link #IDLE_KEEP_OPEN_NANOS}. + * + *

    Latency matters here because a sound is heard against the click that caused + * it: the loop idles rather than writing silence, and while rendering it paces + * itself against the clock instead of filling the line, so at any moment no more + * than {@link #LEAD_NANOS} of audio is committed and a newly fired sound starts + * right behind it. + */ + private void mixLoop() { + AudioPlayback line = null; + try { + float[] mix = new float[VoiceFormat.FRAME_SIZE]; + long due = 0; // when the next frame is due to leave the speaker + while (awaitVoices()) { + if (line == null) { + line = io.openPlayback(outputDevice, VoiceFormat.MAX_CHANNELS); + line.start(); + } + long now = System.nanoTime(); + if (due < now) { + due = now; // fresh start or fell behind: resync + } else if (due - now > LEAD_NANOS) { + Thread.sleep((due - now - LEAD_NANOS) / 1_000_000L); + } + due += FRAME_NANOS; + renderFrame(mix); + line.write(toBytes(mix, line.channels()), 0, mix.length * 2 * line.channels()); + } + } catch (Exception e) { + synchronized (lock) { + voices.clear(); + mixer = null; + } + } finally { + if (line != null) line.close(); + } + } + + /** + * Blocks until there is something to render. + * + * @return false when the idle timeout expired or the player was shut down, in + * which case this thread is done and {@link #play} will start a fresh one + */ + private boolean awaitVoices() throws InterruptedException { + synchronized (lock) { + long deadline = System.nanoTime() + IDLE_KEEP_OPEN_NANOS; + while (running && voices.isEmpty()) { + long remaining = deadline - System.nanoTime(); + if (remaining <= 0) break; + lock.wait(Math.max(1, remaining / 1_000_000L)); + } + if (running && !voices.isEmpty()) return true; + mixer = null; + return false; + } + } + + /** Sums the active sounds into {@code mix}, dropping the ones that ran out. */ + private void renderFrame(float[] mix) { + Arrays.fill(mix, 0f); + synchronized (lock) { + for (Iterator it = voices.iterator(); it.hasNext(); ) { + Voice v = it.next(); + int n = Math.min(mix.length, v.pcm.length - v.position); + for (int i = 0; i < n; i++) { + mix[i] += v.pcm[v.position + i] * v.volume; + } + v.position += n; + if (v.position >= v.pcm.length) it.remove(); + } + } + } + + /** Interleaves the mono mix across the line's channels as signed 16-bit LE. */ + private static byte[] toBytes(float[] mix, int channels) { + byte[] out = new byte[mix.length * 2 * channels]; + for (int i = 0, k = 0; i < mix.length; i++) { + float v = Math.max(-1f, Math.min(1f, mix[i])); + short s = (short) Math.round(v * 32767.0); + for (int c = 0; c < channels; c++, k += 2) { + out[k] = (byte) (s & 0xFF); + out[k + 1] = (byte) ((s >> 8) & 0xFF); + } + } + return out; + } + + // ---- decoding ---- + + private float[] decode(File file) throws Exception { + String key = file.getAbsolutePath() + '@' + file.lastModified(); + synchronized (cache) { + float[] cached = cache.get(key); + if (cached != null) return cached; + } + float[] pcm = readMono48k(file); + synchronized (cache) { + cache.put(key, pcm); + } + return pcm; + } + + /** Decodes a sound file to mono 48 kHz float samples. */ + private float[] readMono48k(File file) throws Exception { + if (file.getName().toLowerCase(Locale.ROOT).endsWith(OggOpusFile.EXTENSION)) { + return OggOpusFile.readMono(file, opus); + } + return WaveFile.readMono(file).at48k(); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundEvent.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundEvent.java new file mode 100644 index 0000000..e38d9a1 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundEvent.java @@ -0,0 +1,220 @@ +package eu.lixko.ts3j.client.sound; + +/** + * The catalogue of actions a sound pack can react to, using TeamSpeak's own event + * ids so the packs shipped with the official client (and third-party ones) load + * unchanged — see {@link SoundPack}. + * + *

    Events are grouped for display and each carries a default "important" flag: + * important sounds are the only ones still played while the speakers are muted + * (see {@link SoundNotifier}). The user can change both the flag and whether an + * event makes a sound at all; that lives in {@link NotificationSettings}. + */ +public enum SoundEvent { + + // ---- connection ---- + CONNECTION_CONNECTED(Category.CONNECTION, "Connection established"), + CONNECTION_DISCONNECTED(Category.CONNECTION, "Disconnected"), + CONNECTION_LOST_CONNECTION(Category.CONNECTION, "Connection lost", true), + + // ---- notifications aimed at us ---- + OTHER_RECEIVED_POKE(Category.OTHER, "You were poked", true), + OTHER_SENT_POKE(Category.OTHER, "You poked someone"), + OTHER_FILETRANSFER_COMPLETE(Category.OTHER, "File transfer complete"), + OTHER_FILETRANSFER_FAILED(Category.OTHER, "File transfer failed", true), + OTHER_WHISPERLIST_EMPTY(Category.OTHER, "Whisper list is empty"), + OTHER_WHISPERTARGET_NOT_FOUND(Category.OTHER, "Whisper target not found"), + OTHER_WHISPERTARGET_TOO_MANY(Category.OTHER, "Too many whisper targets"), + SPECIAL_WHISPER_NOTIFY(Category.OTHER, "Whisper received", true), + + // ---- microphone / test sounds ---- + SPECIAL_MIC_CLICK_SELF_ON(Category.SPECIAL, "Mic clicks self on", false, false), + SPECIAL_MIC_CLICK_SELF_OFF(Category.SPECIAL, "Mic clicks self off", false, false), + SPECIAL_MIC_CLICK_OTHER_ON(Category.SPECIAL, "Mic clicks other on", false, false), + SPECIAL_MIC_CLICK_OTHER_OFF(Category.SPECIAL, "Mic clicks other off", false, false), + SPECIAL_TALKING_WHILE_MUTED(Category.SPECIAL, "Talking while muted", true), + SPECIAL_SOUND_TEST(Category.SPECIAL, "Playback test sound"), + SPECIAL_3D_TEST(Category.SPECIAL, "3D sound test"), + + // ---- channels ---- + CHANNEL_CREATED_BY_YOU(Category.CHANNEL, "Created by you"), + CHANNEL_CREATED_BY_OTHER(Category.CHANNEL, "Created by other"), + CHANNEL_DELETED_BY_YOU(Category.CHANNEL, "Deleted by you"), + CHANNEL_DELETED_BY_OTHER(Category.CHANNEL, "Deleted by other"), + CHANNEL_DELETED_BY_SERVER(Category.CHANNEL, "Deleted by the server"), + CHANNEL_EDITED_CURRENT_BY_YOU(Category.CHANNEL, "Your channel edited by you"), + CHANNEL_EDITED_CURRENT_BY_OTHER(Category.CHANNEL, "Your channel edited by other"), + CHANNEL_EDITED_OTHER_BY_YOU(Category.CHANNEL, "Other channel edited by you"), + CHANNEL_EDITED_OTHER_BY_OTHER(Category.CHANNEL, "Other channel edited by other"), + CHANNEL_EDITED_OTHER_BY_SERVER(Category.CHANNEL, "Other channel edited by the server"), + CHANNEL_MOVED_BY_YOU(Category.CHANNEL, "Moved by you"), + CHANNEL_MOVED_BY_OTHER(Category.CHANNEL, "Moved by other"), + + // ---- server ---- + SERVER_EDITED_BY_YOU(Category.SERVER, "Edited by you"), + SERVER_EDITED_BY_OTHER(Category.SERVER, "Edited by other"), + SERVER_INSUFFICIENT_PERMISSIONS(Category.SERVER, "Insufficient permissions", true), + SERVER_ERROR(Category.SERVER, "Server error", true), + + // ---- other clients ---- + CLIENT_CONNECTION_CONNECTED_SERVER(Category.CLIENT, "Connected to server"), + CLIENT_CONNECTION_CONNECTED_CURRENT_CHANNEL(Category.CLIENT, "Connected to current channel"), + CLIENT_CONNECTION_DISCONNECTED_SERVER(Category.CLIENT, "Disconnected from server"), + CLIENT_CONNECTION_DISCONNECTED_CURRENT_CHANNEL(Category.CLIENT, "Disconnected from current channel"), + CLIENT_CONNECTION_LOST_CONNECTION_SERVER(Category.CLIENT, "Lost connection to server"), + CLIENT_CONNECTION_LOST_CONNECTION_CURRENT_CHANNEL(Category.CLIENT, "Lost connection in current channel"), + CLIENT_SWITCHED_TO_CURRENT_CHANNEL_APPEARS(Category.CLIENT, "Switched to current channel, appears"), + CLIENT_SWITCHED_TO_CURRENT_CHANNEL_STAYS(Category.CLIENT, "Switched to current channel, stays"), + CLIENT_SWITCHED_FROM_CURRENT_CHANNEL_DISAPPEARS(Category.CLIENT, "Switched away from current channel, disappears"), + CLIENT_SWITCHED_FROM_CURRENT_CHANNEL_STAYS(Category.CLIENT, "Switched away from current channel, stays"), + CLIENT_SWITCHED_TO_OTHER_CHANNEL_APPEARS(Category.CLIENT, "Switched to different channel, appears"), + CLIENT_SWITCHED_TO_OTHER_CHANNEL_DISAPPEARS(Category.CLIENT, "Switched to different channel, disappears"), + CLIENT_SWITCHED_TO_OTHER_CHANNEL_STAYS(Category.CLIENT, "Switched to different channel, stays"), + CLIENT_MOVED_TO_CURRENT_CHANNEL_APPEARS(Category.CLIENT, "Moved to current channel, appears"), + CLIENT_MOVED_TO_CURRENT_CHANNEL_STAYS(Category.CLIENT, "Moved to current channel, stays"), + CLIENT_MOVED_FROM_CURRENT_CHANNEL_DISAPPEARS(Category.CLIENT, "Moved away from current channel, disappears"), + CLIENT_MOVED_FROM_CURRENT_CHANNEL_STAYS(Category.CLIENT, "Moved away from current channel, stays"), + CLIENT_MOVED_TO_OTHER_CHANNEL_APPEARS(Category.CLIENT, "Moved to different channel, appears"), + CLIENT_MOVED_TO_OTHER_CHANNEL_DISAPPEARS(Category.CLIENT, "Moved to different channel, disappears"), + CLIENT_MOVED_TO_OTHER_CHANNEL_STAYS(Category.CLIENT, "Moved to different channel, stays"), + CLIENT_RENAMED_BY_YOU(Category.CLIENT, "Renamed by you"), + CLIENT_RENAMED_BY_OTHER(Category.CLIENT, "Renamed by other"), + CLIENT_WAS_KICKED_FROM_CHANNEL_TO_CURRENT_CHANNEL_APPEARS(Category.CLIENT, + "Kicked from channel to current channel, appears"), + CLIENT_WAS_KICKED_FROM_CHANNEL_TO_CURRENT_CHANNEL_STAYS(Category.CLIENT, + "Kicked from channel to current channel, stays"), + CLIENT_WAS_KICKED_FROM_CHANNEL_FROM_CURRENT_CHANNEL_DISAPPEARS(Category.CLIENT, + "Kicked away from current channel, disappears"), + CLIENT_WAS_KICKED_FROM_CHANNEL_FROM_CURRENT_CHANNEL_STAYS(Category.CLIENT, + "Kicked away from current channel, stays"), + CLIENT_WAS_KICKED_FROM_CHANNEL_TO_OTHER_CHANNEL_APPEARS(Category.CLIENT, + "Kicked from channel to different channel, appears"), + CLIENT_WAS_KICKED_FROM_CHANNEL_TO_OTHER_CHANNEL_DISAPPEARS(Category.CLIENT, + "Kicked from channel to different channel, disappears"), + CLIENT_WAS_KICKED_FROM_CHANNEL_TO_OTHER_CHANNEL_STAYS(Category.CLIENT, + "Kicked from channel to different channel, stays"), + CLIENT_WAS_KICKED_FROM_SERVER_SERVER(Category.CLIENT, "Kicked from server"), + CLIENT_WAS_KICKED_FROM_SERVER_CURRENT_CHANNEL(Category.CLIENT, "Kicked from server, from current channel"), + CLIENT_WAS_BANNED_SERVER(Category.CLIENT, "Banned from server"), + CLIENT_WAS_BANNED_CURRENT_CHANNEL(Category.CLIENT, "Banned from server, from current channel"), + CLIENT_SERVERGROUP_ADDED_BY_SERVER(Category.CLIENT, "Server group assigned by the server"), + CLIENT_SERVERGROUP_ADDED_BY_USER(Category.CLIENT, "Server group assigned by other"), + CLIENT_SERVERGROUP_REMOVED_BY_SERVER(Category.CLIENT, "Server group revoked by the server"), + CLIENT_SERVERGROUP_REMOVED_BY_USER(Category.CLIENT, "Server group revoked by other"), + CLIENT_CHANNELGROUP_CHANGED_BY_SERVER(Category.CLIENT, "Channel group changed by the server"), + CLIENT_CHANNELGROUP_CHANGED_BY_USER(Category.CLIENT, "Channel group changed by other"), + CLIENT_RECORDING_START(Category.CLIENT, "Starts recording"), + CLIENT_RECORDING_STOP(Category.CLIENT, "Stops recording"), + CLIENT_RECORDING_IN_CHANNEL(Category.CLIENT, "Is recording in current channel"), + CLIENT_REQUESTED_TALK_POWER(Category.CLIENT, "Talk power requested"), + + // ---- ourselves ---- + YOU_SWITCHED_CHANNEL(Category.SELF, "You switched channel"), + YOU_WERE_MOVED_TO_DIFFERENT_CHANNEL(Category.SELF, "You were moved", true), + YOU_WERE_KICKED_FROM_CHANNEL(Category.SELF, "You were kicked from channel", true), + YOU_WERE_KICKED_FROM_SERVER(Category.SELF, "You were kicked from server", true), + YOU_WERE_BANNED(Category.SELF, "You were banned", true), + YOU_WERE_GRANTED_TALK_POWER(Category.SELF, "Talk power granted", true), + YOU_WERE_REVOKED_TALK_POWER(Category.SELF, "Talk power revoked", true), + YOU_SERVERGROUP_ADDED_BY_SERVER(Category.SELF, "Server group assigned by the server"), + YOU_SERVERGROUP_ADDED_BY_USER(Category.SELF, "Server group assigned by other"), + YOU_SERVERGROUP_REMOVED_BY_SERVER(Category.SELF, "Server group revoked by the server"), + YOU_SERVERGROUP_REMOVED_BY_USER(Category.SELF, "Server group revoked by other"), + YOU_CHANNELGROUP_CHANGED_BY_SERVER(Category.SELF, "Channel group changed by the server"), + YOU_CHANNELGROUP_CHANGED_BY_USER(Category.SELF, "Channel group changed by other"), + + // ---- chat ---- + CHAT_SENT_MESSAGE_CLIENT(Category.CHAT, "You sent a client message"), + CHAT_SENT_MESSAGE_CHANNEL(Category.CHAT, "You sent a channel message"), + CHAT_SENT_MESSAGE_SERVER(Category.CHAT, "You sent a server message"), + CHAT_RECEIVED_MESSAGE_CLIENT(Category.CHAT, "You received a client message", true), + CHAT_RECEIVED_MESSAGE_CHANNEL(Category.CHAT, "You received a channel message"), + CHAT_RECEIVED_MESSAGE_SERVER(Category.CHAT, "You received a server message"), + + // ---- status ---- + SOUND_CAPTURE_MUTED(Category.STATUS, "Microphone muted", true), + SOUND_CAPTURE_UNMUTED(Category.STATUS, "Microphone activated", true), + SOUND_PLAYBACK_MUTED(Category.STATUS, "Sound muted", true), + SOUND_PLAYBACK_UNMUTED(Category.STATUS, "Sound resumed", true), + STATUS_SET_AWAY(Category.STATUS, "Set to away"), + STATUS_SET_PRESENT(Category.STATUS, "Set to present"); + + /** Display grouping, mirroring the sections of TeamSpeak's notification list. */ + public enum Category { + CONNECTION("Connection"), + OTHER("Notifications"), + SPECIAL("Microphone & tests"), + CHANNEL("Channel"), + SERVER("Server"), + CLIENT("Clients"), + SELF("Yourself"), + CHAT("Chat"), + STATUS("Status"); + + private final String label; + + Category(String label) { + this.label = label; + } + + public String label() { + return label; + } + } + + private final Category category; + private final String label; + private final boolean importantByDefault; + private final boolean enabledByDefault; + + SoundEvent(Category category, String label) { + this(category, label, false, true); + } + + SoundEvent(Category category, String label, boolean importantByDefault) { + this(category, label, importantByDefault, true); + } + + SoundEvent(Category category, String label, boolean importantByDefault, boolean enabledByDefault) { + this.category = category; + this.label = label; + this.importantByDefault = importantByDefault; + this.enabledByDefault = enabledByDefault; + } + + /** The key used in a sound pack's {@code settings.ini}; identical to {@link #name()}. */ + public String id() { + return name(); + } + + public Category category() { + return category; + } + + public String label() { + return label; + } + + /** Whether this action counts as important until the user says otherwise. */ + public boolean importantByDefault() { + return importantByDefault; + } + + /** + * Whether the action makes a sound out of the box. The mic clicks are mapped by + * most packs but off by default, as they are in the official client. + */ + public boolean enabledByDefault() { + return enabledByDefault; + } + + /** @return the event with this pack key, or {@code null} for an unknown one */ + public static SoundEvent byId(String id) { + if (id == null) return null; + try { + return valueOf(id.trim().toUpperCase(java.util.Locale.ROOT)); + } catch (IllegalArgumentException e) { + return null; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundNotifier.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundNotifier.java new file mode 100644 index 0000000..70a077a --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundNotifier.java @@ -0,0 +1,165 @@ +package eu.lixko.ts3j.client.sound; + +import eu.lixko.ts3j.client.config.AppDirs; +import eu.lixko.ts3j.client.config.Settings; + +import java.io.File; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Plays the sound a {@link SoundPack} assigns to an action, honouring the user's + * per-action configuration. + * + *

    An action is heard when the pack maps it, the user left it enabled and either + * the speakers are on or the action is marked important — the muted case + * is what the important flag exists for. + * + *

    A sound that is already starting is not started again: one server action often + * arrives as a burst of events (a channel deleted with its subchannels, every tab on + * the same server hearing the same move), and stacking identical copies of a sound + * only makes it louder and garbled. + */ +public final class SoundNotifier { + + /** Contact class in a pack's {@code ${clientType}} placeholder: friend, neutral or blocked. */ + private static final String DEFAULT_CLIENT_TYPE = "neutral"; + + /** How close together two plays of the same sound count as one. */ + private static final long COALESCE_NANOS = 250_000_000L; + + private final Settings settings; + private volatile SoundPlayer player; + private volatile SoundPack pack; + private volatile List available = List.of(); + private volatile boolean soundsMuted; + /** When each resolved sound last started, for {@link #COALESCE_NANOS}. */ + private final Map lastStarted = new HashMap<>(); + + public SoundNotifier(Settings settings) { + this.settings = settings; + reload(); + } + + /** Attaches the platform's player; without one the notifier stays silent. */ + public void setPlayer(SoundPlayer player) { + this.player = player; + } + + /** Re-scans the installed packs and selects the configured one. */ + public void reload() { + available = SoundPacks.findAll(new File(AppDirs.profile(), "sound"), settings.soundPackDir); + pack = SoundPacks.select(available, settings.soundPack); + } + + public List availablePacks() { + return available; + } + + public SoundPack pack() { + return pack; + } + + /** Switches packs and remembers the choice in the settings. */ + public void setPack(SoundPack pack) { + this.pack = pack; + settings.soundPack = pack == null ? "" : pack.id(); + } + + /** + * Silences every notification sound until turned back on — TS3's "Mute Sounds" + * hotkey action. Unlike deafening, this is not tied to a server and even important + * actions stay quiet. + */ + public void setMuted(boolean muted) { + this.soundsMuted = muted; + } + + public boolean isMuted() { + return soundsMuted; + } + + /** + * Plays the sound for an action. + * + * @param muted whether playback is currently muted, in which case only actions + * marked important are heard + */ + public void fire(SoundEvent event, boolean muted) { + fire(event, muted, null); + } + + /** + * @param variables values for the pack's {@code ${...}} placeholders, e.g. + * {@code clientname} or {@code channelname} + */ + public void fire(SoundEvent event, boolean muted, Map variables) { + if (soundsMuted) return; + NotificationSettings notifications = settings.notifications; + if (!notifications.isEnabled(event)) return; + if (muted && !notifications.isImportant(event)) return; + render(event, variables); + } + + /** Plays an action's sound regardless of its configuration, for the options dialog. */ + public void preview(SoundEvent event) { + render(event, null); + } + + /** Whether the current pack would make any sound for this action. */ + public boolean hasSound(SoundEvent event) { + SoundPack p = pack; + if (p == null) return false; + SoundScript script = p.script(event); + if (script == null) return false; + return script.kind() != SoundScript.Kind.SAY || (player != null && player.canSpeak()); + } + + private void render(SoundEvent event, Map variables) { + SoundPack p = pack; + SoundPlayer out = player; + if (p == null || out == null) return; + SoundScript script = p.script(event); + if (script == null) return; + + String resolved = script.resolve(withDefaults(variables)); + double volume = Math.max(0, Math.min(1.0, settings.effectiveSoundVolume())); + if (volume <= 0) return; + if (!claimStart(script.kind() + ":" + resolved)) return; + + if (script.kind() == SoundScript.Kind.SAY) { + out.say(resolved, volume); + return; + } + File file = p.file(resolved); + if (file != null) out.play(file, volume); + } + + /** @return false when the same sound already started within {@link #COALESCE_NANOS} */ + private boolean claimStart(String sound) { + long now = System.nanoTime(); + synchronized (lastStarted) { + Long last = lastStarted.get(sound); + if (last != null && now - last < COALESCE_NANOS) return false; + lastStarted.put(sound, now); + if (lastStarted.size() > 64) lastStarted.values().removeIf(t -> now - t >= COALESCE_NANOS); + } + return true; + } + + private static Map withDefaults(Map variables) { + Map vars = variables == null ? new HashMap<>() : new HashMap<>(variables); + vars.putIfAbsent("clientType", DEFAULT_CLIENT_TYPE); + return vars; + } + + /** Builds a variable map from alternating name/value pairs. */ + public static Map vars(String... nameValuePairs) { + Map vars = new HashMap<>(); + for (int i = 0; i + 1 < nameValuePairs.length; i += 2) { + vars.put(nameValuePairs[i], nameValuePairs[i + 1] == null ? "" : nameValuePairs[i + 1]); + } + return vars; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundPack.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundPack.java new file mode 100644 index 0000000..9c61bdb --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundPack.java @@ -0,0 +1,167 @@ +package eu.lixko.ts3j.client.sound; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.EnumMap; +import java.util.Locale; +import java.util.Map; + +/** + * A TeamSpeak sound pack: a directory of wave files plus a {@code settings.ini} + * mapping {@link SoundEvent}s to {@link SoundScript}s. + * + *

    The format is TeamSpeak's, so the packs shipped with the official client + * (and the ones on its add-on site) can be used as they are: + * + *

    + * [info]
    + * name    = Default Sound Pack (Female)
    + * version = 1.0
    + * author  = TeamSpeak Systems GmbH
    + *
    + * [soundfiles]
    + * CONNECTION_CONNECTED = play("connected.wav")
    + * CLIENT_MOVED_TO_CURRENT_CHANNEL_STAYS = play("${clientType}_moved_tocurrentchannel.wav")
    + * CHANNEL_CREATED_BY_OTHER =
    + * 
    + */ +public final class SoundPack { + + private static final String INI = "settings.ini"; + + private final String id; + private final File directory; + private final String name; + private final String version; + private final String author; + private final Map scripts; + + private SoundPack(String id, File directory, String name, String version, String author, + Map scripts) { + this.id = id; + this.directory = directory; + this.name = name; + this.version = version; + this.author = author; + this.scripts = scripts; + } + + /** Stable identifier used in the settings: the pack's directory name. */ + public String id() { + return id; + } + + public File directory() { + return directory; + } + + public String name() { + return name; + } + + public String version() { + return version; + } + + public String author() { + return author; + } + + /** @return what this pack does for the event, or {@code null} when it stays silent */ + public SoundScript script(SoundEvent event) { + return scripts.get(event); + } + + /** + * Resolves the wave file for a {@code play(...)} script. Pack authors write the + * names as they appear on their (often case-insensitive) file system, so a + * mismatched case is retried against the directory listing. A pack whose sounds + * were converted to Opus keeps its scripts: {@code x.wav} is found as {@code x.opus}. + * + * @return the file, or {@code null} if the pack does not contain it + */ + public File file(String fileName) { + if (fileName == null || fileName.isEmpty()) return null; + File found = find(fileName); + if (found == null && fileName.regionMatches(true, fileName.length() - 4, ".wav", 0, 4)) { + found = find(fileName.substring(0, fileName.length() - 4) + OggOpusFile.EXTENSION); + } + return found; + } + + private File find(String fileName) { + File direct = new File(directory, fileName); + if (direct.isFile()) return direct; + + File[] entries = directory.listFiles(); + if (entries != null) { + for (File f : entries) { + if (f.isFile() && f.getName().equalsIgnoreCase(fileName)) return f; + } + } + return null; + } + + @Override + public String toString() { + return name; + } + + /** + * Reads a pack from a directory holding a {@code settings.ini}. + * + * @return the pack, or {@code null} when the directory is not one + */ + public static SoundPack load(File directory) { + if (directory == null || !directory.isDirectory()) return null; + File ini = new File(directory, INI); + if (!ini.isFile()) { + File[] entries = directory.listFiles(); + if (entries != null) { + for (File f : entries) { + if (f.isFile() && f.getName().equalsIgnoreCase(INI)) ini = f; + } + } + if (!ini.isFile()) return null; + } + + Map scripts = new EnumMap<>(SoundEvent.class); + Map info = new java.util.HashMap<>(); + try (BufferedReader in = new BufferedReader( + new InputStreamReader(Files.newInputStream(ini.toPath()), StandardCharsets.UTF_8))) { + String section = ""; + String line; + while ((line = in.readLine()) != null) { + String trimmed = line.trim(); + if (trimmed.isEmpty() || trimmed.startsWith("#") || trimmed.startsWith(";")) continue; + if (trimmed.startsWith("[") && trimmed.endsWith("]")) { + section = trimmed.substring(1, trimmed.length() - 1).trim().toLowerCase(Locale.ROOT); + continue; + } + int eq = trimmed.indexOf('='); + if (eq < 0) continue; + String key = trimmed.substring(0, eq).trim(); + String value = trimmed.substring(eq + 1).trim(); + + if ("info".equals(section)) { + info.put(key.toLowerCase(Locale.ROOT), value); + continue; + } + SoundEvent event = SoundEvent.byId(key); + SoundScript script = SoundScript.parse(value); + if (event != null && script != null) scripts.put(event, script); + } + } catch (IOException e) { + return null; + } + + String id = directory.getName(); + String name = info.getOrDefault("name", id); + return new SoundPack(id, directory, name, + info.getOrDefault("version", ""), info.getOrDefault("author", ""), scripts); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundPackConverter.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundPackConverter.java new file mode 100644 index 0000000..12e085b --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundPackConverter.java @@ -0,0 +1,54 @@ +package eu.lixko.ts3j.client.sound; + +import eu.lixko.ts3j.client.audio.VoiceFormat; +import eu.lixko.ts3j.client.audio.opus.OpusCodec; +import eu.lixko.ts3j.client.audio.opus.OpusEncoder; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.util.Locale; + +/** + * Copies sound packs with their wave files encoded as Ogg Opus, about a fifteenth of + * the size. The scripts are left as they are: {@link SoundPack#file} finds a pack's + * {@code x.wav} as {@code x.opus}. + */ +public final class SoundPackConverter { + + /** Clear of any audible difference for notification sounds, at a fifteenth of the WAVs' size. */ + public static final int BITRATE = 64_000; + + private SoundPackConverter() { + } + + /** Converts every file under {@code source} into the same place under {@code target}. */ + public static void convert(File source, File target, OpusCodec opus) throws IOException { + File[] entries = source.listFiles(); + if (entries == null) throw new IOException("Cannot list " + source); + Files.createDirectories(target.toPath()); + for (File entry : entries) { + String name = entry.getName(); + if (entry.isDirectory()) { + convert(entry, new File(target, name), opus); + } else if (name.toLowerCase(Locale.ROOT).endsWith(".wav")) { + File out = new File(target, name.substring(0, name.length() - 4) + OggOpusFile.EXTENSION); + encode(entry, out, opus); + } else { + Files.copy(entry.toPath(), new File(target, name).toPath(), StandardCopyOption.REPLACE_EXISTING); + } + } + } + + private static void encode(File wave, File out, OpusCodec opus) throws IOException { + WaveFile.Audio audio = WaveFile.readMono(wave); + try (OpusEncoder encoder = opus.createEncoder(VoiceFormat.SAMPLE_RATE, VoiceFormat.FRAME_SIZE, 1, + OpusCodec.Application.AUDIO)) { + encoder.setBitrate(BITRATE); + encoder.setVbr(true); + encoder.setComplexity(10); + OggOpusFile.write(out, audio.at48k(), audio.sampleRate(), encoder); + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundPacks.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundPacks.java new file mode 100644 index 0000000..c4ff11a --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundPacks.java @@ -0,0 +1,53 @@ +package eu.lixko.ts3j.client.sound; + +import eu.lixko.ts3j.client.config.InstallDirs; + +import java.io.File; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Finds the sound packs installed on this machine: the client's own + * {@code sound/} folder, an extra folder the user configured, and the + * {@code sound/} folder of an installed TeamSpeak 3 client (whose packs are + * usable as they are, see {@link SoundPack}). + */ +public final class SoundPacks { + + private SoundPacks() { + } + + /** + * Loads every pack found under {@code extraDirectory} and the well-known + * locations, newest search root winning on a name clash. + * + * @param userDirectory the client's own pack folder (may not exist yet) + * @param extraDirectory an additional folder chosen by the user, or {@code null} + * @return the packs, ordered by display name + */ + public static List findAll(File userDirectory, String extraDirectory) { + Map byId = new LinkedHashMap<>(); + for (File root : InstallDirs.searchRoots("sound", userDirectory, extraDirectory)) { + File[] entries = root.listFiles(File::isDirectory); + if (entries == null) continue; + for (File dir : entries) { + SoundPack pack = SoundPack.load(dir); + if (pack != null) byId.putIfAbsent(pack.id(), pack); + } + } + List packs = new ArrayList<>(byId.values()); + packs.sort(Comparator.comparing(p -> p.name().toLowerCase(java.util.Locale.ROOT))); + return packs; + } + + /** @return the pack with this id, or the first one available, or {@code null} */ + public static SoundPack select(List packs, String id) { + for (SoundPack p : packs) { + if (p.id().equals(id)) return p; + } + return packs.isEmpty() ? null : packs.get(0); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundPlayer.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundPlayer.java new file mode 100644 index 0000000..5adc793 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundPlayer.java @@ -0,0 +1,33 @@ +package eu.lixko.ts3j.client.sound; + +import java.io.File; + +/** + * Renders notification sounds. Kept separate from the voice pipeline so the core + * stays free of any concrete audio stack; the desktop frontend supplies an + * implementation that mixes onto the configured playback device. + */ +public interface SoundPlayer { + + /** + * Plays a wave file, mixing it with anything already playing. + * + * @param volume linear gain, 0..1 + */ + void play(File file, double volume); + + /** Speaks a sentence from a text-to-speech pack; a no-op where TTS is unavailable. */ + default void say(String text, double volume) { + } + + /** Whether {@link #say} actually produces sound on this platform. */ + default boolean canSpeak() { + return false; + } + + /** Follows the playback device selected in the options. */ + default void setOutputDevice(String device) { + } + + void shutdown(); +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundScript.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundScript.java new file mode 100644 index 0000000..5250428 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundScript.java @@ -0,0 +1,60 @@ +package eu.lixko.ts3j.client.sound; + +import java.util.Map; + +/** + * One action from a sound pack: either {@code play("file.wav")} or + * {@code say("some text")}, with TeamSpeak's {@code ${variable}} placeholders + * still in place until {@link #resolve(Map)} fills them in. + */ +public record SoundScript(Kind kind, String argument) { + + public enum Kind { + /** Play a wave file from the pack's directory. */ + PLAY, + /** Speak a sentence (text-to-speech packs). */ + SAY + } + + /** + * Parses the right-hand side of a {@code settings.ini} entry. + * + * @return the script, or {@code null} for an empty value (the pack stays silent + * for that event) or one whose function we don't know + */ + public static SoundScript parse(String value) { + if (value == null) return null; + String v = value.trim(); + if (v.isEmpty()) return null; + + Kind kind = v.startsWith("play(") ? Kind.PLAY : v.startsWith("say(") ? Kind.SAY : null; + if (kind == null) return null; + + int open = v.indexOf('('); + int close = v.lastIndexOf(')'); + if (close <= open) return null; + String arg = v.substring(open + 1, close).trim(); + if (arg.length() >= 2 && arg.startsWith("\"") && arg.endsWith("\"")) { + arg = arg.substring(1, arg.length() - 1); + } + return arg.isEmpty() ? null : new SoundScript(kind, arg); + } + + /** Substitutes {@code ${name}} placeholders; unknown ones resolve to an empty string. */ + public String resolve(Map variables) { + String text = argument; + int from = 0; + StringBuilder out = new StringBuilder(); + while (true) { + int start = text.indexOf("${", from); + if (start < 0) break; + int end = text.indexOf('}', start); + if (end < 0) break; + String name = text.substring(start + 2, end); + String value = variables == null ? null : variables.get(name); + out.append(text, from, start).append(value == null ? "" : value); + from = end + 1; + } + return out.append(text.substring(from)).toString(); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/WaveFile.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/WaveFile.java new file mode 100644 index 0000000..8b53c0e --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/WaveFile.java @@ -0,0 +1,112 @@ +package eu.lixko.ts3j.client.sound; + +import eu.lixko.ts3j.client.audio.VoiceFormat; + +import java.io.File; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.file.Files; + +/** + * Reads RIFF wave files into mono float samples. Sound packs ship 16-bit PCM, but any + * integer depth up to 32 bits and 32-bit float are accepted too, in plain or + * {@code WAVE_FORMAT_EXTENSIBLE} headers. + */ +final class WaveFile { + + private static final int FORMAT_PCM = 1; + private static final int FORMAT_FLOAT = 3; + private static final int FORMAT_EXTENSIBLE = 0xFFFE; + + /** Decoded audio: mono samples in [-1, 1] at {@code sampleRate}. */ + record Audio(float[] samples, int sampleRate) { + + /** The samples at the 48 kHz everything plays at, linearly interpolated. */ + float[] at48k() { + int toRate = VoiceFormat.SAMPLE_RATE; + if (sampleRate <= 0 || sampleRate == toRate || samples.length == 0) return samples; + double ratio = toRate / (double) sampleRate; + float[] out = new float[(int) (samples.length * ratio)]; + for (int i = 0; i < out.length; i++) { + double position = i / ratio; + int index = (int) position; + double fraction = position - index; + float a = samples[Math.min(index, samples.length - 1)]; + float b = samples[Math.min(index + 1, samples.length - 1)]; + out[i] = (float) (a + (b - a) * fraction); + } + return out; + } + } + + private WaveFile() { + } + + static Audio readMono(File file) throws IOException { + ByteBuffer in = ByteBuffer.wrap(Files.readAllBytes(file.toPath())).order(ByteOrder.LITTLE_ENDIAN); + if (in.remaining() < 12 || in.getInt() != fourCc("RIFF")) throw new IOException("not a RIFF file"); + in.getInt(); // RIFF size + if (in.getInt() != fourCc("WAVE")) throw new IOException("not a wave file"); + + int format = -1, channels = 0, sampleRate = 0, bits = 0; + while (in.remaining() >= 8) { + int id = in.getInt(); + int size = in.getInt(); + if (size < 0 || size > in.remaining()) size = in.remaining(); // truncated files still play + // Android < API 34 lacks ByteBuffer.slice(int, int); original: + // ByteBuffer chunk = in.slice(in.position(), size).order(ByteOrder.LITTLE_ENDIAN); + ByteBuffer chunk = in.duplicate(); + chunk.limit(chunk.position() + size); + chunk = chunk.slice().order(ByteOrder.LITTLE_ENDIAN); + if (id == fourCc("fmt ") && size >= 16) { + format = chunk.getShort() & 0xFFFF; + channels = chunk.getShort() & 0xFFFF; + sampleRate = chunk.getInt(); + chunk.getInt(); // byte rate + chunk.getShort(); // block align + bits = chunk.getShort() & 0xFFFF; + if (format == FORMAT_EXTENSIBLE && size >= 26) { + format = chunk.getShort(24) & 0xFFFF; // the sub-format GUID starts with the tag + } + } else if (id == fourCc("data")) { + if (format < 0) throw new IOException("data before fmt chunk"); + return new Audio(decode(chunk, format, channels, bits), sampleRate); + } + in.position(in.position() + size + (size & 1)); // chunks are word-aligned + } + throw new IOException("no audio data"); + } + + private static float[] decode(ByteBuffer data, int format, int channels, int bits) throws IOException { + int bytes = bits / 8; + boolean supported = (format == FORMAT_PCM && bits % 8 == 0 && bytes >= 1 && bytes <= 4) + || (format == FORMAT_FLOAT && bits == 32); + if (!supported || channels < 1) { + throw new IOException("unsupported wave encoding " + format + "/" + bits + " bit"); + } + int frames = data.remaining() / (bytes * channels); + float[] mono = new float[frames]; + for (int i = 0; i < frames; i++) { + float sum = 0; + for (int c = 0; c < channels; c++) { + sum += format == FORMAT_FLOAT ? data.getFloat() : readInt(data, bytes); + } + mono[i] = sum / channels; + } + return mono; + } + + /** One integer sample scaled to [-1, 1]; 8-bit wave data is unsigned, wider data signed. */ + private static float readInt(ByteBuffer data, int bytes) { + if (bytes == 1) return ((data.get() & 0xFF) - 128) / 128f; + int value = 0; + for (int b = 0; b < bytes; b++) value |= (data.get() & 0xFF) << (8 * b); + int shift = 32 - 8 * bytes; + return (value << shift) / 2147483648f; // sign-extend via the top bits + } + + private static int fourCc(String id) { + return id.charAt(0) | id.charAt(1) << 8 | id.charAt(2) << 16 | id.charAt(3) << 24; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/SqliteReader.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/SqliteReader.java new file mode 100644 index 0000000..4e975d5 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/SqliteReader.java @@ -0,0 +1,288 @@ +package eu.lixko.ts3j.client.teamspeak; + +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +/** + * A minimal read-only reader for SQLite 3 database files, enough to dump the rows + * of a table: it walks the table's b-tree and decodes each record, overflow pages + * included. It exists so the TeamSpeak client's {@code settings.db} can be read + * without a JDBC driver and its native library. + * + *

    Only the main database file is read. A write-ahead log that has not been + * checkpointed yet is not consulted; TeamSpeak uses a rollback journal, whose + * committed state is in the main file. + */ +final class SqliteReader implements AutoCloseable { + + private static final int HEADER_SIZE = 100; + private static final int INTERIOR_TABLE = 0x05; + private static final int LEAF_TABLE = 0x0d; + + /** A table's column names and rows; values are {@link Long}, {@link Double}, {@link String}, {@code byte[]} or {@code null}. */ + static final class Table { + final List columns; + final List rows; + + Table(List columns, List rows) { + this.columns = columns; + this.rows = rows; + } + + int columnIndex(String name) { + for (int i = 0; i < columns.size(); i++) { + if (columns.get(i).equalsIgnoreCase(name)) return i; + } + return -1; + } + } + + private final RandomAccessFile file; + private final int pageSize; + private final int usableSize; + private final int encoding; + + SqliteReader(java.io.File path) throws IOException { + file = new RandomAccessFile(path, "r"); + byte[] header = new byte[HEADER_SIZE]; + file.readFully(header); + if (!new String(header, 0, 15, StandardCharsets.US_ASCII).equals("SQLite format 3")) { + file.close(); + throw new IOException("Not an SQLite 3 database"); + } + int size = u16(header, 16); + pageSize = size == 1 ? 65536 : size; + usableSize = pageSize - (header[20] & 0xFF); + encoding = (int) u32(header, 56); + } + + @Override + public void close() throws IOException { + file.close(); + } + + /** Reads a whole table, or returns {@code null} when the schema has no such table. */ + Table readTable(String tableName) throws IOException { + Object[] schema = null; + for (Object[] row : rowsOf(1)) { + if (row.length < 5 || !"table".equals(row[0])) continue; + if (String.valueOf(row[1]).equalsIgnoreCase(tableName)) { + schema = row; + break; + } + } + if (schema == null || !(schema[3] instanceof Long)) return null; + List columns = columnNames(String.valueOf(schema[4])); + return new Table(columns, rowsOf(((Long) schema[3]).intValue())); + } + + /** The column names out of a {@code CREATE TABLE} statement, in declaration order. */ + static List columnNames(String sql) { + List names = new ArrayList<>(); + int open = sql.indexOf('('); + int close = sql.lastIndexOf(')'); + if (open < 0 || close <= open) return names; + for (String definition : splitTopLevel(sql.substring(open + 1, close))) { + String[] tokens = definition.trim().split("\\s+"); + if (tokens.length == 0 || tokens[0].isEmpty()) continue; + String first = tokens[0].toUpperCase(Locale.ROOT); + // Table constraints live in the same list as columns. + if (first.equals("PRIMARY") || first.equals("UNIQUE") || first.equals("CHECK") + || first.equals("FOREIGN") || first.equals("CONSTRAINT")) { + continue; + } + names.add(unquote(tokens[0])); + } + return names; + } + + /** Splits on commas outside parentheses, so {@code PRIMARY KEY (a, b)} stays one item. */ + private static List splitTopLevel(String s) { + List parts = new ArrayList<>(); + int depth = 0; + int start = 0; + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c == '(') depth++; + else if (c == ')') depth--; + else if (c == ',' && depth == 0) { + parts.add(s.substring(start, i)); + start = i + 1; + } + } + parts.add(s.substring(start)); + return parts; + } + + private static String unquote(String s) { + if (s.length() >= 2) { + char c = s.charAt(0); + if ((c == '"' || c == '`' || c == '\'' || c == '[') && (s.endsWith(String.valueOf(c)) || c == '[' && s.endsWith("]"))) { + return s.substring(1, s.length() - 1); + } + } + return s; + } + + // ---- b-tree walk ---- + + private List rowsOf(int rootPage) throws IOException { + List rows = new ArrayList<>(); + walk(rootPage, rows, 0); + return rows; + } + + private void walk(int pageNumber, List rows, int depth) throws IOException { + if (depth > 64) throw new IOException("B-tree too deep"); + byte[] page = readPage(pageNumber); + int base = pageNumber == 1 ? HEADER_SIZE : 0; + int type = page[base] & 0xFF; + int cells = u16(page, base + 3); + int headerSize = type == INTERIOR_TABLE ? 12 : 8; + int pointers = base + headerSize; + + if (type == INTERIOR_TABLE) { + for (int i = 0; i < cells; i++) { + int cell = u16(page, pointers + 2 * i); + walk((int) u32(page, cell), rows, depth + 1); + } + walk((int) u32(page, base + 8), rows, depth + 1); + } else if (type == LEAF_TABLE) { + for (int i = 0; i < cells; i++) { + int cell = u16(page, pointers + 2 * i); + rows.add(decodeRecord(leafPayload(page, cell))); + } + } else { + throw new IOException("Unexpected page type " + type); + } + } + + /** The full payload of a table leaf cell, following the overflow chain when it spills. */ + private byte[] leafPayload(byte[] page, int cell) throws IOException { + long[] varint = new long[2]; + int pos = readVarint(page, cell, varint); + int payloadSize = (int) varint[0]; + pos = readVarint(page, pos, varint); // rowid + + int usable = usableSize; + int maxLocal = usable - 35; + int minLocal = (usable - 12) * 32 / 255 - 23; + int local; + if (payloadSize <= maxLocal) { + local = payloadSize; + } else { + int k = minLocal + (payloadSize - minLocal) % (usable - 4); + local = k <= maxLocal ? k : minLocal; + } + + byte[] payload = new byte[payloadSize]; + System.arraycopy(page, pos, payload, 0, local); + int filled = local; + long next = local < payloadSize ? u32(page, pos + local) : 0; + while (filled < payloadSize && next != 0) { + byte[] overflow = readPage((int) next); + int chunk = Math.min(payloadSize - filled, usable - 4); + System.arraycopy(overflow, 4, payload, filled, chunk); + filled += chunk; + next = u32(overflow, 0); + } + if (filled < payloadSize) throw new IOException("Truncated overflow chain"); + return payload; + } + + private Object[] decodeRecord(byte[] payload) throws IOException { + long[] varint = new long[2]; + int pos = readVarint(payload, 0, varint); + int headerEnd = (int) varint[0]; + List types = new ArrayList<>(); + while (pos < headerEnd) { + pos = readVarint(payload, pos, varint); + types.add(varint[0]); + } + Object[] values = new Object[types.size()]; + int data = headerEnd; + for (int i = 0; i < values.length; i++) { + long type = types.get(i); + if (type == 0) { + values[i] = null; + } else if (type >= 1 && type <= 6) { + int width = type == 5 ? 6 : type == 6 ? 8 : (int) type; + values[i] = readInt(payload, data, width); + data += width; + } else if (type == 7) { + values[i] = Double.longBitsToDouble(readInt(payload, data, 8)); + data += 8; + } else if (type == 8 || type == 9) { + values[i] = type - 8; + } else if (type >= 12) { + int length = (int) ((type - (type % 2 == 0 ? 12 : 13)) / 2); + if (type % 2 == 0) { + byte[] blob = new byte[length]; + System.arraycopy(payload, data, blob, 0, length); + values[i] = blob; + } else { + values[i] = decodeText(payload, data, length); + } + data += length; + } else { + throw new IOException("Reserved serial type " + type); + } + } + return values; + } + + private String decodeText(byte[] b, int off, int len) { + switch (encoding) { + case 2: + return new String(b, off, len, StandardCharsets.UTF_16LE); + case 3: + return new String(b, off, len, StandardCharsets.UTF_16BE); + default: + return new String(b, off, len, StandardCharsets.UTF_8); + } + } + + private byte[] readPage(int number) throws IOException { + if (number < 1) throw new IOException("Bad page number " + number); + byte[] page = new byte[pageSize]; + file.seek((long) (number - 1) * pageSize); + file.readFully(page); + return page; + } + + // ---- encoding primitives ---- + + private static int u16(byte[] b, int off) { + return (b[off] & 0xFF) << 8 | (b[off + 1] & 0xFF); + } + + private static long u32(byte[] b, int off) { + return (long) (b[off] & 0xFF) << 24 | (b[off + 1] & 0xFF) << 16 | (b[off + 2] & 0xFF) << 8 | (b[off + 3] & 0xFF); + } + + private static long readInt(byte[] b, int off, int width) { + long v = b[off] & 0xFF; + if ((v & 0x80) != 0) v |= -256L; // sign-extend + for (int i = 1; i < width; i++) v = v << 8 | (b[off + i] & 0xFF); + return v; + } + + /** Reads a big-endian varint into {@code out[0]} and returns the position after it. */ + private static int readVarint(byte[] b, int off, long[] out) { + long v = 0; + for (int i = 0; i < 8; i++) { + int c = b[off + i] & 0xFF; + v = v << 7 | (c & 0x7F); + if ((c & 0x80) == 0) { + out[0] = v; + return off + i + 1; + } + } + out[0] = v << 8 | (b[off + 8] & 0xFF); + return off + 9; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/SyncItem.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/SyncItem.java new file mode 100644 index 0000000..e8b1f1e --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/SyncItem.java @@ -0,0 +1,42 @@ +package eu.lixko.ts3j.client.teamspeak; + +/** + * One entry of the TeamSpeak 3 client's synchronised item store — the data that + * a myTeamSpeak account syncs between installations. Since client 3.1 the + * bookmarks and identities of every installation live there, signed in or not. + * Whisper lists, hotkey profiles and the other item classes are not modelled. + */ +public sealed interface SyncItem { + + /** The item's own id, a UUID string. */ + String uuid(); + + /** UUID of the {@link Folder} the item sits in, or empty at the top level. */ + String parentUuid(); + + /** UUID of the item just above it in its folder, or empty when it is the first. */ + String previousUuid(); + + record Folder(String uuid, String parentUuid, String previousUuid, String name) implements SyncItem { + } + + /** + * @param identity the key in TeamSpeak's obfuscated {@code V} identity form + * @param nickname the nickname used with this identity when a bookmark names none + */ + record Identity(String uuid, String parentUuid, String previousUuid, String identity, String name, + String nickname, String phoneticNickname, boolean isDefault) implements SyncItem { + } + + /** + * @param identityUuid {@link Identity#uuid()} of the identity to connect with (or its {@link Identity#name()} + * in some myTeamSpeak items); empty for the default + * @param defaultChannel channel path to join, "/"-separated; empty for the server default + * @param defaultChannelId the same channel by id, {@code 0} when unknown + */ + record Bookmark(String uuid, String parentUuid, String previousUuid, String name, String address, int port, + String nickname, String phoneticNickname, String identityUuid, + String serverPassword, String defaultChannel, String defaultChannelPassword, + long defaultChannelId, boolean autoconnect) implements SyncItem { + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/SyncItemDecoder.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/SyncItemDecoder.java new file mode 100644 index 0000000..4b785eb --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/SyncItemDecoder.java @@ -0,0 +1,107 @@ +package eu.lixko.ts3j.client.teamspeak; + +import eu.lixko.ts3j.client.proto.ProtobufReader; + +import java.io.IOException; + +/** + * Decodes a serialised {@code com.teamspeak.sync.proto.Item_Data} message (the + * schema is embedded in the TeamSpeak client binary) into a {@link SyncItem}: + * a row of the local store, or a decrypted myTeamSpeak item, which is the same. + */ +public final class SyncItemDecoder { + + /** Item_Data.parent of a top-level item. */ + private static final String ROOT_PARENT = "ffffffff-ffff-ffff-ffff-ffffffffffff"; + + private static final int ITEM_DELETED = 2; + + private SyncItemDecoder() { + } + + /** + * @return the item, or {@code null} when it is of an unmodelled class or was + * deleted locally and only lingers until the deletion is synced + */ + public static SyncItem decode(byte[] blob) throws IOException { + String uuid = ""; + String parent = ""; + String previous = ""; + boolean deleted = false; + ProtobufReader content = null; + int contentField = 0; + + ProtobufReader r = new ProtobufReader(blob); + while (r.next()) { + switch (r.fieldNumber()) { + case 2 -> uuid = r.readString(); + case 4 -> deleted = r.readVarint() == ITEM_DELETED; + case 7 -> parent = r.readString(); + case 8 -> previous = r.readString(); + case 16, 17, 22 -> { + contentField = r.fieldNumber(); + content = r.readMessage(); + } + default -> r.skip(); + } + } + if (deleted || content == null) return null; + if (parent.equals(ROOT_PARENT)) parent = ""; + return switch (contentField) { + case 16 -> bookmark(uuid, parent, previous, content); + case 17 -> identity(uuid, parent, previous, content); + default -> folder(uuid, parent, previous, content); + }; + } + + private static SyncItem.Bookmark bookmark(String uuid, String parent, String previous, ProtobufReader r) throws IOException { + String name = "", address = "", nickname = "", phonetic = "", identity = ""; + String serverPassword = "", channel = "", channelPassword = ""; + int port = 9987; + long channelId = 0; + boolean autoconnect = false; + while (r.next()) { + switch (r.fieldNumber()) { + case 1 -> name = r.readString(); + case 2 -> address = r.readString(); + case 3 -> port = (int) r.readVarint(); + case 4 -> nickname = r.readString(); + case 5 -> phonetic = r.readString(); + case 6 -> identity = r.readString(); + case 7 -> serverPassword = r.readString(); + case 8 -> channel = r.readString(); + case 9 -> channelPassword = r.readString(); + case 10 -> channelId = r.readVarint(); + case 14 -> autoconnect = r.readBool(); + default -> r.skip(); + } + } + return new SyncItem.Bookmark(uuid, parent, previous, name, address, port, nickname, phonetic, identity, + serverPassword, channel, channelPassword, channelId, autoconnect); + } + + private static SyncItem.Identity identity(String uuid, String parent, String previous, ProtobufReader r) throws IOException { + String identity = "", name = "", nickname = "", phonetic = ""; + boolean isDefault = false; + while (r.next()) { + switch (r.fieldNumber()) { + case 1 -> identity = r.readString(); + case 2 -> name = r.readString(); + case 3 -> nickname = r.readString(); + case 4 -> phonetic = r.readString(); + case 5 -> isDefault = r.readBool(); + default -> r.skip(); + } + } + return new SyncItem.Identity(uuid, parent, previous, identity, name, nickname, phonetic, isDefault); + } + + private static SyncItem.Folder folder(String uuid, String parent, String previous, ProtobufReader r) throws IOException { + String name = ""; + while (r.next()) { + if (r.fieldNumber() == 1) name = r.readString(); + else r.skip(); + } + return new SyncItem.Folder(uuid, parent, previous, name); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/SyncOrder.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/SyncOrder.java new file mode 100644 index 0000000..98074f8 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/SyncOrder.java @@ -0,0 +1,69 @@ +package eu.lixko.ts3j.client.teamspeak; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Puts sync items in the order the TeamSpeak client lists them. The store keeps them in the + * order they were created; each item names the one above it in its folder, so a reorder only + * rewrites those links. + */ +public final class SyncOrder { + + private SyncOrder() { + } + + /** + * The items top to bottom, each folder's contents right after the folder. Items whose + * links lead nowhere, or whose folder is missing, come last in their stored order. + */ + public static List sorted(List items) { + Map> byFolder = new LinkedHashMap<>(); + for (SyncItem item : items) byFolder.computeIfAbsent(item.parentUuid(), k -> new ArrayList<>()).add(item); + + List out = new ArrayList<>(items.size()); + Set placed = new HashSet<>(); + appendFolder("", byFolder, placed, out); + for (List stray : byFolder.values()) { + for (SyncItem item : stray) { + if (!placed.contains(item)) appendFolder(item.parentUuid(), byFolder, placed, out); + } + } + return out; + } + + private static void appendFolder(String folder, Map> byFolder, Set placed, + List out) { + List members = byFolder.getOrDefault(folder, List.of()); + Map> byPrevious = new LinkedHashMap<>(); + for (SyncItem item : members) byPrevious.computeIfAbsent(item.previousUuid(), k -> new ArrayList<>()).add(item); + + List chain = new ArrayList<>(members.size()); + follow(byPrevious.getOrDefault("", List.of()), byPrevious, placed, chain); + // Broken links: the rest start chains of their own. + for (SyncItem item : members) follow(List.of(item), byPrevious, placed, chain); + for (SyncItem item : chain) { + out.add(item); + if (item instanceof SyncItem.Folder) appendFolder(item.uuid(), byFolder, placed, out); + } + } + + /** Appends {@code heads} and, after each, the items below it, depth first. */ + private static void follow(List heads, Map> byPrevious, Set placed, + List chain) { + ArrayDeque stack = new ArrayDeque<>(); + for (int i = heads.size() - 1; i >= 0; i--) stack.push(heads.get(i)); + while (!stack.isEmpty()) { + SyncItem item = stack.pop(); + if (!placed.add(item)) continue; + chain.add(item); + List below = byPrevious.getOrDefault(item.uuid(), List.of()); + for (int i = below.size() - 1; i >= 0; i--) stack.push(below.get(i)); + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakImporter.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakImporter.java new file mode 100644 index 0000000..3240bd4 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakImporter.java @@ -0,0 +1,227 @@ +package eu.lixko.ts3j.client.teamspeak; + +import eu.lixko.ts3j.client.config.Bookmark; +import eu.lixko.ts3j.client.config.Bookmarks; +import eu.lixko.ts3j.client.config.IdentityEntry; +import eu.lixko.ts3j.client.config.IdentityStore; +import eu.lixko.ts3j.client.config.Settings; +import com.github.manevolent.ts3j.identity.LocalIdentity; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Carries the TeamSpeak 3 client's synchronised bookmarks and identities — + * from its local store or a myTeamSpeak account — over into this client's stores. Importing is additive and idempotent: an identity + * already present (same unique ID) or a bookmark already present (same label, + * address and port) is left alone, and bookmarks are wired to the identities + * they referenced in TeamSpeak. + */ +public final class TeamSpeakImporter { + + /** What an import did; {@code known} counts the items that were already there. */ + public record Result(int identitiesAdded, int identitiesKnown, int bookmarksAdded, int bookmarksKnown) { + public int identities() { + return identitiesAdded + identitiesKnown; + } + + public int bookmarks() { + return bookmarksAdded + bookmarksKnown; + } + } + + private final IdentityStore identities; + private final Bookmarks bookmarks; + private final Settings settings; + + public TeamSpeakImporter(IdentityStore identities, Bookmarks bookmarks, Settings settings) { + this.identities = identities; + this.bookmarks = bookmarks; + this.settings = settings; + } + + /** Imports the identities only. */ + public Result importIdentities(File db) throws IOException { + return importItems(TeamSpeakSettingsDb.readSyncItems(db), false, false); + } + + /** Imports the bookmarks, together with the identities they connect with. */ + public Result importBookmarks(File db) throws IOException { + return importItems(TeamSpeakSettingsDb.readSyncItems(db), true, true); + } + + /** Imports every identity and bookmark. */ + public Result importAll(File db) throws IOException { + return importAll(TeamSpeakSettingsDb.readSyncItems(db)); + } + + /** Imports every identity and bookmark among items read elsewhere, such as from a myTeamSpeak account. */ + public Result importAll(List items) throws IOException { + return importItems(items, true, false); + } + + /** + * Imports the chosen items out of {@code all}, together with the identities the chosen + * bookmarks connect with, which only {@code all} may hold. + */ + public Result importSelected(List all, Collection chosen) throws IOException { + Map syncIdentities = identitiesOf(all); + Set selection = new LinkedHashSet<>(chosen); + for (SyncItem item : chosen) { + if (!(item instanceof SyncItem.Bookmark bookmark)) continue; + SyncItem.Identity identity = identityOf(bookmark, syncIdentities); + if (identity != null) selection.add(identity); + } + return importItems(new ArrayList<>(selection), true, false); + } + + /** Whether the item is here already: an identity with the same key, or a bookmark with the same label and address. */ + public boolean isPresent(SyncItem item) { + if (item instanceof SyncItem.Bookmark bookmark) return find(bookmark) != null; + if (!(item instanceof SyncItem.Identity identity)) return false; + try { + return identities.byUniqueId(IdentityStore.parseIdentityString(identity.identity()).getUid().toBase64()) != null; + } catch (IOException malformed) { + return false; + } + } + + /** + * First run — no identity of our own yet — so adopt whatever the TeamSpeak 3 + * client on this machine has, as the contact list does. Quiet on any failure. + * + * @return what was imported, or {@code null} when this was not a first run or there was nothing to import + */ + public Result seedIfFresh() { + if (!identities.isEmpty()) return null; + File db = TeamSpeakSettingsDb.locate(); + if (db == null) return null; + try { + return importAll(db); + } catch (Exception e) { + return null; + } + } + + private Result importItems(List items, boolean withBookmarks, boolean onlyUsedIdentities) + throws IOException { + Map syncIdentities = identitiesOf(items); + List syncBookmarks = new ArrayList<>(); + for (SyncItem item : items) { + if (item instanceof SyncItem.Bookmark bookmark && !bookmark.address().isBlank()) syncBookmarks.add(bookmark); + } + if (onlyUsedIdentities) { + // Only the identities some bookmark connects with come along. + Set referenced = new HashSet<>(); + for (SyncItem.Bookmark bookmark : syncBookmarks) { + SyncItem.Identity identity = identityOf(bookmark, syncIdentities); + if (identity != null) referenced.add(identity); + } + syncIdentities.values().retainAll(referenced); + } + + int identitiesAdded = 0, identitiesKnown = 0, bookmarksAdded = 0, bookmarksKnown = 0; + Map imported = new HashMap<>(); + boolean settingsChanged = false; + + for (SyncItem.Identity identity : syncIdentities.values()) { + LocalIdentity key; + try { + key = IdentityStore.parseIdentityString(identity.identity()); + } catch (IOException malformed) { + continue; + } + IdentityEntry entry = identities.byUniqueId(key.getUid().toBase64()); + if (entry != null) { + identitiesKnown++; + } else { + entry = identities.add(nameOf(identity), key, identity.nickname(), identity.phoneticNickname()); + identitiesAdded++; + } + imported.put(identity.uuid(), entry); + if (!identity.isDefault()) continue; + // No default of our own yet: TeamSpeak's default identity and nickname become ours. + if (identities.byId(settings.defaultIdentityId) == null) { + settings.defaultIdentityId = entry.getId(); + if (!identity.nickname().isBlank()) settings.nickname = identity.nickname(); + settingsChanged = true; + } + } + if (settingsChanged) settings.save(); + if (!withBookmarks) return new Result(identitiesAdded, identitiesKnown, 0, 0); + + for (SyncItem.Bookmark bookmark : syncBookmarks) { + if (find(bookmark) != null) { + bookmarksKnown++; + continue; + } + // A bookmark naming no identity connects with the default one, as it does here. + SyncItem.Identity syncIdentity = identityOf(bookmark, syncIdentities); + IdentityEntry identity = bookmark.identityUuid().isEmpty() || syncIdentity == null + ? null : imported.get(syncIdentity.uuid()); + bookmarks.add(toBookmark(bookmark, identity)); + bookmarksAdded++; + } + if (bookmarksAdded > 0) bookmarks.save(); + return new Result(identitiesAdded, identitiesKnown, bookmarksAdded, bookmarksKnown); + } + + private Bookmark toBookmark(SyncItem.Bookmark sync, IdentityEntry identity) { + // Without a nickname of its own, the bookmark takes the identity's as it connects. + Bookmark b = new Bookmark(sync.name(), sync.address(), sync.port(), sync.nickname(), sync.serverPassword()); + b.identityId = identity == null ? "" : identity.getId(); + b.channel = sync.defaultChannel(); + if (b.channel.isBlank() && sync.defaultChannelId() != 0) b.channel = "/" + sync.defaultChannelId(); + b.channelPassword = sync.defaultChannelPassword(); + b.connectOnStartup = sync.autoconnect(); + return b; + } + + private static Map identitiesOf(List items) { + Map identities = new LinkedHashMap<>(); + for (SyncItem item : items) { + if (item instanceof SyncItem.Identity identity) identities.put(identity.uuid(), identity); + } + return identities; + } + + /** + * The identity a bookmark connects with. Bookmarks normally name it by item UUID, + * but some — seen in a myTeamSpeak account — name it by its display name instead. + */ + private static SyncItem.Identity identityOf(SyncItem.Bookmark bookmark, Map identities) { + String ref = bookmark.identityUuid(); + for (SyncItem.Identity identity : identities.values()) { + if (ref.isEmpty() ? identity.isDefault() : identity.uuid().equals(ref)) return identity; + } + for (SyncItem.Identity identity : identities.values()) { + if (identity.name().equals(ref)) return identity; + } + return null; + } + + private Bookmark find(SyncItem.Bookmark sync) { + for (Bookmark b : bookmarks.all()) { + if (b.port == sync.port() + && sync.address().equalsIgnoreCase(b.address == null ? "" : b.address) + && sync.name().equals(b.label == null ? "" : b.label)) { + return b; + } + } + return null; + } + + private static String nameOf(SyncItem.Identity identity) { + if (!identity.name().isBlank()) return identity.name(); + return identity.nickname().isBlank() ? "TeamSpeak 3 identity" : identity.nickname(); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakSettingsDb.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakSettingsDb.java new file mode 100644 index 0000000..4100f9a --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakSettingsDb.java @@ -0,0 +1,100 @@ +package eu.lixko.ts3j.client.teamspeak; + +import eu.lixko.ts3j.client.contacts.Contact; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * Reads an installed TeamSpeak 3 client's {@code settings.db}: the {@code Contacts} + * table holds one record per contact in the format {@link Contact#parseRecord} + * understands, and {@code ProtobufItems} holds the myTeamSpeak-synchronised + * store — bookmarks, identities and their folders — as {@link SyncItem}s. + */ +public final class TeamSpeakSettingsDb { + + /** Overrides where the TeamSpeak client keeps its configuration. */ + private static final String CONFIG_DIR_PROPERTY = "ts3.config.dir"; + + private TeamSpeakSettingsDb() { + } + + /** The TeamSpeak client's settings database on this machine, or {@code null} when there is none. */ + public static File locate() { + String configured = System.getProperty(CONFIG_DIR_PROPERTY); + List candidates = new ArrayList<>(); + if (configured != null && !configured.isBlank()) candidates.add(new File(configured.trim())); + + String home = System.getProperty("user.home", "."); + candidates.add(new File(home, ".ts3client")); + String appData = System.getenv("APPDATA"); + if (appData != null) candidates.add(new File(appData, "TS3Client")); + candidates.add(new File(home, "Library/Application Support/TeamSpeak 3")); + + for (File dir : candidates) { + File db = new File(dir, "settings.db"); + if (db.isFile()) return db; + } + return null; + } + + /** The contacts of the local TeamSpeak client, or an empty list when it has none or cannot be read. */ + public static List readContacts() { + File db = locate(); + if (db == null) return List.of(); + try { + return readContacts(db); + } catch (Exception e) { + return List.of(); + } + } + + /** @throws IOException when the file is not a readable SQLite database */ + public static List readContacts(File db) throws IOException { + List contacts = new ArrayList<>(); + for (Object value : columnValues(db, "Contacts")) { + if (!(value instanceof String record)) continue; + Contact c = Contact.parseRecord(record); + if (c != null) contacts.add(c); + } + return contacts; + } + + /** + * The synchronised items in the order the client lists them. Rows that are not items — the + * table's checksum, unmodelled classes, pending deletions — are left out. + * + * @throws IOException when the file is not a readable SQLite database + */ + public static List readSyncItems(File db) throws IOException { + List items = new ArrayList<>(); + for (Object value : columnValues(db, "ProtobufItems")) { + if (!(value instanceof byte[] blob)) continue; + SyncItem item; + try { + item = SyncItemDecoder.decode(blob); + } catch (IOException malformed) { + continue; + } + if (item != null) items.add(item); + } + return SyncOrder.sorted(items); + } + + /** The {@code value} column of a key/value table, in row order; empty when the table is absent. */ + private static List columnValues(File db, String tableName) throws IOException { + List values = new ArrayList<>(); + try (SqliteReader reader = new SqliteReader(db)) { + SqliteReader.Table table = reader.readTable(tableName); + if (table == null) return values; + int column = table.columnIndex("value"); + if (column < 0) return values; + for (Object[] row : table.rows) { + if (column < row.length) values.add(row[column]); + } + } + return values; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/text/BBCode.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/text/BBCode.java new file mode 100644 index 0000000..ee1e972 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/text/BBCode.java @@ -0,0 +1,303 @@ +package eu.lixko.ts3j.client.text; + +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Renderer for the small BBCode dialect TeamSpeak uses in chat messages and + * channel/client descriptions. Produces an HTML fragment restricted to the tags + * Swing's HTML 3.2 renderer understands; anything unrecognised is passed + * through as literal text, and all input is escaped, so server-supplied text + * can never inject markup. + */ +public final class BBCode { + + /** {@code [url]http://x[/url]} is rewritten to the {@code [url=…]} form before parsing. */ + private static final Pattern BARE_URL_TAG = + Pattern.compile("\\[url]([^\\[\\]]+)\\[/url]", Pattern.CASE_INSENSITIVE); + private static final Pattern BARE_IMG_TAG = + Pattern.compile("\\[img]([^\\[\\]]+)\\[/img]", Pattern.CASE_INSENSITIVE); + /** A picture's address: only the web, so a description cannot point the client anywhere else. */ + private static final Pattern IMAGE_URL = Pattern.compile("(?i)https?://[^\\s\"'<>]+"); + private static final int MAX_ADDRESS = 48; + private static final Pattern IMG_CLOSE = Pattern.compile("(?i)\\[/img]"); + private static final Pattern PLAIN_URL = + Pattern.compile("(?i)\\b(?:https?://|www\\.)[^\\s<>\"']+"); + private static final Pattern COLOR = Pattern.compile("#[0-9a-fA-F]{3,6}|[a-zA-Z]{3,20}"); + /** Web links plus TeamSpeak's own {@code client://} / {@code channel://} / {@code ts3server://} schemes. */ + private static final Pattern SAFE_URL = + Pattern.compile("(?i)(https?|ftp|client|channel|ts3server|ts3file|offline)://[^\\s\"'<>]*"); + /** TeamSpeak's own protocols, which are rendered without an underline. */ + private static final Pattern TS_PROTOCOL = + Pattern.compile("(?i)^(client|channel|ts3server|ts3file|offline)://"); + private static final Pattern CLIENT_PROTOCOL = Pattern.compile("(?i)^client://"); + + /** CSS class on {@code client://} links, styled like a message author's name. */ + public static final String IDENTITY_LINK_CLASS = "identity"; + /** CSS class on links using TeamSpeak's other protocols (channel, ts3server, …). */ + public static final String TS_LINK_CLASS = "tslink"; + /** CSS class on links that leave the client, so they are visibly not an identity. */ + public static final String EXTERNAL_LINK_CLASS = "extlink"; + + /** A single {@code [url=href]label[/url]} pair, the only markup the log carries. */ + private static final Pattern URL_LINK = + Pattern.compile("(?i)\\[url=([^\\]]+)](.*?)\\[/url]"); + + private BBCode() { + } + + /** Converts BBCode to an HTML fragment (no surrounding {@code } element), pictures as links. */ + public static String toHtml(String input) { + return toHtml(input, false); + } + + /** + * @param images whether {@code [img]} becomes an {@code }, as TeamSpeak shows it in + * descriptions, rather than a link to the picture, as in chat + */ + public static String toHtml(String input, boolean images) { + if (input == null || input.isEmpty()) return ""; + String src = BARE_URL_TAG.matcher(input).replaceAll("[url=$1]$1[/url]"); + if (!images) src = BARE_IMG_TAG.matcher(src).replaceAll("[url=$1]$1[/url]"); + + StringBuilder out = new StringBuilder(); + Deque open = new ArrayDeque<>(); + int i = 0; + while (i < src.length()) { + int lb = src.indexOf('[', i); + if (lb < 0) { + text(out, src.substring(i), open); + break; + } + text(out, src.substring(i, lb), open); + int rb = src.indexOf(']', lb); + if (rb < 0) { + text(out, src.substring(lb), open); + break; + } + if (images && src.substring(lb + 1, rb).equalsIgnoreCase("img")) { + int end = image(out, src, rb + 1); + if (end > 0) { + i = end; + continue; + } + } + if (!emitTag(out, src.substring(lb + 1, rb), open)) { + text(out, src.substring(lb, rb + 1), open); + } + i = rb + 1; + } + while (!open.isEmpty()) out.append(open.pop().close); + return out.toString(); + } + + /** The text BBCode reads as, markup dropped, for places that show no formatting. */ + public static String toPlain(String input) { + return HtmlText.plain(toHtml(input)); + } + + /** + * Renders text carrying {@code [url=…]…[/url]} links and nothing else: everything + * outside those tags stays literal. The server log is written this way, so that a + * name happening to contain bracket markup is shown as it is rather than rendered. + */ + public static String linksToHtml(String input) { + if (input == null || input.isEmpty()) return ""; + StringBuilder out = new StringBuilder(); + Matcher m = URL_LINK.matcher(input); + int last = 0; + while (m.find()) { + out.append(escape(input.substring(last, m.start()))); + String href = m.group(1); + if (SAFE_URL.matcher(href).matches()) { + out.append(link(href)).append(escape(m.group(2))).append(linkClose(href)); + } else { + out.append(escape(m.group())); + } + last = m.end(); + } + return out.append(escape(input.substring(last))).toString(); + } + + /** A long web address as its host and file name, for a link's label where room is short. */ + public static String shortAddress(String url) { + if (url.length() <= MAX_ADDRESS) return url; + int host = url.indexOf("://"); + int path = host < 0 ? -1 : url.indexOf('/', host + 3); + int file = url.lastIndexOf('/'); + if (path < 0 || file <= path) return url; + return url.substring(host + 3, path) + "/…" + url.substring(file); + } + + /** Escapes plain text for HTML without interpreting any BBCode. */ + public static String escape(String s) { + if (s == null) return ""; + return s.replace("&", "&").replace("<", "<").replace(">", ">") + .replace("\"", """); + } + + /** + * Writes the picture whose address starts at {@code from}, up to its {@code [/img]}. + * + * @return where the text goes on after it, or -1 when there is no web address to show + */ + private static int image(StringBuilder out, String src, int from) { + Matcher close = IMG_CLOSE.matcher(src); + if (!close.find(from)) return -1; + String url = src.substring(from, close.start()).trim(); + if (!IMAGE_URL.matcher(url).matches()) return -1; + out.append(""); + return close.end(); + } + + /** True once the tag was recognised and written; false to render it literally. */ + private static boolean emitTag(StringBuilder out, String tag, Deque open) { + if (tag.isEmpty()) return false; + String lower = tag.toLowerCase(); + + if (lower.charAt(0) == '/') { + return closeTag(out, lower.substring(1), open); + } + if (lower.equals("*")) { + if (!contains(open, "list")) return false; + if (peekIs(open, "*")) out.append(open.pop().close); + push(out, open, "*", "
  • ", "
  • "); + return true; + } + + int eq = tag.indexOf('='); + String name = (eq < 0 ? lower : lower.substring(0, eq)).trim(); + String value = eq < 0 ? "" : tag.substring(eq + 1).trim(); + switch (name) { + case "b": + return push(out, open, name, "", ""); + case "i": + return push(out, open, name, "", ""); + case "u": + return push(out, open, name, "", ""); + case "s": + return push(out, open, name, "", ""); + case "hr": + // Stands alone; a closing tag some write after it is dropped, see closeTag. + out.append("
    "); + return true; + case "left": + case "center": + case "right": + case "justify": + return push(out, open, name, "
    ", "
    "); + case "list": + if (value.equals("1")) return push(out, open, name, "
      ", "
    "); + if (value.equalsIgnoreCase("a")) return push(out, open, name, "
      ", "
    "); + return push(out, open, name, "
      ", "
    "); + case "table": + return push(out, open, name, "", "
    "); + case "tr": + if (!contains(open, "table")) return false; + return push(out, open, name, "", ""); + case "td": + case "th": + if (!contains(open, "tr")) return false; + return push(out, open, name, "<" + name + ">", ""); + case "color": { + if (!COLOR.matcher(value).matches()) return false; + return push(out, open, name, "", ""); + } + case "size": { + int px = parseSize(value); + if (px < 0) return false; + return push(out, open, name, "", ""); + } + case "url": { + if (!SAFE_URL.matcher(value).matches()) return false; + return push(out, open, name, link(value), linkClose(value)); + } + + default: + return false; + } + } + + private static boolean closeTag(StringBuilder out, String name, Deque open) { + if (name.equals("hr")) return true; + if (!contains(open, name)) return false; + // Close anything left dangling inside, then the tag itself. + while (!open.isEmpty()) { + Open o = open.pop(); + out.append(o.close); + if (o.name.equals(name)) break; + } + return true; + } + + private static String link(String href) { + return ""; + } + + private static String linkClose(String href) { + return ""; + } + + /** The CSS class a link gets, by protocol. */ + public static String linkClass(String href) { + if (CLIENT_PROTOCOL.matcher(href).find()) return IDENTITY_LINK_CLASS; + return TS_PROTOCOL.matcher(href).find() ? TS_LINK_CLASS : EXTERNAL_LINK_CLASS; + } + + private static boolean push(StringBuilder out, Deque open, String name, + String openHtml, String closeHtml) { + out.append(openHtml); + open.push(new Open(name, closeHtml)); + return true; + } + + private static boolean contains(Deque open, String name) { + for (Open o : open) { + if (o.name.equals(name)) return true; + } + return false; + } + + private static boolean peekIs(Deque open, String name) { + return !open.isEmpty() && open.peek().name.equals(name); + } + + private static int parseSize(String value) { + try { + return Math.max(8, Math.min(28, Integer.parseInt(value.trim()))); + } catch (NumberFormatException e) { + return -1; + } + } + + /** Escapes a text run, turning newlines into breaks and linkifying bare URLs. */ + private static void text(StringBuilder out, String raw, Deque open) { + if (raw.isEmpty()) return; + if (contains(open, "url")) { // don't nest links inside a link label + out.append(escape(raw).replace("\n", "
    ")); + return; + } + Matcher m = PLAIN_URL.matcher(raw); + int last = 0; + while (m.find()) { + out.append(escape(raw.substring(last, m.start())).replace("\n", "
    ")); + String url = m.group(); + String href = url.regionMatches(true, 0, "www.", 0, 4) ? "http://" + url : url; + out.append(link(href)).append(escape(url)).append(linkClose(href)); + last = m.end(); + } + out.append(escape(raw.substring(last)).replace("\n", "
    ")); + } + + private static final class Open { + final String name; + final String close; + + Open(String name, String close) { + this.name = name; + this.close = close; + } + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/text/ChatHtml.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/text/ChatHtml.java new file mode 100644 index 0000000..686827a --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/text/ChatHtml.java @@ -0,0 +1,152 @@ +package eu.lixko.ts3j.client.text; + +import eu.lixko.ts3j.client.myts.ChatAttachment; +import eu.lixko.ts3j.client.myts.ChatAttachments; + +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.Locale; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Builds the entries a chat shows, one {@code
    } of HTML each, the form TeamSpeak's own + * chat logs are in — so live lines and lines loaded from a log history look alike. The + * {@code class} attributes name how a frontend may style them. + */ +public final class ChatHtml { + + /** Timestamps and the chat's own notices. */ + public static final String MUTED_CLASS = "muted"; + /** A server event: someone joining, leaving, moving, a channel being edited, … */ + public static final String EVENT_CLASS = "event"; + /** A sender that cannot be linked to. */ + public static final String NAME_CLASS = "name"; + + /** A file shared in chat; its link's address is a {@link ChatAttachment#href}. */ + public static final String ATTACHMENT_CLASS = "attachment"; + + private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("HH:mm:ss"); + /** The text of a message in TeamSpeak's HTML log. */ + private static final Pattern LOG_TEXT = Pattern.compile("()(.*?)()", + Pattern.DOTALL); + + private ChatHtml() { + } + + /** + * A chat message; the sender becomes a {@code client://} link when their id is known. + * + * @param text the message as sent, in BBCode + */ + public static String message(int fromId, String fromUniqueId, String from, String text) { + return message(fromId, fromUniqueId, from, text, ""); + } + + /** + * A chat message, showing a file shared in it as the file. + * + * @param room the unique identifier of the server the chat is on, where shared files lie + */ + public static String message(int fromId, String fromUniqueId, String from, String text, String room) { + String name = BBCode.escape(from); + String sender = fromId > 0 + ? "" + name + "" + : span(NAME_CLASS, name); + ChatAttachment attachment = ChatAttachment.parse(text); + String body = attachment != null ? attachment(attachment, room) : BBCode.toHtml(text); + return div(span(MUTED_CLASS, stamp()) + sender + ": " + body); + } + + /** + * A shared file: a picture shown as one, anything else as a link with its size. Without + * the room to fetch it from, only its name. + */ + public static String attachment(ChatAttachment attachment, String room) { + String name = BBCode.escape(attachment.fileName().isBlank() ? "file" : attachment.fileName()); + String caption = attachment.caption().isEmpty() ? "" : "
    " + BBCode.escape(attachment.caption()); + if (room == null || room.isBlank()) return span(ATTACHMENT_CLASS, name) + caption; + String href = BBCode.escape(attachment.href(room)); + String open = ""; + if (attachment.isImage() && attachment.fileSize() <= ChatAttachments.MAX_PREVIEW_BYTES) { + return "
    " + open + "
    " + caption; + } + String size = attachment.fileSize() >= 0 ? " " + span(MUTED_CLASS, "(" + size(attachment.fileSize()) + ")") : ""; + return open + name + "" + size + caption; + } + + /** A message as plain text, e.g. for a notification: a shared file as its name. */ + public static String plainMessage(String text) { + ChatAttachment attachment = ChatAttachment.parse(text); + if (attachment == null) return BBCode.toPlain(text); + return attachment.caption().isEmpty() ? attachment.fileName() : attachment.caption(); + } + + /** One of the chat's own notices: connection progress, errors, pokes. */ + public static String system(String text) { + return div(span(MUTED_CLASS, stamp() + BBCode.escape(text))); + } + + /** + * A server event. It names clients and channels with TeamSpeak's own links, which stay + * links; everything else in it is literal text. + */ + public static String serverLog(String text) { + return div(span(EVENT_CLASS, stamp() + BBCode.linksToHtml(text))); + } + + /** + * Brings an entry of TeamSpeak's HTML log into the form of the others: one {@code
    }, + * without the images that log refers to by the native client's own paths. + * + * @return the entry, or empty for one that shows nothing + */ + public static String logEntry(String html) { + return logEntry(html, ""); + } + + /** + * {@link #logEntry(String)}, showing a file shared in the message as the file. + * + * @param room the unique identifier of the server the log is of + */ + public static String logEntry(String html, String room) { + if (html == null || html.isBlank()) return ""; + String normalized = html + .replaceAll("(?i)]*>", "") + .replaceFirst("(?i)^\\s*\\s*$", "
    "); + normalized = withAttachment(normalized, room); + return normalized.startsWith("" + html + ""; + } + + private static String div(String html) { + return "
    " + html + "
    "; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/text/HtmlText.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/text/HtmlText.java new file mode 100644 index 0000000..21ca42b --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/text/HtmlText.java @@ -0,0 +1,56 @@ +package eu.lixko.ts3j.client.text; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** The readable text of an HTML fragment such as a chat log entry, for searching it. */ +public final class HtmlText { + + private static final Pattern BREAK = Pattern.compile("(?i)|"); + private static final Pattern TAG = Pattern.compile("<[^>]*>"); + private static final Pattern ENTITY = Pattern.compile("&(#[0-9]+|#[xX][0-9a-fA-F]+|[a-zA-Z]+);"); + + private HtmlText() { + } + + public static String plain(String html) { + if (html == null || html.isEmpty()) return ""; + String text = TAG.matcher(BREAK.matcher(html).replaceAll("\n")).replaceAll(""); + return text.indexOf('&') < 0 ? text : unescape(text); + } + + private static String unescape(String s) { + Matcher m = ENTITY.matcher(s); + // Android < API 34 lacks Matcher.appendReplacement/appendTail(StringBuilder); original: + // StringBuilder out = new StringBuilder(s.length()); + StringBuffer out = new StringBuffer(s.length()); + while (m.find()) { + String decoded = decode(m.group(1)); + m.appendReplacement(out, Matcher.quoteReplacement(decoded == null ? m.group() : decoded)); + } + m.appendTail(out); + return out.toString(); + } + + private static String decode(String entity) { + if (entity.charAt(0) == '#') { + try { + int cp = entity.length() > 1 && (entity.charAt(1) == 'x' || entity.charAt(1) == 'X') + ? Integer.parseInt(entity.substring(2), 16) + : Integer.parseInt(entity.substring(1)); + return Character.isValidCodePoint(cp) ? new String(Character.toChars(cp)) : null; + } catch (NumberFormatException e) { + return null; + } + } + return switch (entity) { + case "amp" -> "&"; + case "lt" -> "<"; + case "gt" -> ">"; + case "quot" -> "\""; + case "apos" -> "'"; + case "nbsp" -> " "; + default -> null; + }; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/text/Json.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/text/Json.java new file mode 100644 index 0000000..6f91cae --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/text/Json.java @@ -0,0 +1,167 @@ +package eu.lixko.ts3j.client.text; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Just enough JSON for the small objects other clients put into chat messages: values + * come back as {@link String}, {@link Double}, {@link Boolean}, {@code null}, + * {@link List} and {@link Map}. + */ +public final class Json { + + private final String src; + private int pos; + + private Json(String src) { + this.src = src; + } + + /** @return the object {@code text} holds, or {@code null} when it is not a JSON object */ + public static Map parseObject(String text) { + if (text == null) return null; + try { + Json json = new Json(text); + json.skipSpace(); + if (json.peek() != '{') return null; + @SuppressWarnings("unchecked") + Map object = (Map) json.value(); + json.skipSpace(); + return json.pos == text.length() ? object : null; + } catch (IllegalArgumentException | IndexOutOfBoundsException malformed) { + return null; + } + } + + /** {@code s} as a JSON string literal. */ + public static String quote(String s) { + StringBuilder out = new StringBuilder(s.length() + 2).append('"'); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + switch (c) { + case '"' -> out.append("\\\""); + case '\\' -> out.append("\\\\"); + case '\n' -> out.append("\\n"); + case '\r' -> out.append("\\r"); + case '\t' -> out.append("\\t"); + default -> { + if (c < 0x20) out.append(String.format("\\u%04x", (int) c)); + else out.append(c); + } + } + } + return out.append('"').toString(); + } + + private Object value() { + skipSpace(); + char c = peek(); + return switch (c) { + case '{' -> object(); + case '[' -> array(); + case '"' -> string(); + case 't' -> literal("true", Boolean.TRUE); + case 'f' -> literal("false", Boolean.FALSE); + case 'n' -> literal("null", null); + default -> number(); + }; + } + + private Map object() { + Map object = new LinkedHashMap<>(); + pos++; + skipSpace(); + if (peek() == '}') { + pos++; + return object; + } + while (true) { + skipSpace(); + String key = string(); + skipSpace(); + expect(':'); + object.put(key, value()); + skipSpace(); + if (peek() == ',') { + pos++; + continue; + } + expect('}'); + return object; + } + } + + private List array() { + List array = new ArrayList<>(); + pos++; + skipSpace(); + if (peek() == ']') { + pos++; + return array; + } + while (true) { + array.add(value()); + skipSpace(); + if (peek() == ',') { + pos++; + continue; + } + expect(']'); + return array; + } + } + + private String string() { + expect('"'); + StringBuilder out = new StringBuilder(); + while (true) { + char c = src.charAt(pos++); + if (c == '"') return out.toString(); + if (c != '\\') { + out.append(c); + continue; + } + char e = src.charAt(pos++); + switch (e) { + case 'b' -> out.append('\b'); + case 'f' -> out.append('\f'); + case 'n' -> out.append('\n'); + case 'r' -> out.append('\r'); + case 't' -> out.append('\t'); + case 'u' -> { + out.append((char) Integer.parseInt(src.substring(pos, pos + 4), 16)); + pos += 4; + } + default -> out.append(e); + } + } + } + + private Double number() { + int start = pos; + while (pos < src.length() && "+-0123456789.eE".indexOf(src.charAt(pos)) >= 0) pos++; + if (start == pos) throw new IllegalArgumentException("Unexpected " + peek()); + return Double.valueOf(src.substring(start, pos)); + } + + private Object literal(String word, Object value) { + if (!src.startsWith(word, pos)) throw new IllegalArgumentException("Expected " + word); + pos += word.length(); + return value; + } + + private void expect(char c) { + if (peek() != c) throw new IllegalArgumentException("Expected " + c); + pos++; + } + + private char peek() { + return src.charAt(pos); + } + + private void skipSpace() { + while (pos < src.length() && Character.isWhitespace(src.charAt(pos))) pos++; + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/text/TextQuery.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/text/TextQuery.java new file mode 100644 index 0000000..8f30a73 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/text/TextQuery.java @@ -0,0 +1,86 @@ +package eu.lixko.ts3j.client.text; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; + +/** + * What a find bar is looking for: the typed text and how to match it. Immutable, so a + * query can be handed to a background search while the user keeps typing. + */ +public final class TextQuery { + + public static final TextQuery EMPTY = new TextQuery("", false, false, false); + + public final String text; + public final boolean matchCase; + public final boolean wholeWord; + public final boolean regex; + /** {@code null} when the query is empty or not a valid regular expression. */ + private final Pattern pattern; + private final String error; + + public TextQuery(String text, boolean matchCase, boolean wholeWord, boolean regex) { + this.text = text == null ? "" : text; + this.matchCase = matchCase; + this.wholeWord = wholeWord; + this.regex = regex; + Pattern p = null; + String err = null; + if (!this.text.isEmpty()) { + try { + p = compile(); + } catch (PatternSyntaxException e) { + err = e.getDescription(); + } + } + this.pattern = p; + this.error = err; + } + + private Pattern compile() { + String body = regex ? text : Pattern.quote(text); + if (wholeWord) body = "(?/~} and {@code channel:///}. + */ +public final class TsLink { + + public static final String CLIENT_SCHEME = "client://"; + public static final String CHANNEL_SCHEME = "channel://"; + /** Opens the offline message inbox, as the "unread offline messages" log line does. */ + public static final String OFFLINE_MESSAGES_HREF = "offline://"; + + /** A parsed {@code client://} or {@code channel://} link. */ + public static final class Ref { + public final boolean client; + public final int id; + /** Client unique id, or {@code ""} for channel links / when absent. */ + public final String uniqueId; + /** Nickname or channel name, or {@code ""} when absent. */ + public final String name; + + Ref(boolean client, int id, String uniqueId, String name) { + this.client = client; + this.id = id; + this.uniqueId = uniqueId; + this.name = name; + } + } + + private TsLink() { + } + + /** Parses a TS link, or returns {@code null} if it is not one. */ + public static Ref parse(String href) { + if (href == null) return null; + boolean client = startsWithIgnoreCase(href, CLIENT_SCHEME); + if (!client && !startsWithIgnoreCase(href, CHANNEL_SCHEME)) return null; + + String rest = href.substring((client ? CLIENT_SCHEME : CHANNEL_SCHEME).length()); + int slash = rest.indexOf('/'); + String idPart = slash < 0 ? rest : rest.substring(0, slash); + String tail = slash < 0 ? "" : rest.substring(slash + 1); + + int id; + try { + id = Integer.parseInt(idPart.trim()); + } catch (NumberFormatException e) { + return null; + } + + String uid = ""; + String name = tail; + if (client) { + int tilde = tail.indexOf('~'); + if (tilde >= 0) { + uid = tail.substring(0, tilde); + name = tail.substring(tilde + 1); + } else { + uid = tail; + name = ""; + } + } + return new Ref(client, id, decode(uid), decode(name)); + } + + public static boolean isOfflineMessages(String href) { + return href != null && startsWithIgnoreCase(href, OFFLINE_MESSAGES_HREF); + } + + public static String offlineMessagesBBCode(String label) { + return "[URL=" + OFFLINE_MESSAGES_HREF + "]" + label + "[/URL]"; + } + + public static String clientHref(int clientId, String uniqueId, String nickname) { + return CLIENT_SCHEME + clientId + "/" + encode(uniqueId) + "~" + encode(nickname); + } + + public static String channelHref(int channelId, String name) { + return CHANNEL_SCHEME + channelId + "/" + encode(name); + } + + /** The BBCode TeamSpeak inserts when a client is dragged into the text box. */ + public static String clientBBCode(int clientId, String uniqueId, String nickname) { + return "[URL=" + clientHref(clientId, uniqueId, nickname) + "]" + nickname + "[/URL]"; + } + + /** The BBCode TeamSpeak inserts when a channel is dragged into the text box. */ + public static String channelBBCode(int channelId, String name) { + return "[URL=" + channelHref(channelId, name) + "]" + name + "[/URL]"; + } + + private static boolean startsWithIgnoreCase(String s, String prefix) { + return s.regionMatches(true, 0, prefix, 0, prefix.length()); + } + + private static String encode(String s) { + if (s == null) return ""; + try { + // TS3 leaves the base64 padding of unique ids unescaped, so match that. + return URLEncoder.encode(s, "UTF-8").replace("+", "%20").replace("%3D", "="); + } catch (UnsupportedEncodingException e) { + return s; + } + } + + private static String decode(String s) { + if (s == null || s.isEmpty()) return ""; + try { + return URLDecoder.decode(s, "UTF-8"); + } catch (UnsupportedEncodingException | IllegalArgumentException e) { + return s; + } + } +} diff --git a/ts3-client/core/src/test/java/com/ts3client/audio/FakeOpus.java b/ts3-client/core/src/test/java/com/ts3client/audio/FakeOpus.java deleted file mode 100644 index e8d8769..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/audio/FakeOpus.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.ts3client.audio; - -import com.ts3client.audio.opus.OpusCodec; -import com.ts3client.audio.opus.OpusDecoder; -import com.ts3client.audio.opus.OpusEncoder; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Stands in for libopus: a "packet" of n bytes decodes to n 20 ms frames holding the first byte - * divided by 100 in every sample. Concealment yields -1 and recovery -2, so both are easy to spot. - */ -final class FakeOpus implements OpusCodec { - - static final float CONCEALED = -1f; - static final float RECOVERED = -2f; - - int resets; - final List concealedFrameSizes = new ArrayList<>(); - - static byte[] packet(int value) { - return new byte[]{(byte) value}; - } - - @Override - public OpusEncoder createEncoder(int sampleRate, int frameSize, int channels, Application application) { - throw new UnsupportedOperationException(); - } - - @Override - public OpusDecoder createDecoder(int sampleRate, int maxFrameSize, int channels) { - return new OpusDecoder() { - @Override - public int decode(byte[] packet, float[] out) { - int frames = VoiceFormat.FRAME_SIZE * packet.length; - Arrays.fill(out, 0, frames * channels, packet[0] / 100f); - return frames; - } - - @Override - public int conceal(float[] out, int frameSize) { - concealedFrameSizes.add(frameSize); - Arrays.fill(out, 0, frameSize * channels, CONCEALED); - return frameSize; - } - - @Override - public int recover(byte[] next, float[] out, int frameSize) { - Arrays.fill(out, 0, frameSize * channels, RECOVERED); - return frameSize; - } - - @Override - public void reset() { - resets++; - } - - @Override - public void close() { - } - }; - } - - @Override - public String version() { - return "fake"; - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/audio/JitterBufferTest.java b/ts3-client/core/src/test/java/com/ts3client/audio/JitterBufferTest.java deleted file mode 100644 index 9fdff01..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/audio/JitterBufferTest.java +++ /dev/null @@ -1,374 +0,0 @@ -package com.ts3client.audio; - -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class JitterBufferTest { - - private static final int SPAN = JitterBuffer.TEAMSPEAK_TICKS_PER_FRAME; - - private static JitterBuffer buffer() { - return JitterBuffer.forTeamSpeakVoice(SPAN); - } - - /** Frame {@code n} of a stream, tagged so it can be identified on the way out. */ - private static byte[] frame(int n) { - return new byte[]{(byte) n}; - } - - private static void put(JitterBuffer b, int n) { - b.put(frame(n), n * SPAN, SPAN); - } - - /** Pulls one frame, returning its tag, or -1 for concealment. */ - private static int pull(JitterBuffer b) { - JitterBuffer.Status status = b.get(SPAN); - int tag = status == JitterBuffer.Status.OK ? b.payload()[0] : -1; - b.tick(); - return tag; - } - - @Test - void playsAnUndisturbedStreamInOrder() { - JitterBuffer b = buffer(); - List played = new ArrayList<>(); - for (int i = 0; i < 20; i++) { - put(b, i); - played.add(pull(b)); - } - // The buffer holds some delay back, so the tail is still queued; nothing is reordered. - List real = played.stream().filter(n -> n >= 0).toList(); - assertEquals(real.stream().sorted().toList(), real); - assertTrue(real.size() >= 15, "most frames should have played: " + played); - } - - @Test - void aLargerMarginBuffersThatMuchMore() { - JitterBuffer b = buffer(); - int n = 0; - int lastPlayed = -1; - for (; n < 60; n++) { - put(b, n); - int tag = pull(b); - if (tag >= 0) lastPlayed = tag; - } - int before = n - 1 - lastPlayed; - - b.setMargin(b.margin() + 5 * SPAN); - for (; n < 120; n++) { - put(b, n); - int tag = pull(b); - if (tag >= 0) lastPlayed = tag; - } - assertEquals(before + 5, n - 1 - lastPlayed); - } - - @Test - void reordersPacketsThatArriveOutOfOrder() { - JitterBuffer b = buffer(); - // Prime a delay so a swapped pair still lands in time. - for (int i = 0; i < 12; i++) { - put(b, i); - pull(b); - } - - put(b, 13); - put(b, 12); - put(b, 14); - - List played = new ArrayList<>(); - for (int i = 0; i < 6; i++) played.add(pull(b)); - List real = played.stream().filter(n -> n >= 0).toList(); - assertEquals(real.stream().sorted().toList(), real, "played out of order: " + played); - assertTrue(real.contains(12) && real.contains(13) && real.contains(14), "lost a frame: " + played); - } - - @Test - void reportsMissingFramesInsteadOfSkippingAhead() { - JitterBuffer b = buffer(); - for (int i = 0; i < 30; i++) { - if (i != 20) put(b, i); - } - - int concealed = 0; - int played = 0; - for (int i = 0; i < 30; i++) { - if (pull(b) < 0) concealed++; - else played++; - } - assertTrue(concealed >= 1, "the gap should have been concealed"); - assertEquals(29, played, "every delivered frame should still be played"); - } - - @Test - void everyGetYieldsExactlyOneFrameOfAudio() { - JitterBuffer b = buffer(); - Random random = new Random(7); - long ticks = 0; - for (int i = 0; i < 200; i++) { - if (random.nextInt(10) != 0) put(b, i); - b.get(SPAN); - assertEquals(0, b.span() % SPAN, "a partial frame cannot be rendered"); - assertTrue(b.span() > 0); - ticks += b.span(); - b.tick(); - } - // Concealment for a growing delay may run long, but audio never stops or doubles up. - assertTrue(ticks >= 200L * SPAN, "output underran: " + ticks); - } - - @Test - void growsTheDelayWhenArrivalsAreJittery() { - JitterBuffer b = buffer(); - Random random = new Random(11); - - // Deliver in bursts: frames pile up, then nothing arrives for a while. - int next = 0; - int concealedEarly = 0; - int concealedLate = 0; - for (int i = 0; i < 400; i++) { - if (i % 5 == 0) { - int burst = 3 + random.nextInt(4); - for (int j = 0; j < burst && next < 400; j++) put(b, next++); - } - boolean concealed = pull(b) < 0; - if (i < 100) concealedEarly += concealed ? 1 : 0; - else if (i >= 300) concealedLate += concealed ? 1 : 0; - } - - assertTrue(concealedLate < concealedEarly, - "the buffer should settle: " + concealedEarly + " -> " + concealedLate); - } - - @Test - void staysStableAcrossTimestampWraparound() { - JitterBuffer b = buffer(); - // Start just below the point where the tick counter overflows. - int base = Integer.MAX_VALUE - 5 * SPAN; - for (int i = 0; i < 40; i++) { - b.put(frame(i), base + i * SPAN, SPAN); - } - int played = 0; - for (int i = 0; i < 40; i++) { - if (b.get(SPAN) == JitterBuffer.Status.OK) { - assertNotNull(b.payload()); - played++; - } - b.tick(); - } - assertTrue(played >= 35, "wraparound lost frames: " + played); - } - - @Test - void resetForgetsTheTimelineSoTheNextBurstResyncs() { - JitterBuffer b = buffer(); - for (int i = 0; i < 10; i++) { - put(b, i); - pull(b); - } - b.reset(); - assertTrue(b.isEmpty()); - - // A new burst numbered far away must still play, not be treated as hopelessly late. - b.put(frame(1), 500 * SPAN, SPAN); - assertEquals(JitterBuffer.Status.OK, b.get(SPAN)); - assertEquals(1, b.payload()[0]); - } - - @Test - void dropsPacketsThatArriveHopelesslyLate() { - JitterBuffer b = buffer(); - for (int i = 0; i < 40; i++) { - put(b, i); - pull(b); - } - assertFalse(b.isEmpty() && b.bufferedSpan() != 0); - - // A frame from far in the past has nowhere to go and must not stall the stream. - b.put(frame(99), 0, SPAN); - for (int i = 0; i < 5; i++) { - assertTrue(pull(b) != 99, "a hopelessly late frame was played"); - } - } - - @Test - void teamSpeakConfigurationMatchesTheShippedClient() { - JitterBuffer b = JitterBuffer.forTeamSpeakVoice(JitterBuffer.TEAMSPEAK_TICKS_PER_FRAME); - assertEquals(60, JitterBuffer.TEAMSPEAK_TICKS_PER_FRAME); - assertEquals(60, b.margin()); - } - - /** Plays until nothing is held, leaving the position just past the last real frame. */ - private static void drain(JitterBuffer b) { - for (int i = 0; i < 100 && !b.isEmpty(); i++) pull(b); - } - - @Test - void offersTheFollowingPacketToRebuildALostOne() { - JitterBuffer b = buffer(); - for (int i = 0; i < 12; i++) put(b, i); - drain(b); - - // The frame due now never arrives, but the one after it is already here, - // carrying the FEC copy that can rebuild it. - int due = b.position(); - b.put(frame(13), due + SPAN, SPAN); - - assertEquals(JitterBuffer.Status.MISSING, b.get(SPAN)); - assertNotNull(b.nextPayload(), "the successor should be offered for FEC recovery"); - assertEquals(13, b.nextPayload()[0]); - b.tick(); - - // And it is still there to be played normally afterwards. - assertEquals(13, pull(b)); - } - - @Test - void offersNothingWhenTheSuccessorIsAlsoLost() { - JitterBuffer b = buffer(); - for (int i = 0; i < 12; i++) put(b, i); - drain(b); - - // Two frames in a row are gone; FEC only reaches back one. - int due = b.position(); - b.put(frame(15), due + 2 * SPAN, SPAN); - - assertEquals(JitterBuffer.Status.MISSING, b.get(SPAN)); - assertNull(b.nextPayload(), "a double loss cannot be rebuilt from FEC"); - } - - @Test - void aPauseInSpeechCostsNothingWhenTheClockStopsToo() { - JitterBuffer b = buffer(); - for (int i = 0; i < 40; i++) { - put(b, i); - pull(b); - } - drain(b); - - // Silence. No packets arrive and nothing is pulled, so the position stays put — - // which is what lets the sender's numbering still line up when speech resumes. - int paused = b.position(); - assertEquals(paused, b.position()); - - b.put(frame(7), paused, SPAN); - assertEquals(JitterBuffer.Status.OK, b.get(SPAN), "the next burst should play, not be judged late"); - assertEquals(7, b.payload()[0]); - } - - @Test - void keepsItsEstimateAcrossAPause() { - JitterBuffer b = buffer(); - Random random = new Random(5); - int next = 0; - for (int i = 0; i < 300; i++) { - if (i % 4 == 0) { - for (int j = 0, burst = 2 + random.nextInt(4); j < burst; j++) put(b, next++); - } - pull(b); - } - drain(b); - - JitterBuffer fresh = buffer(); - assertTrue(concealedInBurst(b, b.position() / SPAN) <= concealedInBurst(fresh, 1000), - "a buffer that survived the pause should conceal no more than a cold one"); - } - - /** Plays a short jittery burst through a buffer and counts the concealed frames. */ - private static int concealedInBurst(JitterBuffer b, int firstFrame) { - Random random = new Random(9); - int concealed = 0; - int next = firstFrame; - for (int i = 0; i < 60; i++) { - if (i % 4 == 0) { - for (int j = 0, burst = 2 + random.nextInt(4); j < burst; j++) { - b.put(frame(next), next * SPAN, SPAN); - next++; - } - } - if (pull(b) < 0) concealed++; - } - return concealed; - } - - @Test - void resetForgetsTheNetworkEstimateToo() { - JitterBuffer b = buffer(); - for (int i = 0; i < 100; i++) { - put(b, i); - pull(b); - } - b.reset(); - // With no timings recorded there is nothing to justify moving the delay. - assertTrue(b.isEmpty()); - assertEquals(0, b.heldFrames(SPAN)); - } - - @Test - void heldFramesCountsWhatIsWaiting() { - JitterBuffer b = buffer(); - assertEquals(0, b.heldFrames(SPAN)); - put(b, 0); - put(b, 1); - put(b, 2); - assertEquals(3, b.heldFrames(SPAN)); - } - - @Test - void aShortUtteranceComesOutWhole() { - JitterBuffer b = buffer(); - int played = 0; - // Five frames, one per frame period — a single short word. - for (int i = 0; i < 5; i++) { - put(b, i); - if (pull(b) >= 0) played++; - } - // Then whatever the delay is still holding back. - for (int i = 0; i < 20 && !b.isEmpty(); i++) { - if (pull(b) >= 0) played++; - } - assertEquals(5, played, "every frame of a short utterance must be heard"); - } - - @Test - void pullingOnlyWhenAPacketIsWaitingStarvesTheStream() { - // The buffer adapts its delay in tick(), which only runs on a pull. A consumer that - // skips the pull whenever the buffer happens to be empty pins the delay at zero — - // and at zero delay the buffer is empty much of the time, so it never recovers. - int periods = 300; - assertEquals(periods, emitted(true), "a frame per period keeps the device fed"); - - int gated = emitted(false); - assertTrue(gated < periods * 9 / 10, - "gating the pull on a non-empty buffer should visibly starve the device: " + gated); - } - - /** Runs a jittery arrival schedule for 300 periods, counting frames actually emitted. */ - private static int emitted(boolean pullEveryPeriod) { - JitterBuffer b = buffer(); - Random random = new Random(13); - int next = 0; - int frames = 0; - for (int i = 0; i < 300; i++) { - // Arrivals clump and stall, as they do on a real connection. - if (random.nextInt(4) != 0) { - for (int j = 0, burst = random.nextInt(3); j < burst; j++) put(b, next++); - } - if (pullEveryPeriod || !b.isEmpty()) { - b.get(SPAN); - b.tick(); - frames++; - } - } - return frames; - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/audio/MixedPlayoutTest.java b/ts3-client/core/src/test/java/com/ts3client/audio/MixedPlayoutTest.java deleted file mode 100644 index ded30ea..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/audio/MixedPlayoutTest.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.ts3client.audio; - -import com.github.manevolent.ts3j.enums.CodecType; -import com.github.manevolent.ts3j.protocol.ProtocolRole; -import com.github.manevolent.ts3j.protocol.packet.PacketBody0Voice; -import org.junit.jupiter.api.Test; - -import java.util.List; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class MixedPlayoutTest { - - /** A mono line that records every frame written and blocks until the test lets it go on. */ - private static final class RecordingLine implements AudioPlayback { - final BlockingQueue firstSamples = new LinkedBlockingQueue<>(); - final Semaphore permits = new Semaphore(0); - - @Override - public int channels() { - return 1; - } - - @Override - public void start() { - } - - @Override - public void write(byte[] buffer, int offset, int length) { - firstSamples.add((short) ((buffer[offset + 1] << 8) | (buffer[offset] & 0xFF))); - permits.acquireUninterruptibly(); - } - - @Override - public void drain() { - } - - @Override - public void close() { - } - } - - @Test - void mixesSimultaneousSpeakersOntoOneLine() throws Exception { - RecordingLine line = new RecordingLine(); - AudioIo io = new AudioIo() { - @Override - public List inputDevices() { - return List.of(); - } - - @Override - public List outputDevices() { - return List.of(); - } - - @Override - public AudioCapture openCapture(String deviceId, int preferredChannels) { - throw new UnsupportedOperationException(); - } - - @Override - public AudioPlayback openPlayback(String deviceId, int preferredChannels) { - return line; - } - }; - StreamingVoiceOutput output = new StreamingVoiceOutput(io, new FakeOpus(), "", StreamingVoiceOutput.Lines.SHARED); - try { - for (int i = 0; i < 10; i++) { - output.handleVoice(voice(1, i, 25)); - output.handleVoice(voice(2, i, 50)); - } - line.permits.release(100); - - short expected = (short) Math.round(0.75f * 32767f); - boolean mixed = false; - for (int i = 0; i < 20 && !mixed; i++) { - Short sample = line.firstSamples.poll(1, TimeUnit.SECONDS); - assertNotNull(sample, "the mixer stopped writing"); - mixed = sample == expected; - } - assertTrue(mixed, "no frame carried both speakers"); - } finally { - output.shutdown(); - line.permits.release(1000); - } - } - - private static PacketBody0Voice voice(int clientId, int packetId, int value) { - PacketBody0Voice voice = new PacketBody0Voice(ProtocolRole.SERVER); - voice.setClientId(clientId); - voice.setPacketId(packetId); - voice.setCodecType(CodecType.OPUS_VOICE); - voice.setCodecData(FakeOpus.packet(value)); - return voice; - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/audio/VoiceStreamTest.java b/ts3-client/core/src/test/java/com/ts3client/audio/VoiceStreamTest.java deleted file mode 100644 index 149e6a4..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/audio/VoiceStreamTest.java +++ /dev/null @@ -1,246 +0,0 @@ -package com.ts3client.audio; - -import com.github.manevolent.ts3j.enums.CodecType; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class VoiceStreamTest { - - private final FakeOpus opus = new FakeOpus(); - private final List talk = new ArrayList<>(); - private final VoiceStream stream = new VoiceStream(7, opus, (id, talking) -> talk.add(talking)); - private final float[] out = new float[VoiceStream.MAX_FRAME * 2]; - - private boolean offer(int packetId, int value) { - return stream.offer(packetId, CodecType.OPUS_VOICE, FakeOpus.packet(value)); - } - - private void offerEnd(int packetId) { - stream.offer(packetId, CodecType.OPUS_VOICE, new byte[0]); - } - - /** Pulls one frame and returns its first sample, or NaN if nothing was played. */ - private float pull() { - int frames = stream.pull(out, 1, 1.0); - return frames > 0 ? out[0] : Float.NaN; - } - - @Test - void playsPacketsInOrderWhateverOrderTheyArriveIn() { - assertTrue(offer(10, 1)); - assertFalse(offer(12, 3)); - assertFalse(offer(11, 2)); - - assertEquals(0.01f, pull()); - assertEquals(0.02f, pull()); - assertEquals(0.03f, pull()); - assertEquals(List.of(true), talk); - } - - @Test - void tapHearsTheSpeakerInMonoAtFullVolume() { - List tapped = new ArrayList<>(); - stream.setTap((clientId, mono, frames) -> { - assertEquals(7, clientId); - assertEquals(VoiceFormat.FRAME_SIZE, frames); - tapped.add(mono[frames - 1]); - }); - stream.offer(0, CodecType.OPUS_MUSIC, FakeOpus.packet(40)); - stream.pull(out, 2, 0.5); - assertEquals(0.2f, out[1]); - assertEquals(List.of(0.4f), tapped); - } - - @Test - void rebuildsALostPacketFromTheOneAfterIt() { - offer(0, 1); - offer(2, 3); - assertEquals(0.01f, pull()); - assertEquals(FakeOpus.RECOVERED, pull()); - assertEquals(0.03f, pull()); - assertEquals(List.of(), opus.concealedFrameSizes); - } - - @Test - void concealsALostPacketWhenTheNextIsMissingToo() { - offer(0, 1); - offer(3, 4); - assertEquals(0.01f, pull()); - assertEquals(FakeOpus.CONCEALED, pull()); - assertEquals(FakeOpus.RECOVERED, pull()); - assertEquals(0.04f, pull()); - assertEquals(List.of(VoiceFormat.FRAME_SIZE), opus.concealedFrameSizes); - } - - @Test - void anExtraDelayLeadsANewSpeakerInWithSilence() { - stream.setExtraDelay(2 * JitterBuffer.TEAMSPEAK_TICKS_PER_FRAME); - offer(0, 1); - assertEquals(0f, pull()); - offer(1, 2); - assertEquals(0f, pull()); - assertEquals(0.01f, pull()); - assertEquals(0.02f, pull()); - assertEquals(List.of(), opus.concealedFrameSizes); - } - - @Test - void dropsPacketsThatArriveTooLate() { - offer(0, 1); - offer(1, 2); - pull(); - pull(); - assertFalse(offer(0, 9)); - } - - @Test - void aLateCopyAfterTheBurstDoesNotStartAnother() { - offer(0, 1); - offerEnd(1); - pull(); - pull(); - assertFalse(offer(0, 1)); - assertFalse(stream.isPlaying()); - assertEquals(List.of(true, false), talk); - } - - @Test - void countsWhatCameInAndWhatWasMissing() { - offer(0, 1); - offer(2, 3); - offer(1, 2); // out of order, still in time - offer(2, 3); // a copy - pull(); - pull(); - pull(); - pull(); // 3 never arrives: concealed - offer(3, 4); // too late, dropped - offer(3, 4); // a copy of that - assertEquals(new VoiceReceiveStats(6, 3, 1, 0, 1, 1, 2), stream.stats()); - } - - @Test - void theTalkersStopEndsTheBurst() { - offer(0, 1); - offerEnd(1); - assertEquals(0.01f, pull()); - assertEquals(VoiceStream.IDLE, stream.pull(out, 1, 1.0)); - assertFalse(stream.isPlaying()); - assertEquals(List.of(true, false), talk); - } - - @Test - void theNextBurstCarriesOnWhereTheLastStopped() { - offer(0, 1); - offerEnd(1); - pull(); - pull(); - - assertTrue(offer(2, 2), "the next packet starts a new burst"); - assertEquals(0f, pull(), "the stop's slot is the talker's own silence, not a loss"); - assertEquals(0.02f, pull()); - assertEquals(0, opus.resets, "the decoder keeps its state between bursts"); - assertEquals(List.of(), opus.concealedFrameSizes); - } - - @Test - void givesUpOnABurstWhoseStopWasLost() { - offer(0, 1); - pull(); - int concealed = 0; - while (stream.pull(out, 1, 1.0) != VoiceStream.IDLE) concealed++; - assertTrue(concealed > 0 && concealed < 10, "concealed " + concealed + " frames"); - assertEquals(List.of(true, false), talk); - } - - @Test - void playsALongPacketOneFrameAtATime() { - stream.offer(0, CodecType.OPUS_VOICE, new byte[]{40, 0}); - offer(1, 50); - assertEquals(VoiceFormat.FRAME_SIZE, stream.pull(out, 1, 1.0)); - assertEquals(0.4f, out[0]); - assertEquals(VoiceFormat.FRAME_SIZE, stream.pull(out, 1, 1.0)); - assertEquals(0.4f, out[0]); - assertEquals(0.5f, pull()); - } - - @Test - void stopFromAnotherThreadEndsTheBurst() { - offer(0, 1); - stream.stop(); - assertEquals(VoiceStream.IDLE, stream.pull(out, 1, 1.0)); - assertEquals(List.of(true, false), talk); - } - - @Test - void spreadsMonoOverStereoWithGain() { - offer(0, 50); - assertEquals(VoiceFormat.FRAME_SIZE, stream.pull(out, 2, 0.5)); - assertEquals(0.25f, out[0]); - assertEquals(0.25f, out[1]); - assertEquals(0.25f, out[2 * VoiceFormat.FRAME_SIZE - 1]); - } - - @Test - void neverHandsOutMoreThanOneFrame() { - for (int i = 0; i < 50; i++) offer(i, 1); - for (int i = 0; i < 50; i++) assertTrue(stream.pull(out, 1, 1.0) <= VoiceFormat.FRAME_SIZE); - } - - /** - * Packets sent every 20 ms arrive up to 60 ms late. A fixed delay short of that conceals - * constantly; the adaptive one should learn the spread and stop concealing. - */ - @Test - void learnsADelayThatRidesOutJitter() { - Random random = new Random(1); - int packets = 1500; - long[] arrival = new long[packets]; - for (int i = 0; i < packets; i++) arrival[i] = i * 20L + random.nextInt(61); - - int next = 0; - int concealedLate = 0; - for (long now = 0; now < packets * 20L; now += 20) { - for (; next < packets && arrival[next] <= now; next++) offer(next, 1); - // arrivals are not in order, but whatever is due by now has been offered - float sample = pull(); - if (now >= packets * 10L && sample == FakeOpus.CONCEALED) concealedLate++; - } - assertTrue(concealedLate < packets / 2 / 50, "concealed " + concealedLate + " frames in the second half"); - } - - /** - * Every packet is sent twice, the copy 120 ms after the original, and a tenth of the - * originals are lost. The copies arrive too late for a buffer tuned to the originals, so - * it has to learn from them and grow until they are in time to stand in. - */ - @Test - void growsToWaitForRedundantCopies() { - Random random = new Random(1); - int packets = 1500; - List arrivals = new ArrayList<>(); - for (int i = 0; i < packets; i++) { - if (random.nextInt(10) != 0) arrivals.add(new long[]{i * 20L, i}); - arrivals.add(new long[]{i * 20L + 120, i}); - } - arrivals.sort((x, y) -> Long.compare(x[0], y[0])); - - int next = 0; - int concealedLate = 0; - for (long now = 0; now < packets * 20L; now += 20) { - for (; next < arrivals.size() && arrivals.get(next)[0] <= now; next++) { - offer((int) arrivals.get(next)[1], 1); - } - float sample = pull(); - if (now >= packets * 10L && sample == FakeOpus.CONCEALED) concealedLate++; - } - assertTrue(concealedLate < packets / 2 / 100, "concealed " + concealedLate + " frames in the second half"); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/audio/processing/AudioProcessorTest.java b/ts3-client/core/src/test/java/com/ts3client/audio/processing/AudioProcessorTest.java deleted file mode 100644 index f6283d0..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/audio/processing/AudioProcessorTest.java +++ /dev/null @@ -1,194 +0,0 @@ -package com.ts3client.audio.processing; - -import com.ts3client.audio.processing.ns.SuppressionLevel; -import org.junit.jupiter.api.Test; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.Random; -import java.util.Set; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Checks the chain against WebRTC itself. The {@code golden-*.s16} resources are - * {@link #testSignal()} run through upstream APM (webrtc-audio-processing 2.1 for noise - * suppression, 1.3 for the transient suppressor, which 2.x no longer ships), configured as - * TS3 configures it, and stored as 16-bit PCM. - */ -class AudioProcessorTest { - - private static final int RATE = AudioProcessor.SAMPLE_RATE; - private static final int FRAME = AudioProcessor.FRAME_SIZE; - - /** 10 ms frames in which the test signal has a key click, reported as key presses. */ - static final int[] KEY_FRAMES = {66, 72, 79, 85, 90, 97}; - private static final Set KEYS = Set.of(66, 72, 79, 85, 90, 97); - - /** - * One second of microphone-like input: quiet pink noise throughout, a voiced harmonic - * burst from 0.3 to 0.6 s, and key clicks after it. - */ - static float[] testSignal() { - Random random = new Random(11); - float[] x = new float[RATE]; - double b0 = 0, b1 = 0, b2 = 0; - for (int i = 0; i < x.length; i++) { - double w = random.nextGaussian(); - b0 = 0.99765 * b0 + w * 0.0990460; - b1 = 0.96300 * b1 + w * 0.2965164; - b2 = 0.57000 * b2 + w * 1.0526913; - double noise = (b0 + b1 + b2 + w * 0.1848) * 0.0012; - - double t = (double) i / RATE; - double voice = 0; - if (t >= 0.3 && t < 0.6) { - double envelope = Math.sin(Math.PI * (t - 0.3) / 0.3); - for (int h = 1; h <= 20; h++) { - voice += Math.sin(2 * Math.PI * 140 * h * t + h) / h; - } - voice *= 0.08 * envelope; - } - x[i] = (float) (noise + voice); - } - for (int frame : KEY_FRAMES) { - int start = frame * FRAME + 100; - for (int k = 0; k < 480; k++) { - x[start + k] += (float) (random.nextGaussian() * 0.1 * Math.exp(-k / 96.0)); - } - } - return x; - } - - private static float[] run(AudioProcessor processor, float[] input, Set keyFrames) { - float[] x = input.clone(); - float[] frame = new float[FRAME]; - for (int f = 0; f * FRAME + FRAME <= x.length; f++) { - if (keyFrames.contains(f)) processor.keyPressed(); - System.arraycopy(x, f * FRAME, frame, 0, FRAME); - processor.process(frame, FRAME); - System.arraycopy(frame, 0, x, f * FRAME, FRAME); - } - return x; - } - - private static void assertMatchesGolden(String name, float[] actual) throws IOException { - short[] golden = loadGolden(name); - assertEquals(golden.length, actual.length); - double maxDiff = 0; - double sumSquares = 0; - for (int i = 0; i < actual.length; i++) { - double d = actual[i] * 32768.0 - golden[i]; - maxDiff = Math.max(maxDiff, Math.abs(d)); - sumSquares += d * d; - } - double rms = Math.sqrt(sumSquares / actual.length); - // The reference is quantised to 16 bits, and float rounding differs slightly from - // upstream's: anything within a few LSB is the same signal. - assertTrue(maxDiff <= 4, name + ": max deviation " + maxDiff + " LSB"); - assertTrue(rms <= 0.6, name + ": RMS deviation " + rms + " LSB"); - } - - private static short[] loadGolden(String name) throws IOException { - try (InputStream in = AudioProcessorTest.class.getResourceAsStream(name)) { - assertNotNull(in, name); - ByteBuffer bytes = ByteBuffer.wrap(in.readAllBytes()).order(ByteOrder.LITTLE_ENDIAN); - short[] out = new short[bytes.remaining() / 2]; - bytes.asShortBuffer().get(out); - return out; - } - } - - @Test - void everythingOffPassesAudioThroughUntouched() { - float[] x = testSignal(); - assertArrayEquals(x, run(new AudioProcessor(), x, KEYS)); - } - - @Test - void noiseSuppressionMatchesWebRtcAtEveryLevel() throws IOException { - for (int level = 0; level <= 3; level++) { - AudioProcessor p = new AudioProcessor(); - p.setNoiseSuppression(true); - p.setSuppressionLevel(SuppressionLevel.fromDenoiserLevel(level)); - assertMatchesGolden("golden-ns" + level + ".s16", run(p, testSignal(), Set.of())); - } - } - - @Test - void typingAttenuationMatchesWebRtc() throws IOException { - AudioProcessor p = new AudioProcessor(); - p.setNoiseSuppression(true); - p.setSuppressionLevel(SuppressionLevel.DB_12); - p.setTransientSuppression(true); - assertMatchesGolden("golden-ns1-typing.s16", run(p, testSignal(), KEYS)); - } - - @Test - void typingAttenuationOnlyDelaysWithoutKeyPresses() { - float[] x = testSignal(); - AudioProcessor p = new AudioProcessor(); - p.setTransientSuppression(true); - float[] y = run(p, x, Set.of()); - int delay = 1024 - FRAME; - for (int i = delay; i < x.length; i++) { - assertEquals(x[i - delay], y[i], 0.0f); - } - } - - @Test - void gainControlRaisesQuietSpeechAndLeavesSilenceAlone() { - AudioProcessor p = new AudioProcessor(); - p.setGainControl(true); - float[] silence = run(p, new float[RATE], Set.of()); - for (float s : silence) assertEquals(0.0f, s, 0.0f); - - // 3 s of quiet voiced "words" at about -40 dBFS over a -70 dBFS noise floor. The - // pauses matter: without them AGC2 would take the voice for the noise floor. - Random random = new Random(5); - float[] quiet = new float[RATE * 3]; - for (int i = 0; i < quiet.length; i++) { - double t = (double) i / RATE; - double v = 0; - if (t % 0.5 < 0.3) { - for (int h = 1; h <= 20; h++) v += Math.sin(2 * Math.PI * 130 * h * t + h) / h; - v *= 0.004 * Math.sin(Math.PI * (t % 0.5) / 0.3); - } - quiet[i] = (float) (v + random.nextGaussian() * 0.0003); - } - float[] out = run(p, quiet, Set.of()); - assertTrue(rms(out, RATE * 2, RATE * 3) > 4 * rms(quiet, RATE * 2, RATE * 3), - "quiet speech should be raised by more than 12 dB"); - } - - @Test - void gainBoostLetsTheNoiseFloorRiseFurther() { - // -60 dBFS of noise alone: AGC2 starts at 15 dB of gain and, with no speech to - // raise it, can only lower it, down to what keeps the noise under its cap. - Random random = new Random(3); - float[] noise = new float[RATE * 3]; - for (int i = 0; i < noise.length; i++) noise[i] = (float) (random.nextGaussian() * 0.001); - - AudioProcessor plain = new AudioProcessor(); - plain.setGainControl(true); - AudioProcessor boosted = new AudioProcessor(); - boosted.setGainControl(true); - boosted.setGainBoost(20); - - double plainDb = 20 * Math.log10(rms(run(plain, noise, Set.of()), RATE * 2, RATE * 3)); - double boostedDb = 20 * Math.log10(rms(run(boosted, noise, Set.of()), RATE * 2, RATE * 3)); - assertEquals(-50, plainDb, 1.5, "the noise is held at AGC2's -50 dBFS cap"); - assertEquals(-45, boostedDb, 1.5, "with the cap 20 dB higher, the initial 15 dB of gain stays"); - } - - private static double rms(float[] x, int from, int to) { - double sum = 0; - for (int i = from; i < to; i++) sum += x[i] * x[i]; - return Math.sqrt(sum / (to - from)); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/audio/vad/RealFftTest.java b/ts3-client/core/src/test/java/com/ts3client/audio/vad/RealFftTest.java deleted file mode 100644 index 19c2722..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/audio/vad/RealFftTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.ts3client.audio.vad; - -import org.junit.jupiter.api.Test; - -import java.util.Random; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -class RealFftTest { - - /** - * The rnn_vad transform length is 480 = 2^5 * 3 * 5, so the mixed-radix path has to be - * right for factors other than powers of two. - */ - @Test - void matchesDirectDftForMixedRadixLengths() { - for (int n : new int[]{480, 240, 512, 64, 60, 210, 100}) { - RealFft fft = new RealFft(n); - Random random = new Random(n); - float[] in = new float[n]; - float[] out = new float[n]; - for (int i = 0; i < n; i++) { - in[i] = (float) random.nextGaussian(); - } - fft.forward(in, out); - - for (int k = 0; k <= n / 2; k++) { - double re = 0; - double im = 0; - for (int t = 0; t < n; t++) { - double angle = -2 * Math.PI * k * t / n; - re += in[t] * Math.cos(angle); - im += in[t] * Math.sin(angle); - } - double gotRe; - double gotIm; - if (k == 0) { - gotRe = out[0]; - gotIm = 0; - } else if (k == n / 2) { - gotRe = out[1]; // Packed layout keeps Nyquist in slot 1. - gotIm = 0; - } else { - gotRe = out[2 * k]; - gotIm = out[2 * k + 1]; - } - assertEquals(re, gotRe, 1e-2, "n=" + n + " bin=" + k + " real"); - assertEquals(im, gotIm, 1e-2, "n=" + n + " bin=" + k + " imag"); - } - } - } - - @Test - void rejectsOddLengths() { - org.junit.jupiter.api.Assertions.assertThrows( - IllegalArgumentException.class, () -> new RealFft(481)); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/audio/vad/RnnVadTest.java b/ts3-client/core/src/test/java/com/ts3client/audio/vad/RnnVadTest.java deleted file mode 100644 index c865a97..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/audio/vad/RnnVadTest.java +++ /dev/null @@ -1,129 +0,0 @@ -package com.ts3client.audio.vad; - -import org.junit.jupiter.api.Test; - -import java.util.Random; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Behavioural checks on the {@code rnn_vad} port. The network weights are the ones the TS3 - * client links, so these also pin the detector's agreement with it. - */ -class RnnVadTest { - - private static final int FRAMES = 60; - - @Test - void silenceScoresZero() { - float[] x = new float[RnnVad.FRAME_SIZE * FRAMES]; - double[] probabilities = run(x); - for (double p : probabilities) { - assertEquals(0.0, p, 0.0, "silence must not score above zero"); - } - } - - @Test - void voicedSpeechLikeSignalScoresHigh() { - float[] x = synth(FRAMES, t -> { - double sum = 0; - for (int h = 1; h <= 30 && 120 * h < 8000; h++) { - double f = 120 * h; - double gain = formant(f, 700, 90) + formant(f, 1220, 110) + formant(f, 2600, 160); - sum += gain * Math.sin(2 * Math.PI * f * t + h); - } - // A slow tremolo keeps it from looking like a stationary tone. - return 0.25 * (0.6 + 0.4 * Math.sin(2 * Math.PI * 5 * t)) * sum / 6.0; - }); - // Skip the first frames: the pitch buffer and GRU need history. - assertTrue(meanFrom(run(x), 20) > 0.8, "a voiced signal should score high"); - } - - @Test - void quietPinkNoiseScoresLow() { - Random random = new Random(3); - float[] x = new float[RnnVad.FRAME_SIZE * FRAMES]; - double b0 = 0; - double b1 = 0; - double b2 = 0; - for (int i = 0; i < x.length; i++) { - double w = random.nextGaussian(); - b0 = 0.99765 * b0 + w * 0.0990460; - b1 = 0.96300 * b1 + w * 0.2965164; - b2 = 0.57000 * b2 + w * 1.0526913; - // About -45 dBFS: representative of room tone rather than loud hiss. - x[i] = (float) ((b0 + b1 + b2 + w * 0.1848) * 0.0011); - } - assertTrue(meanFrom(run(x), 20) < 0.2, "quiet room tone should not read as speech"); - } - - @Test - void estimatesPitchPeriodExactly() { - // The pitch feature is fed to the network as 0.01 * (period48k - 300). - for (double f0 : new double[]{80, 100, 120, 150, 200, 250, 300, 400}) { - RnnVad vad = new RnnVad(); - float[] x = synth(FRAMES, t -> { - double sum = 0; - for (int h = 1; h <= 40 && f0 * h < 11000; h++) { - sum += Math.sin(2 * Math.PI * f0 * h * t) / h; - } - return 0.2 * sum; - }); - for (int f = 0; f < FRAMES; f++) { - vad.process(x, f * RnnVad.FRAME_SIZE); - } - assertEquals(48000 / f0, vad.pitchPeriod48kHz(), 1e-9, - "pitch period for f0=" + f0); - } - } - - @Test - void resetClearsState() { - float[] x = synth(FRAMES, t -> 0.3 * Math.sin(2 * Math.PI * 200 * t)); - RnnVad vad = new RnnVad(); - for (int f = 0; f < FRAMES; f++) { - vad.process(x, f * RnnVad.FRAME_SIZE); - } - assertTrue(vad.probability() > 0.0); - vad.reset(); - assertEquals(0.0, vad.probability(), 0.0); - } - - // ---- helpers ---- - - private interface Signal { - double at(double t); - } - - private static double formant(double f, double centre, double bandwidth) { - double d = (f - centre) / bandwidth; - return 1.0 / (1.0 + d * d); - } - - private static float[] synth(int frames, Signal signal) { - float[] x = new float[RnnVad.FRAME_SIZE * frames]; - for (int i = 0; i < x.length; i++) { - x[i] = (float) signal.at((double) i / RnnVad.SAMPLE_RATE); - } - return x; - } - - private static double[] run(float[] x) { - RnnVad vad = new RnnVad(); - int frames = x.length / RnnVad.FRAME_SIZE; - double[] probabilities = new double[frames]; - for (int i = 0; i < frames; i++) { - probabilities[i] = vad.process(x, i * RnnVad.FRAME_SIZE); - } - return probabilities; - } - - private static double meanFrom(double[] values, int start) { - double sum = 0; - for (int i = start; i < values.length; i++) { - sum += values[i]; - } - return sum / (values.length - start); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/chatlog/ChatLogStoreTest.java b/ts3-client/core/src/test/java/com/ts3client/chatlog/ChatLogStoreTest.java deleted file mode 100644 index 2942b34..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/chatlog/ChatLogStoreTest.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.ts3client.chatlog; - -import com.ts3client.text.TextQuery; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class ChatLogStoreTest { - - @TempDir - Path temp; - - @Test - void writesTs3CompatibleClientLogNamesAndEntries() throws Exception { - ChatLogStore logs = new ChatLogStore(temp, "+Tyg2JtxE8vRNZp+JiUBnmBh0MY="); - - logs.begin(); - logs.appendPrivateMessage("cckqISCrfr6Lq2SLMC//afsbO9w=", true, - 610, "bdrlePoB9hU8K8CyjCabY07t3Wo=", "ericek111", "hello"); - - Path serverDir = temp.resolve("K1R5ZzJKdHhFOHZSTlpwK0ppVUJubUJoME1ZPQ=="); - Path clientHtml = serverDir.resolve("clients") - .resolve("Y2NrcUlTQ3JmcjZMcTJTTE1DLy9hZnNiTzl3PQ==.html"); - Path clientTxt = serverDir.resolve("clients") - .resolve("Y2NrcUlTQ3JmcjZMcTJTTE1DLy9hZnNiTzl3PQ==.txt"); - - assertTrue(Files.isRegularFile(serverDir.resolve("server.html"))); - assertTrue(Files.isRegularFile(serverDir.resolve("channel.html"))); - assertTrue(Files.isRegularFile(clientHtml)); - assertEquals(1, Files.readAllLines(clientTxt).size()); - - List history = logs.privateHtmlHistory("cckqISCrfr6Lq2SLMC//afsbO9w="); - assertEquals(1, history.size()); - assertTrue(history.get(0).contains("TextMessage_Message")); - assertTrue(history.get(0).contains("ericek111")); - assertTrue(history.get(0).contains("hello")); - } - - @Test - void searchReachesPastTheLoadedHistory() throws Exception { - ChatLogStore logs = new ChatLogStore(temp, "+Tyg2JtxE8vRNZp+JiUBnmBh0MY="); - logs.appendMessage(ChatLogScope.CHANNEL, false, 5, "uid", "alice", "the needle is here"); - for (int i = 0; i < ChatLogStore.HISTORY_LIMIT; i++) { - logs.appendMessage(ChatLogScope.CHANNEL, false, 5, "uid", "alice", "filler " + i); - } - logs.appendServerEvent("a NEEDLE of the server"); - - assertTrue(logs.channelHtmlHistory().stream().noneMatch(e -> e.contains("needle"))); - ChatLogStore.SearchResult channel = logs.search(ChatLogScope.CHANNEL, null, - new TextQuery("needle", false, false, false), 10); - assertEquals(1, channel.total()); - assertTrue(channel.entries().get(0).contains("the needle is here")); - - ChatLogStore.SearchResult server = logs.search(ChatLogScope.SERVER, null, - new TextQuery("needle", true, false, false), 10); - assertEquals(0, server.total()); - - ChatLogStore.SearchResult capped = logs.search(ChatLogScope.CHANNEL, null, - new TextQuery("filler", false, false, false), 10); - assertEquals(ChatLogStore.HISTORY_LIMIT, capped.total()); - assertEquals(10, capped.entries().size()); - assertTrue(capped.truncated()); - assertTrue(capped.entries().get(9).contains("filler " + (ChatLogStore.HISTORY_LIMIT - 1))); - } - - @Test - void readsAMessageWithLineBreaksBackWhole() throws Exception { - ChatLogStore logs = new ChatLogStore(temp, "+Tyg2JtxE8vRNZp+JiUBnmBh0MY="); - logs.appendMessage(ChatLogScope.CHANNEL, false, 5, "uid", "alice", "first line\n\nthird line"); - logs.appendMessage(ChatLogScope.CHANNEL, false, 5, "uid", "bob", "reply"); - - List history = logs.channelHtmlHistory(); - assertEquals(2, history.size()); - assertTrue(history.get(0).contains("first line

    third line"), history.get(0)); - assertTrue(history.get(1).contains("reply")); - } - - @Test - void historyComesFromTheEndOfALongLog() throws Exception { - ChatLogStore logs = new ChatLogStore(temp, "+Tyg2JtxE8vRNZp+JiUBnmBh0MY="); - logs.appendMessage(ChatLogScope.CHANNEL, false, 5, "uid", "alice", "start"); - Path txt = logs.serverDir().resolve("channel.txt"); - StringBuilder filler = new StringBuilder(); - for (int i = 0; i < 200_000; i++) filler.append("<12:00:00> alice: žluťoučký kůň ").append(i).append('\n'); - Files.writeString(txt, filler, java.nio.file.StandardOpenOption.APPEND); - logs.appendMessage(ChatLogScope.CHANNEL, false, 5, "uid", "bob", "the latest"); - - List history = logs.channelHtmlHistory(); - assertEquals(ChatLogStore.HISTORY_LIMIT, history.size()); - assertTrue(history.get(history.size() - 1).contains("the latest")); - assertTrue(history.get(0).contains("žluťoučký kůň"), history.get(0)); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/config/IdentityStoreTest.java b/ts3-client/core/src/test/java/com/ts3client/config/IdentityStoreTest.java deleted file mode 100644 index 8f7b2c7..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/config/IdentityStoreTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.ts3client.config; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.nio.file.Path; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -class IdentityStoreTest { - - @TempDir - Path dir; - - @BeforeEach - void freshProfile() { - AppDirs.init(dir.toFile(), dir.resolve("chats")); - } - - @AfterEach - void defaultProfile() { - AppDirs.init(null, null); - } - - @Test - void exportedIdentityImportsWithItsName() throws Exception { - IdentityStore store = IdentityStore.load(new Settings()); - IdentityEntry original = store.generate("Žofia's key", 0); - - ByteArrayOutputStream exported = new ByteArrayOutputStream(); - store.exportTo(original, exported); - IdentityEntry imported = store.importStream(new ByteArrayInputStream(exported.toByteArray()), null); - - assertEquals("Žofia's key", imported.getName()); - assertEquals(original.getUniqueId(), imported.getUniqueId()); - assertNotEquals(original.getId(), imported.getId()); - assertEquals(2, IdentityStore.load(new Settings()).all().size()); - } - - @Test - void nicknamesTravelWithTheIdentity() throws Exception { - IdentityStore store = IdentityStore.load(new Settings()); - IdentityEntry original = store.generate("Work", 0); - store.setNicknames(original, " Žofia ", "Zofia"); - - IdentityEntry reloaded = IdentityStore.load(new Settings()).byId(original.getId()); - assertEquals("Žofia", reloaded.getNickname()); - assertEquals("Zofia", reloaded.getPhoneticNickname()); - - ByteArrayOutputStream exported = new ByteArrayOutputStream(); - store.exportTo(original, exported); - IdentityEntry imported = store.importStream(new ByteArrayInputStream(exported.toByteArray()), null); - assertEquals("Žofia", imported.getNickname()); - assertEquals("Zofia", imported.getPhoneticNickname()); - } - - @Test - void givenNameWinsOverTheFilesOwn() throws Exception { - IdentityStore store = IdentityStore.load(new Settings()); - ByteArrayOutputStream exported = new ByteArrayOutputStream(); - store.exportTo(store.generate("First", 0), exported); - - IdentityEntry imported = store.importStream(new ByteArrayInputStream(exported.toByteArray()), "Second"); - - assertEquals("Second", imported.getName()); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/config/ProfileFilesTest.java b/ts3-client/core/src/test/java/com/ts3client/config/ProfileFilesTest.java deleted file mode 100644 index f32d881..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/config/ProfileFilesTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.ts3client.config; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.attribute.PosixFilePermissions; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -class ProfileFilesTest { - - @TempDir - Path dir; - - @Test - void replacesTheFileReadableByTheUserOnly() throws Exception { - File file = dir.resolve("settings.properties").toFile(); - Files.writeString(file.toPath(), "old"); - - ProfileFiles.write(file, out -> out.write("new".getBytes())); - - assertEquals("new", Files.readString(file.toPath())); - assertEquals("rw-------", PosixFilePermissions.toString(Files.getPosixFilePermissions(file.toPath()))); - try (var left = Files.list(dir)) { - assertEquals(1, left.count(), "no temporary file left behind"); - } - } - - @Test - void aFailedWriteLeavesTheOldFileAlone() throws Exception { - File file = dir.resolve("bookmarks.properties").toFile(); - Files.writeString(file.toPath(), "old"); - - assertThrows(IOException.class, () -> ProfileFiles.write(file, out -> { - out.write("half".getBytes()); - throw new IOException("crashed"); - })); - - assertEquals("old", Files.readString(file.toPath())); - try (var left = Files.list(dir)) { - assertEquals(1, left.count(), "no temporary file left behind"); - } - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/config/ServerLogSettingsTest.java b/ts3-client/core/src/test/java/com/ts3client/config/ServerLogSettingsTest.java deleted file mode 100644 index 112125b..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/config/ServerLogSettingsTest.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.ts3client.config; - -import com.ts3client.config.ServerLogSettings.Highlight; -import com.ts3client.net.ServerLogEntry.Level; -import org.junit.jupiter.api.Test; - -import java.util.List; -import java.util.Properties; -import java.util.Set; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class ServerLogSettingsTest { - - @Test - void whatIsStoredLoadsBack() { - ServerLogSettings saved = new ServerLogSettings(); - saved.levels.remove(Level.INFO); - saved.localTime = true; - saved.highlights.clear(); - saved.highlights.add(new Highlight("banned", 0x112233, null)); - saved.highlights.add(new Highlight("kicked", null, 0xABCDEF)); - saved.excludes.add("ping timeout"); - Properties p = new Properties(); - saved.store(p); - - ServerLogSettings loaded = new ServerLogSettings(); - loaded.load(p); - assertEquals(Set.of(Level.CRITICAL, Level.ERROR, Level.WARNING), loaded.levels); - assertTrue(loaded.localTime); - assertEquals(saved.highlights, loaded.highlights); - assertEquals(List.of("ping timeout"), loaded.excludes); - } - - @Test - void shorterListsLeaveNoStaleEntriesBehind() { - ServerLogSettings s = new ServerLogSettings(); - s.excludes.addAll(List.of("a", "b", "c")); - Properties p = new Properties(); - s.store(p); - s.excludes.clear(); - s.highlights.clear(); - s.store(p); - - assertTrue(p.stringPropertyNames().stream().noneMatch(k -> k.startsWith("serverLog.exclude."))); - assertTrue(p.stringPropertyNames().stream().noneMatch(k -> k.startsWith("serverLog.highlight."))); - ServerLogSettings loaded = new ServerLogSettings(); - loaded.load(p); - assertTrue(loaded.excludes.isEmpty()); - assertTrue(loaded.highlights.isEmpty()); - } - - @Test - void levelsAndExcludesDecideWhatShows() { - ServerLogSettings s = new ServerLogSettings(); - s.levels.remove(Level.INFO); - s.excludes.add("Ping Timeout"); - assertFalse(s.shows(Level.INFO, "client connected")); - assertTrue(s.shows(Level.WARNING, "something odd")); - assertFalse(s.shows(Level.WARNING, "dropping client because of ping timeout")); - assertTrue(s.shows(Level.DEBUG, "levels the window has no box for always show")); - } - - @Test - void theFirstMatchingKeywordWins() { - ServerLogSettings s = new ServerLogSettings(); - s.highlights.clear(); - s.highlights.add(new Highlight("error", 1, null)); - s.highlights.add(new Highlight("client", 2, null)); - assertEquals(1, s.highlightFor("ERROR client gone").foreground()); - assertEquals(2, s.highlightFor("client joined").foreground()); - assertNull(s.highlightFor("nothing here")); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/config/SettingsTest.java b/ts3-client/core/src/test/java/com/ts3client/config/SettingsTest.java deleted file mode 100644 index 03d38ee..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/config/SettingsTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.ts3client.config; - -import com.ts3client.audio.InputLevel; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import java.nio.file.Files; -import java.nio.file.Path; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; - -class SettingsTest { - - @TempDir - Path dir; - - @BeforeEach - void freshProfile() { - AppDirs.init(dir.toFile(), dir.resolve("chats")); - } - - @AfterEach - void defaultProfile() { - AppDirs.init(null, null); - } - - @Test - void whatIsSavedLoadsBack() { - Settings saved = new Settings(); - saved.nickname = "Žofia"; - saved.inputMode = Settings.InputMode.PUSH_TO_TALK; - saved.vadMode = Settings.VadMode.AUTOMATIC; - saved.vadThresholdDb = -33.5; - saved.appearance = Settings.Appearance.DARK; - saved.whisperPolicy = Settings.WhisperPolicy.NOBODY; - saved.chatLogs = false; - saved.chatLogDir = "/somewhere/else"; - saved.save(); - - Settings loaded = Settings.load(); - assertEquals("Žofia", loaded.nickname); - assertEquals(Settings.InputMode.PUSH_TO_TALK, loaded.inputMode); - assertEquals(Settings.VadMode.AUTOMATIC, loaded.vadMode); - assertEquals(-33.5, loaded.vadThresholdDb); - assertEquals(Settings.Appearance.DARK, loaded.appearance); - assertEquals(Settings.WhisperPolicy.NOBODY, loaded.whisperPolicy); - assertFalse(loaded.chatLogs); - assertEquals("/somewhere/else", loaded.chatLogDir); - } - - @Test - void unknownValuesFallBackToDefaults() throws Exception { - Files.writeString(dir.resolve("settings.properties"), "inputMode=TELEPATHY\nvadMode=\n"); - Settings loaded = Settings.load(); - assertEquals(new Settings().inputMode, loaded.inputMode); - assertEquals(new Settings().vadMode, loaded.vadMode); - } - - @Test - void anOldDbfsThresholdIsConvertedOnce() throws Exception { - Files.writeString(dir.resolve("settings.properties"), "vadThresholdDb=-40.0\n"); - Settings loaded = Settings.load(); - double expected = InputLevel.powerToDb(Math.pow(10.0, -40.0 / 10.0)); - assertEquals(expected, loaded.vadThresholdDb, 1e-9); - - loaded.save(); - String saved = Files.readString(dir.resolve("settings.properties")); - assertFalse(saved.contains("vadThresholdDb"), "the old key is dropped once converted"); - assertEquals(expected, Settings.load().vadThresholdDb, 1e-9); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/contacts/ContactStoreTest.java b/ts3-client/core/src/test/java/com/ts3client/contacts/ContactStoreTest.java deleted file mode 100644 index 11cb0fb..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/contacts/ContactStoreTest.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.ts3client.contacts; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import java.io.File; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.time.LocalDateTime; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class ContactStoreTest { - - @TempDir - File dir; - - @Test - void addsWithTheTypeDefaultsAndPersistsInTeamSpeakRecords() throws Exception { - File file = new File(dir, "contacts.txt"); - ContactStore store = new ContactStore(file); - ContactDefaults defaults = new ContactDefaults(); - defaults.of(ContactType.BLOCKED).ignorePokes = true; - defaults.of(ContactType.BLOCKED).ignoreWhisper = true; - defaults.of(ContactType.BLOCKED).nicknameDisplay = NicknameDisplay.ONLY_NICKNAME; - - AtomicInteger changes = new AtomicInteger(); - store.addListener(changes::incrementAndGet); - Contact bob = store.add("bob=", "Bob", ContactType.BLOCKED, defaults); - assertTrue(bob.ignorePokes); - assertTrue(!bob.whisperAllowed); - assertEquals(NicknameDisplay.ONLY_NICKNAME, bob.nicknameDisplay); - assertEquals("Bob2", store.displayName("bob=", "Bob2")); - bob.nicknameDisplay = NicknameDisplay.BOTH; - assertEquals("Bob (Bob2)", store.displayName("bob=", "Bob2")); - assertEquals(1, changes.get()); - - // Adding again only re-types; the edited flags stay. - bob.ignorePrivateMessages = true; - store.put(bob); - Contact again = store.add("bob=", "Other", ContactType.FRIEND, defaults); - assertTrue(again.ignorePrivateMessages); - assertEquals(ContactType.FRIEND, again.type); - assertEquals(ContactType.FRIEND, store.typeOf("bob=")); - assertNull(store.typeOf("nobody")); - - String text = Files.readString(file.toPath(), StandardCharsets.UTF_8); - assertTrue(text.startsWith("IDS=bob=\nNickname=Bob\nFriend=0\n"), text); - - ContactStore reloaded = new ContactStore(file); - reloaded.readFile(); - Contact back = reloaded.find("bob="); - assertNotNull(back); - assertTrue(back.ignorePrivateMessages); - assertEquals(ContactType.FRIEND, back.type); - } - - @Test - void markSeenRecordsOnceAMinute() { - ContactStore store = new ContactStore(new File(dir, "c.txt")); - store.add("a=", "A", ContactType.NEUTRAL, new ContactDefaults()); - AtomicInteger changes = new AtomicInteger(); - store.addListener(changes::incrementAndGet); - - store.markSeen("a=", "Server", "host:9987"); - store.markSeen("a=", "Server", "host:9987"); - store.markSeen("missing", "Server", "host:9987"); - assertEquals(1, changes.get()); - Contact a = store.find("a="); - assertEquals("Server", a.lastSeenServerName); - assertTrue(a.lastSeen.isAfter(LocalDateTime.now().minusMinutes(1))); - - store.markSeen("a=", "Other", "other:9987"); - assertEquals(2, changes.get()); - assertEquals("other:9987", a.lastSeenServerAddress); - } - - @Test - void sightingsWaitForTheNextSave() throws Exception { - File file = new File(dir, "s.txt"); - ContactStore store = new ContactStore(file); - store.add("a=", "A", ContactType.NEUTRAL, new ContactDefaults()); - long written = file.lastModified(); - String before = Files.readString(file.toPath(), StandardCharsets.UTF_8); - - store.markSeen("a=", "Server", "host:9987"); - assertEquals(before, Files.readString(file.toPath(), StandardCharsets.UTF_8)); - store.flush(); - assertTrue(Files.readString(file.toPath(), StandardCharsets.UTF_8).contains("LastSeenServerAddress=host:9987")); - - // An edit's save takes a waiting sighting along; the flush then has nothing left to write. - store.markSeen("a=", "Other", "other:9987"); - store.put(store.find("a=")); - assertTrue(Files.readString(file.toPath(), StandardCharsets.UTF_8).contains("LastSeenServerAddress=other:9987")); - assertTrue(file.setLastModified(written)); - store.flush(); - assertEquals(written, file.lastModified()); - } - - @Test - void mergeAddsNewAndOverwritesExisting() { - ContactStore store = new ContactStore(new File(dir, "m.txt")); - store.add("a=", "A", ContactType.NEUTRAL, new ContactDefaults()); - Contact importedA = new Contact("a="); - importedA.nickname = "A imported"; - importedA.type = ContactType.FRIEND; - Contact importedB = new Contact("b="); - importedB.nickname = "B"; - assertEquals(1, store.merge(List.of(importedA, importedB))); - assertEquals(2, store.all().size()); - assertEquals("A imported", store.find("a=").nickname); - assertEquals(ContactType.FRIEND, store.find("a=").type); - store.remove("a="); - assertEquals(1, store.all().size()); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/contacts/ContactTest.java b/ts3-client/core/src/test/java/com/ts3client/contacts/ContactTest.java deleted file mode 100644 index 2f3dc35..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/contacts/ContactTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.ts3client.contacts; - -import org.junit.jupiter.api.Test; - -import java.time.LocalDateTime; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class ContactTest { - - @Test - void recordRoundTripsInTeamSpeakFormat() { - Contact c = new Contact("AbCdEfGh1234567890abcdefghijk="); - c.nickname = "Alice"; - c.type = ContactType.FRIEND; - c.automute = true; - c.ignorePokes = true; - c.nicknameDisplay = NicknameDisplay.ONLY_CUSTOM; - c.hasVolumeModifier = true; - c.volumeModifier = -6; - c.whisperAllowed = false; - c.phoneticNickname = "Ah-lees"; - c.lastSeen = LocalDateTime.of(2024, 3, 1, 18, 33, 34); - c.lastSeenServerName = "Test Server"; - c.lastSeenServerAddress = "server.lixko.eu:9987"; - - String record = c.toRecord(); - assertTrue(record.startsWith("IDS=AbCdEfGh1234567890abcdefghijk=\nNickname=Alice\nFriend=0\nAutomute=1\n")); - assertTrue(record.contains("\nVolumeModifier=-6\n")); - assertTrue(record.contains("\nWhisperAllow=0\n")); - assertTrue(record.contains("\nLastSeen=2024-03-01T18:33:34\n")); - - Contact parsed = Contact.parseRecord(record); - assertEquals(c.uniqueId, parsed.uniqueId); - assertEquals("Alice", parsed.nickname); - assertEquals(ContactType.FRIEND, parsed.type); - assertTrue(parsed.automute); - assertTrue(parsed.ignorePokes); - assertFalse(parsed.ignorePublicMessages); - assertEquals(NicknameDisplay.ONLY_CUSTOM, parsed.nicknameDisplay); - assertTrue(parsed.hasVolumeModifier); - assertEquals(-6.0, parsed.volumeModifier); - assertFalse(parsed.whisperAllowed); - assertEquals("Ah-lees", parsed.phoneticNickname); - assertEquals(c.lastSeen, parsed.lastSeen); - assertEquals("server.lixko.eu:9987", parsed.lastSeenServerAddress); - assertEquals(record, parsed.toRecord()); - } - - @Test - void missingFieldsFallBackToTeamSpeakDefaults() { - Contact c = Contact.parseRecord("IDS=abc=\nNickname=X\nFriend=1\n"); - assertEquals(ContactType.BLOCKED, c.type); - assertTrue(c.whisperAllowed); - assertEquals(NicknameDisplay.BOTH, c.nicknameDisplay); - assertNull(c.lastSeen); - assertNull(Contact.parseRecord("Nickname=nobody\n")); - } - - @Test - void displayNameFollowsTheShowType() { - Contact c = new Contact("u"); - c.nickname = "Custom"; - assertEquals("Custom (Live)", c.displayName("Live")); - assertEquals("Live", c.displayName("Live") == null ? null : NicknameDisplay.ONLY_NICKNAME.render("Custom", "Live")); - c.nicknameDisplay = NicknameDisplay.ONLY_CUSTOM; - assertEquals("Custom", c.displayName("Live")); - c.nickname = ""; - assertEquals("Live", c.displayName("Live")); - } - - @Test - void volumeModifierIsDecibels() { - Contact c = new Contact("u"); - assertEquals(1.0, c.volumeGain()); - c.hasVolumeModifier = true; - c.volumeModifier = -6; - assertEquals(0.501, c.volumeGain(), 0.001); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/gfx/CountryFlagsTest.java b/ts3-client/core/src/test/java/com/ts3client/gfx/CountryFlagsTest.java deleted file mode 100644 index d00ddc4..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/gfx/CountryFlagsTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.ts3client.gfx; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -class CountryFlagsTest { - - @Test - void namesCountriesInEnglishAndLeavesOddCodesAsTheyAre() { - assertEquals("Slovakia", CountryFlags.name("SK")); - assertEquals("Germany", CountryFlags.name("de")); - assertEquals("not a code", CountryFlags.name("not a code")); - } - - @Test - void hasNoFlagForNoCountry() { - assertNull(CountryFlags.png("")); - assertNull(CountryFlags.png(null)); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/gfx/IconPackTest.java b/ts3-client/core/src/test/java/com/ts3client/gfx/IconPackTest.java deleted file mode 100644 index 815148f..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/gfx/IconPackTest.java +++ /dev/null @@ -1,160 +0,0 @@ -package com.ts3client.gfx; - -import com.ts3client.net.ClientStatus; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import java.io.File; -import java.io.OutputStream; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Map; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class IconPackTest { - - private static final String INI = """ - [info] - name = Test Icons - - [options] - FALLBACK = false - - [gfxfiles] - # a comment - CONNECT = connect.svg - DISCONNECT = Disconnect.SVG - CHANNEL_GREEN= channel_green.png - MISSING = not_shipped.svg - EMPTY = - """; - - private static File zip(Path dir, String name, Map entries) throws Exception { - File file = dir.resolve(name).toFile(); - try (OutputStream out = Files.newOutputStream(file.toPath()); - ZipOutputStream zip = new ZipOutputStream(out)) { - for (Map.Entry e : entries.entrySet()) { - zip.putNextEntry(new ZipEntry(e.getKey())); - zip.write(e.getValue().getBytes(StandardCharsets.UTF_8)); - zip.closeEntry(); - } - } - return file; - } - - @Test - void readsTheMappingOfAModernPack(@TempDir Path dir) throws Exception { - IconPack pack = IconPack.load(zip(dir, "test_pack.zip", Map.of( - "settings.ini", INI, - "connect.svg", "", - "disconnect.svg", "disconnect", - "channel_green.png", "png bytes", - "emoticons/smile.svg", ""))); - assertNotNull(pack); - - assertEquals("test_pack.zip", pack.id()); - assertEquals("Test Icons", pack.name()); - assertFalse(pack.fallsBack()); - - assertArrayEquals("".getBytes(StandardCharsets.UTF_8), pack.icon("CONNECT", 16)); - assertTrue(pack.isVector("CONNECT", 16)); - assertFalse(pack.isVector("CHANNEL_GREEN", 16)); - // Keys are case-insensitive, as are the file names pack authors write. - assertArrayEquals("disconnect".getBytes(StandardCharsets.UTF_8), - pack.icon("disconnect", 16)); - - assertNull(pack.icon("MISSING", 16), "mapped to a file the pack does not ship"); - assertNull(pack.icon("EMPTY", 16)); - assertNull(pack.icon("NOT_IN_THE_PACK", 16)); - } - - @Test - void fallsBackByDefault(@TempDir Path dir) throws Exception { - IconPack pack = IconPack.load(zip(dir, "p.zip", Map.of( - "settings.ini", "[gfxfiles]\nCONNECT = connect.svg\n", - "connect.svg", ""))); - assertNotNull(pack); - assertTrue(pack.fallsBack()); - } - - @Test - void resolvesLegacyPacksByFileName(@TempDir Path dir) throws Exception { - IconPack pack = IconPack.load(zip(dir, "default.zip", Map.of( - "16x16_connect.png", "small", - "32x32_connect.png", "large", - "24x24_upload_avatar.png", "avatar", - "group_100.png", "group", - "emoticons/smile.png", "ignored"))); - assertNotNull(pack); - assertEquals("Default", pack.name()); - - // The smallest image that still covers the requested size wins. - assertArrayEquals("small".getBytes(StandardCharsets.UTF_8), pack.icon("CONNECT", 16)); - assertArrayEquals("large".getBytes(StandardCharsets.UTF_8), pack.icon("CONNECT", 32)); - assertArrayEquals("large".getBytes(StandardCharsets.UTF_8), pack.icon("CONNECT", 64)); - - assertArrayEquals("avatar".getBytes(StandardCharsets.UTF_8), pack.icon("UPLOAD_AVATAR", 16)); - assertArrayEquals("group".getBytes(StandardCharsets.UTF_8), pack.icon("GROUP_100", 16)); - assertFalse(pack.has("SMILE"), "emoticons are not icons of the user interface"); - } - - @Test - void readsUnpackedDirectories(@TempDir Path dir) throws Exception { - Path unpacked = Files.createDirectory(dir.resolve("my_icons")); - Files.writeString(unpacked.resolve("settings.ini"), "[gfxfiles]\nCONNECT = connect.svg\n"); - Files.writeString(unpacked.resolve("connect.svg"), ""); - - IconPack pack = IconPack.load(unpacked.toFile()); - assertNotNull(pack); - assertEquals("My Icons", pack.name()); - assertArrayEquals("".getBytes(StandardCharsets.UTF_8), pack.icon("CONNECT", 16)); - } - - @Test - void ignoresWhatIsNotAPack(@TempDir Path dir) throws Exception { - assertNull(IconPack.load(dir.resolve("nope.zip").toFile())); - assertNull(IconPack.load(Files.createDirectory(dir.resolve("empty")).toFile())); - assertNull(IconPack.load(null)); - } - - @Test - void shipsAMaterialPackForEveryIconTheTreeDraws() { - IconPack pack = IconPacks.material(); - assertNotNull(pack); - assertEquals("Material", pack.name()); - assertFalse(pack.fallsBack()); - assertNull(pack.source()); - for (ClientStatus status : ClientStatus.values()) { - String key = IconKeys.client(status); - assertTrue(pack.isVector(key, 16), key); - assertNotNull(pack.icon(key, 16), key); - } - for (boolean password : new boolean[]{false, true}) { - for (boolean full : new boolean[]{false, true}) { - for (boolean subscribed : new boolean[]{false, true}) { - for (String key : IconKeys.channel(password, full, subscribed)) { - assertNotNull(pack.icon(key, 16), key); - } - } - } - } - } - - @Test - void setsTheColourVectorArtPaintsWith() { - byte[] svg = "".getBytes(StandardCharsets.UTF_8); - assertEquals("", - new String(IconPack.withCurrentColor(svg, 0xFF0A0B0C), StandardCharsets.UTF_8)); - byte[] fixed = "".getBytes(StandardCharsets.UTF_8); - assertTrue(fixed == IconPack.withCurrentColor(fixed, 0)); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/hotkey/HotkeyEngineTest.java b/ts3-client/core/src/test/java/com/ts3client/hotkey/HotkeyEngineTest.java deleted file mode 100644 index 68c9908..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/hotkey/HotkeyEngineTest.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.ts3client.hotkey; - -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class HotkeyEngineTest { - - private static final HotkeyKey CTRL = HotkeyKey.keyboard(37); - private static final HotkeyKey K = HotkeyKey.keyboard(45); - private static final HotkeyKey MOUSE4 = HotkeyKey.mouse(8); - - private final List fired = new ArrayList<>(); - private final Hotkeys hotkeys = new Hotkeys(); - private final HotkeyEngine engine = new HotkeyEngine(hotkeys, - (hotkey, active) -> fired.add(hotkey.action + (active ? ":on" : ":off"))); - - private Hotkey bind(HotkeyAction action, Hotkey.Trigger trigger, HotkeyKey... keys) { - Hotkey h = new Hotkey(action, new HotkeyCombo(List.of(keys))); - h.trigger = trigger; - hotkeys.add(h); - return h; - } - - @Test - void firesOnKeyDownOnlyWhenEveryKeyIsHeld() { - bind(HotkeyAction.MIC_TOGGLE, Hotkey.Trigger.KEY_DOWN, CTRL, K); - - engine.onInput(K, true); - assertTrue(fired.isEmpty(), "one key of the combination is not enough"); - engine.onInput(CTRL, true); - assertEquals(List.of("MIC_TOGGLE:on"), fired); - - // Releasing and re-pressing arms it again, but only once per completion. - engine.onInput(CTRL, false); - engine.onInput(CTRL, true); - assertEquals(List.of("MIC_TOGGLE:on", "MIC_TOGGLE:on"), fired); - } - - @Test - void keyUpTriggerFiresOnRelease() { - bind(HotkeyAction.SPEAKER_TOGGLE, Hotkey.Trigger.KEY_UP, MOUSE4); - - engine.onInput(MOUSE4, true); - assertTrue(fired.isEmpty()); - engine.onInput(MOUSE4, false); - assertEquals(List.of("SPEAKER_TOGGLE:on"), fired); - } - - @Test - void momentaryActionReportsPressAndRelease() { - bind(HotkeyAction.PTT_ACTIVATE, Hotkey.Trigger.KEY_UP, MOUSE4); - - engine.onInput(MOUSE4, true); - engine.onInput(MOUSE4, false); - // The trigger setting does not apply: push-to-talk always spans the hold. - assertEquals(List.of("PTT_ACTIVATE:on", "PTT_ACTIVATE:off"), fired); - } - - @Test - void disabledAndUnsupportedBindingsStaySilent() { - bind(HotkeyAction.MIC_TOGGLE, Hotkey.Trigger.KEY_DOWN, K).enabled = false; - bind(HotkeyAction.RECORDING_START, Hotkey.Trigger.KEY_DOWN, MOUSE4); - - engine.onInput(K, true); - engine.onInput(MOUSE4, true); - assertTrue(fired.isEmpty()); - } - - @Test - void recordingCapturesTheCombinationInsteadOfFiring() { - bind(HotkeyAction.MIC_TOGGLE, Hotkey.Trigger.KEY_DOWN, K); - List recorded = new ArrayList<>(); - engine.record(new HotkeyEngine.Recorder() { - @Override - public void onRecording(HotkeyCombo combo) { - } - - @Override - public void onRecorded(HotkeyCombo combo) { - recorded.add(combo); - } - }); - - engine.onInput(CTRL, true); - engine.onInput(K, true); - engine.onInput(K, false); - engine.onInput(CTRL, false); - - assertTrue(fired.isEmpty(), "bindings must not fire while recording"); - assertEquals(1, recorded.size()); - assertEquals(List.of(CTRL, K), recorded.get(0).keys()); - } - - @Test - void actionsCarryTeamSpeaksTreeGrouping() { - assertEquals("Sounds", HotkeyAction.SOUNDPACK_ACTIVATE.group()); - assertEquals("Microphone", HotkeyAction.MIC_TOGGLE.group()); - // TS3 leaves a handful of actions ungrouped, listed straight under their category. - assertEquals("", HotkeyAction.NICKNAME_CHANGE.group()); - assertEquals("", HotkeyAction.BRING_TO_FRONT.group()); - - Hotkey pack = new Hotkey(HotkeyAction.SOUNDPACK_ACTIVATE, new HotkeyCombo(List.of(K))); - pack.argument = "Default Sound Pack (Male)"; - assertEquals("Sounds / Activate Soundpack / Default Sound Pack (Male)", pack.path()); - assertEquals("Bring Client to Front", - new Hotkey(HotkeyAction.BRING_TO_FRONT, new HotkeyCombo(List.of(K))).path()); - } - - @Test - void combinationsSurviveARoundTripThroughText() { - HotkeyCombo combo = new HotkeyCombo(List.of(CTRL, MOUSE4)); - assertEquals("Keyboard:37+Mouse:8", combo.toString()); - assertEquals(combo, HotkeyCombo.parse(combo.toString())); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/myts/AccountInfoTest.java b/ts3-client/core/src/test/java/com/ts3client/myts/AccountInfoTest.java deleted file mode 100644 index 6f27728..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/myts/AccountInfoTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.ts3client.myts; - -import org.junit.jupiter.api.Test; - -import java.nio.charset.StandardCharsets; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -class AccountInfoTest { - - private static String base32(String text) { - return AccountInfo.base32(text.getBytes(StandardCharsets.US_ASCII)); - } - - @Test - void encodesRfc4648VectorsLowercaseAndUnpadded() { - assertEquals("", base32("")); - assertEquals("my", base32("f")); - assertEquals("mzxq", base32("fo")); - assertEquals("mzxw6", base32("foo")); - assertEquals("mzxw6yq", base32("foob")); - assertEquals("mzxw6ytb", base32("fooba")); - assertEquals("mzxw6ytboi", base32("foobar")); - } - - @Test - void toleratesAReplyWithoutIdentityData() { - AccountInfo info = AccountInfo.of("tester", "u", null, 0); - assertEquals("", info.userId()); - assertNull(info.created()); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/myts/ChatAttachmentTest.java b/ts3-client/core/src/test/java/com/ts3client/myts/ChatAttachmentTest.java deleted file mode 100644 index f862e9b..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/myts/ChatAttachmentTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.ts3client.myts; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class ChatAttachmentTest { - - /** As TeamSpeak 6 sends it: JSON.stringify of its object, keys in this order. */ - private static final String TS6_MESSAGE = "{\"msg_type\":\"ts.file.myts\",\"file_id\":\"YWx1aW1hZWJp\"," - + "\"chat_user_id\":\"@agl7x5qxz7h7pqrfz7xyzedmlkbpstkbbkxw7gxltefsa3p7eexri===:chat-1.tmspk.net\"," - + "\"file_name\":\"cat picture.PNG\",\"file_size\":532,\"body\":\"cat picture.PNG\",\"v2\":true}"; - - @Test - void readsTheMessageTeamSpeak6Sends() { - ChatAttachment a = ChatAttachment.parse(TS6_MESSAGE); - assertEquals("YWx1aW1hZWJp", a.fileId()); - assertEquals("agl7x5qxz7h7pqrfz7xyzedmlkbpstkbbkxw7gxltefsa3p7eexri===", a.senderUserId()); - assertEquals("cat picture.PNG", a.fileName()); - assertEquals(532, a.fileSize()); - assertTrue(a.isImage()); - assertEquals("", a.caption()); - } - - @Test - void writesWhatItReads() { - assertEquals(TS6_MESSAGE, ChatAttachment.parse(TS6_MESSAGE).toMessage()); - } - - @Test - void namesItsSenderAsTeamSpeak6Does() { - ChatAttachment a = ChatAttachment.of("id", "aeqlaxceldn5xjqkgnzdd3bjsxety4k46mzr7v5sd4xwtpyv5yfm2", "a.txt", 3); - assertEquals("@aeqlaxceldn5xjqkgnzdd3bjsxety4k46mzr7v5sd4xwtpyv5yfm2===:chat-1.tmspk.net", a.senderChatId()); - assertFalse(a.isImage()); - ChatAttachment back = ChatAttachment.parse(a.toMessage()); - assertEquals(a, back); - } - - @Test - void keepsQuotesAndBracketsInNames() { - ChatAttachment a = new ChatAttachment("f", "@u:h", "say \"hi\" [b]x[/b].gif", 1, "line\nbreak"); - assertEquals(a, ChatAttachment.parse(a.toMessage())); - assertEquals("line\nbreak", a.caption()); - } - - @Test - void ignoresOtherMessages() { - assertNull(ChatAttachment.parse("hello")); - assertNull(ChatAttachment.parse("{\"msg_type\":\"ts.file.myts\"}")); - assertNull(ChatAttachment.parse("{\"msg_type\":\"other\",\"file_id\":\"a\",\"chat_user_id\":\"@b:c\"} ts.file.myts")); - assertNull(ChatAttachment.parse("{\"msg_type\":\"ts.file.myts\", broken")); - } - - @Test - void hrefNamesEverythingNeededToFetchIt() { - ChatAttachment a = ChatAttachment.parse(TS6_MESSAGE); - String href = a.href("+Tyg2JtxE8vRNZp/JiUBnmBh0MY="); - assertTrue(ChatAttachment.isHref(href)); - ChatAttachment.Ref ref = ChatAttachment.Ref.parse(href); - assertEquals("+Tyg2JtxE8vRNZp/JiUBnmBh0MY=", ref.room()); - assertEquals(a.senderUserId(), ref.owner()); - assertEquals("YWx1aW1hZWJp", ref.fileId()); - assertEquals("cat picture.PNG", ref.fileName()); - assertFalse(href.contains(" ")); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/myts/MyTeamSpeakLoginTest.java b/ts3-client/core/src/test/java/com/ts3client/myts/MyTeamSpeakLoginTest.java deleted file mode 100644 index a42dfed..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/myts/MyTeamSpeakLoginTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.ts3client.myts; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import java.io.File; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class MyTeamSpeakLoginTest { - - @Test - void staysSignedInWithoutKeepingThePassword(@TempDir File dir) throws Exception { - File file = new File(dir, "myteamspeak.properties"); - MyTeamSpeakTest.ReplayServer server = new MyTeamSpeakTest.ReplayServer(); - MyTeamSpeakLogin login = new MyTeamSpeakLogin(file, new MyTeamSpeak(server)); - assertFalse(login.isSignedIn()); - - login.signIn(MyTsCryptoTest.EMAIL, MyTsCryptoTest.PASSWORD); - assertTrue(login.isSignedIn()); - assertEquals("tester", login.username()); - assertFalse(Files.readString(file.toPath(), StandardCharsets.ISO_8859_1).contains(MyTsCryptoTest.PASSWORD)); - - MyTeamSpeakLogin restarted = new MyTeamSpeakLogin(file, new MyTeamSpeak(server)); - assertTrue(restarted.isSignedIn()); - assertEquals(MyTsCryptoTest.EMAIL, restarted.email()); - assertEquals("tester", restarted.username()); - assertEquals(1, restarted.fetch().bookmarks()); - - restarted.signOut(); - assertFalse(file.exists()); - assertFalse(restarted.isSignedIn()); - } - - @Test - void aFailedSignInKeepsNothing(@TempDir File dir) { - File file = new File(dir, "myteamspeak.properties"); - MyTeamSpeakTest.ReplayServer server = new MyTeamSpeakTest.ReplayServer(); - server.loginError = MyTsException.LOGIN_FAILED; - MyTeamSpeakLogin login = new MyTeamSpeakLogin(file, new MyTeamSpeak(server)); - - assertThrows(MyTsException.class, () -> login.signIn(MyTsCryptoTest.EMAIL, "wrong")); - assertFalse(login.isSignedIn()); - assertFalse(file.exists()); - } - - @Test - void signsOutWhenThePasswordChangedElsewhere(@TempDir File dir) throws Exception { - File file = new File(dir, "myteamspeak.properties"); - MyTeamSpeakTest.ReplayServer server = new MyTeamSpeakTest.ReplayServer(); - MyTeamSpeakLogin login = new MyTeamSpeakLogin(file, new MyTeamSpeak(server)); - login.signIn(MyTsCryptoTest.EMAIL, MyTsCryptoTest.PASSWORD); - - server.loginError = MyTsException.LOGIN_FAILED; - MyTsException e = assertThrows(MyTsException.class, login::fetch); - assertTrue(e.credentialsRejected()); - assertFalse(login.isSignedIn()); - assertFalse(file.exists()); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/myts/MyTeamSpeakTest.java b/ts3-client/core/src/test/java/com/ts3client/myts/MyTeamSpeakTest.java deleted file mode 100644 index 93ba3a1..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/myts/MyTeamSpeakTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.ts3client.myts; - -import com.ts3client.proto.ProtobufReader; -import com.ts3client.proto.ProtobufWriter; -import com.ts3client.teamspeak.SyncItem; -import org.junit.jupiter.api.Test; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertInstanceOf; -import static org.junit.jupiter.api.Assertions.assertThrows; - -class MyTeamSpeakTest { - - private static final String SESSION = "00000000-1111-2222-3333-444444444444"; - - static MyTeamSpeak.Credentials credentials(String password) throws MyTsException { - return MyTeamSpeak.Credentials.derive(MyTsCryptoTest.EMAIL, password); - } - - /** Replays the captured account: answers each call and records it. */ - static final class ReplayServer implements MyTsTransport { - final List calls = new ArrayList<>(); - int loginError = 200; - String loginToken; - - @Override - public byte[] call(String endpoint, String method, byte[] request) throws IOException { - calls.add(endpoint + "/" + method); - return switch (method) { - case "login" -> login(request); - case "requestServerItems" -> items(request); - default -> new byte[0]; - }; - } - - private byte[] login(byte[] request) throws IOException { - ProtobufReader r = new ProtobufReader(request); - while (r.next()) { - if (r.fieldNumber() == 2) loginToken = r.readString(); - else r.skip(); - } - if (loginError != 200) return new ProtobufWriter().varint(5, loginError).toByteArray(); - return new ProtobufWriter() - .bytes(1, MyTsCryptoTest.KEY_PACKAGE) - .string(2, SESSION) - .varint(5, 200) - .string(4, "828613f7-3cde-45e6-993e-c57ee979a39f") - .string(8, "tester") - .message(9, new ProtobufWriter().varint(3, 1_770_000_000L) - .bytes(4, java.util.HexFormat.of().parseHex( - "0120b05c4b1a2d3e4f5061728394a5b6c7d8e9f00112233445566778899aabbccd"))) - .toByteArray(); - } - - private byte[] items(byte[] request) throws IOException { - ProtobufReader r = new ProtobufReader(request); - while (r.next()) { - if (r.fieldNumber() == 1) assertEquals(SESSION, r.readString()); - else r.skip(); - } - try { - ProtobufWriter bookmark = new ProtobufWriter() - .string(1, "43c5d058-4803-3cd8-b844-15fdcc92e730") - .string(2, "5d831e3c-d5aa-0e66-7af2-a0feb13af048") - .bytes(3, MyTsCryptoTest.itemFrame()); - ProtobufWriter tombstone = new ProtobufWriter().string(1, "gone").varint(4, 1); - // Sent though not asked for, and in the clear. - ProtobufWriter addOn = new ProtobufWriter() - .string(1, "38aa56e2-55ae-b37a-a7db-7a11832a9812") - .bytes(3, new ProtobufWriter().string(2, "38aa56e2-55ae-b37a-a7db-7a11832a9812") - .varint(6, 4).toByteArray()); - return new ProtobufWriter() - .varint(1, 301) - .message(2, new ProtobufWriter().varint(1, 0).string(2, "v").message(3, bookmark).message(3, tombstone)) - .message(2, new ProtobufWriter().varint(1, 1).varint(4, 1)) - .message(2, new ProtobufWriter().varint(1, 4).string(2, "v").message(3, addOn)) - .string(3, "g") - .toByteArray(); - } catch (java.security.GeneralSecurityException e) { - throw new AssertionError(e); - } - } - } - - @Test - void downloadsAndDecryptsTheAccount() throws Exception { - ReplayServer server = new ReplayServer(); - MyTeamSpeak.Account account = new MyTeamSpeak(server).download(credentials(MyTsCryptoTest.PASSWORD)); - - assertEquals("tester", account.username()); - assertEquals("828613f7-3cde-45e6-993e-c57ee979a39f", account.info().uuid()); - assertEquals(java.time.Instant.ofEpochSecond(1_770_000_000L), account.info().created()); - assertEquals("aeqlaxcldiwt4t2qmfzihfffw3d5r2pqaejcgncfkztxrcm2vo6m2", account.info().userId()); - assertEquals(1, account.items().size()); - SyncItem.Bookmark bookmark = assertInstanceOf(SyncItem.Bookmark.class, account.items().get(0)); - assertEquals("server.lixko.eu", bookmark.address()); - assertEquals(9987, bookmark.port()); - assertEquals("niger", bookmark.nickname()); - assertEquals(MyTsCryptoTest.LOGIN_TOKEN, server.loginToken); - assertEquals(List.of("authentication/login", "synchronization/requestServerItems", - "authentication/deleteSession"), server.calls); - } - - @Test - void reportsAWrongPassword() { - ReplayServer server = new ReplayServer(); - server.loginError = 202; - MyTsException e = assertThrows(MyTsException.class, - () -> new MyTeamSpeak(server).download(credentials("wrong"))); - assertEquals(202, e.code()); - assertEquals(List.of("authentication/login"), server.calls); - } - - @Test - void signsOutWhenTheKeyDoesNotOpen() { - // The server accepted the login token but the key does not open with this password. - ReplayServer server = new ReplayServer(); - assertThrows(MyTsException.class, () -> new MyTeamSpeak(server).download(credentials("other"))); - assertEquals("authentication/deleteSession", server.calls.get(server.calls.size() - 1)); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/myts/MyTsCryptoTest.java b/ts3-client/core/src/test/java/com/ts3client/myts/MyTsCryptoTest.java deleted file mode 100644 index 16d97e8..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/myts/MyTsCryptoTest.java +++ /dev/null @@ -1,117 +0,0 @@ -package com.ts3client.myts; - -import org.junit.jupiter.api.Test; - -import javax.crypto.Cipher; -import javax.crypto.spec.GCMParameterSpec; -import javax.crypto.spec.SecretKeySpec; -import java.security.GeneralSecurityException; -import java.security.MessageDigest; -import java.util.Arrays; -import java.util.HexFormat; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -/** - * Vectors from the official client (see CRYPTO_RE_SALT.md). The sign-in sample is a login the client - * computed for an address with no account; the item is a real captured one with its item key. - */ -class MyTsCryptoTest { - - static final String EMAIL = "probe.nobody@example.com"; - static final String PASSWORD = "wrongpassword1"; - static final String LOGIN_TOKEN = "kJLau9cQuYPQi/hi0ey4dPBChwvTMhz2lfAYHWQnNNtaVffCzHHac8mIFVb2FpN4"; - static final byte[] ITEM_KEY = hex("22efa5d631ddaa11ec97ccb82846b4d24598a9376319f444b5065cd47b391b2d"); - - /** {@code LoginSession.key} sealing {@link #ITEM_KEY} for {@link #EMAIL}, laid out as the server sends it. */ - static final byte[] KEY_PACKAGE = keyPackage(); - - /** A bookmark: server.lixko.eu:9987, nickname "niger". */ - static final byte[] ITEM_DATA = hex("122434336335643035382d343830332d336364382d623834342d3135666463633932653733301a24" - + "64373663663736312d316163332d373434662d366234312d36363633386362643165303320003000" - + "3a00420048f7f5dbd506820189010a19457269c48d516f76205465616d537065616b207365727665" - + "72120f7365727665722e6c69786b6f2e657518834e22056e696765722a00320744656661756c743a" - + "0042004a0050005a0744656661756c74620744656661756c746a0070007a1c2b547967324a747845" - + "3876524e5a702b4a6955426e6d4268304d593d8a0100900100980100b00101"); - - /** The capture cut the frame 37 bytes into its SHA-512 trailer, so the test completes it. */ - static byte[] itemFrame() throws GeneralSecurityException { - byte[] captured = hex("1114428e2059c038f339b1c1a6bc4eb0eac1f4479ec2764ea53c0b4dd0fc4626" - + "4642cab8908d295933fac43152154f58990909e933d899b86d4776ae8c52f61575b33932d4667fc3f" - + "b50e78a2a056dc6c8cd74e3e2446275e0d351c7139bc686a3555b4dd3dd6fdfae1c7176e84f99b3" - + "0df52dbe9b95e28d9545e2dd3188fec7e34ac233fb7de6d21db8795a45186ff91a01d23189d072d6" - + "afb60cad9b1c834e35acf04006daa1d6e439750afaa00a4c63e53f10cf54d2820108c1b859b394d0" - + "ba7d80b38de402b631da9ba4daedbff4d9de85cdeae7466b516ac5abe9af4d43e9df1c9bf8951d1" - + "2e9f5c42ce7cf802443d4bc051902164ec510126130dd962e54778518ae0a44947e6dd19975eef8b" - + "33ce8"); - byte[] hash = MessageDigest.getInstance("SHA-512").digest(ITEM_DATA); - byte[] frame = Arrays.copyOf(captured, 16 + ITEM_DATA.length + hash.length); - System.arraycopy(hash, 0, frame, 16 + ITEM_DATA.length, hash.length); - return frame; - } - - @Test - void derivesTheOfficialLoginToken() throws GeneralSecurityException { - assertEquals(LOGIN_TOKEN, MyTsCrypto.loginToken(EMAIL, PASSWORD)); - } - - @Test - void emailCaseDoesNotMatter() throws GeneralSecurityException { - assertEquals(LOGIN_TOKEN, MyTsCrypto.loginToken("Probe.Nobody@EXAMPLE.com", PASSWORD)); - } - - /** The same construction opened a real account's key; this pins it for the sample address. */ - @Test - void derivesTheAccountKey() throws GeneralSecurityException { - assertArrayEquals(hex("f0e2ba6d60d69c8eb6bb9e56f0093490db7379b3f4df5475599ddad2a750d00d"), - MyTsCrypto.accountKey(EMAIL, PASSWORD)); - } - - @Test - void unwrapsTheItemKey() throws GeneralSecurityException { - assertArrayEquals(ITEM_KEY, MyTsCrypto.unwrapItemKey(MyTsCrypto.accountKey(EMAIL, PASSWORD), KEY_PACKAGE)); - } - - @Test - void wrongPasswordCannotUnwrap() throws GeneralSecurityException { - byte[] accountKey = MyTsCrypto.accountKey(EMAIL, "not the password"); - assertThrows(GeneralSecurityException.class, () -> MyTsCrypto.unwrapItemKey(accountKey, KEY_PACKAGE)); - } - - @Test - void decryptsAnItem() throws GeneralSecurityException { - assertArrayEquals(ITEM_DATA, MyTsCrypto.decryptItem(itemFrame(), ITEM_KEY)); - } - - @Test - void rejectsATamperedItem() throws GeneralSecurityException { - byte[] frame = itemFrame(); - frame[40] ^= 1; - assertThrows(GeneralSecurityException.class, () -> MyTsCrypto.decryptItem(frame, ITEM_KEY)); - } - - /** {@code 02 || tag || iv || ciphertext}; JCA puts the tag last, the server first. */ - private static byte[] keyPackage() { - try { - byte[] iv = hex("0102030405060708090a0b0c"); - Cipher gcm = Cipher.getInstance("AES/GCM/NoPadding"); - gcm.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(MyTsCrypto.accountKey(EMAIL, PASSWORD), "AES"), - new GCMParameterSpec(128, iv)); - byte[] sealed = gcm.doFinal(ITEM_KEY); - byte[] out = new byte[1 + 16 + 12 + 32]; - out[0] = 2; - System.arraycopy(sealed, 32, out, 1, 16); - System.arraycopy(iv, 0, out, 17, 12); - System.arraycopy(sealed, 0, out, 29, 32); - return out; - } catch (GeneralSecurityException e) { - throw new AssertionError(e); - } - } - - static byte[] hex(String s) { - return HexFormat.of().parseHex(s); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/myts/MyTsFilesTest.java b/ts3-client/core/src/test/java/com/ts3client/myts/MyTsFilesTest.java deleted file mode 100644 index b81d9ee..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/myts/MyTsFilesTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.ts3client.myts; - -import com.ts3client.proto.ProtobufReader; -import com.ts3client.proto.ProtobufWriter; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -class MyTsFilesTest { - - /** The account replay, plus the file service: hands out made-up addresses. */ - static final class FileServer implements MyTsTransport { - final MyTeamSpeakTest.ReplayServer accounts = new MyTeamSpeakTest.ReplayServer(); - final List requests = new ArrayList<>(); - int expireNext; - - @Override - public byte[] call(String endpoint, String method, byte[] request) throws IOException, MyTsException { - if (!endpoint.equals("user")) return accounts.call(endpoint, method, request); - accounts.calls.add(endpoint + "/" + method); - if (expireNext > 0) { - expireNext--; - return new ProtobufWriter().varint(2, 109).toByteArray(); - } - ProtobufReader r = new ProtobufReader(request); - StringBuilder fields = new StringBuilder(method); - while (r.next()) fields.append(' ').append(r.fieldNumber()).append('=').append(r.readString()); - requests.add(fields.toString()); - return new ProtobufWriter().varint(1, 1).string(5, "file1").string(6, "https://store/" + method) - .toByteArray(); - } - } - - private static MyTsFiles signedIn(File dir, FileServer server) throws Exception { - MyTeamSpeakLogin login = new MyTeamSpeakLogin(new File(dir, "myts.properties"), new MyTeamSpeak(server)); - login.signIn(MyTsCryptoTest.EMAIL, MyTsCryptoTest.PASSWORD); - server.accounts.calls.clear(); - return new MyTsFiles(login, new MyTeamSpeak(server)); - } - - @Test - void asksUnderTheAccountsIdAndKeepsTheSession(@TempDir File dir) throws Exception { - FileServer server = new FileServer(); - MyTsFiles files = signedIn(dir, server); - - MyTsFiles.Upload upload = files.requestUpload("room="); - assertEquals("file1", upload.fileId()); - assertEquals("aeqlaxcldiwt4t2qmfzihfffw3d5r2pqaejcgncfkztxrcm2vo6m2===", upload.senderUserId()); - assertEquals("https://store/requestDownloadFile", files.requestDownload("owner", "room=", "file9")); - - String session = "00000000-1111-2222-3333-444444444444"; - assertEquals(List.of("requestUploadFile 1=" + session + " 2=" + upload.senderUserId() + " 3=room=", - "requestDownloadFile 1=" + session + " 2=owner 3=room= 4=file9"), server.requests); - assertEquals(List.of("authentication/login", "user/requestUploadFile", "user/requestDownloadFile"), - server.accounts.calls); - - files.close(); - assertEquals("authentication/deleteSession", server.accounts.calls.get(3)); - } - - @Test - void signsInAgainWhenTheSessionRanOut(@TempDir File dir) throws Exception { - FileServer server = new FileServer(); - MyTsFiles files = signedIn(dir, server); - files.requestUpload("room"); - server.expireNext = 1; - server.accounts.calls.clear(); - - files.requestUpload("room"); - assertEquals(List.of("user/requestUploadFile", "authentication/login", "user/requestUploadFile"), - server.accounts.calls); - } - - @Test - void needsASignIn(@TempDir File dir) { - FileServer server = new FileServer(); - MyTeamSpeakLogin login = new MyTeamSpeakLogin(new File(dir, "myts.properties"), new MyTeamSpeak(server)); - MyTsFiles files = new MyTsFiles(login, new MyTeamSpeak(server)); - assertThrows(MyTsException.class, () -> files.requestUpload("room")); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/net/ConnectionEventHandlerTest.java b/ts3-client/core/src/test/java/com/ts3client/net/ConnectionEventHandlerTest.java deleted file mode 100644 index 9201b60..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/net/ConnectionEventHandlerTest.java +++ /dev/null @@ -1,211 +0,0 @@ -package com.ts3client.net; - -import com.github.manevolent.ts3j.command.MultiCommand; -import com.github.manevolent.ts3j.event.ChannelCreateEvent; -import com.github.manevolent.ts3j.event.ChannelDeletedEvent; -import com.github.manevolent.ts3j.event.ChannelEditedEvent; -import com.github.manevolent.ts3j.event.ChannelMovedEvent; -import com.github.manevolent.ts3j.event.ClientJoinEvent; -import com.github.manevolent.ts3j.event.ClientLeaveEvent; -import com.github.manevolent.ts3j.event.ClientMovedEvent; -import com.github.manevolent.ts3j.event.ClientUpdatedEvent; -import com.github.manevolent.ts3j.event.ServerGroupClientAddedEvent; -import com.github.manevolent.ts3j.event.ServerGroupClientDeletedEvent; -import com.github.manevolent.ts3j.protocol.ProtocolRole; -import com.ts3client.config.Settings; -import com.ts3client.contacts.ContactStore; -import com.ts3client.sound.SoundNotifier; -import org.junit.jupiter.api.Test; - -import java.util.List; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** Feeds the handler events as the server words them and checks what the model makes of them. */ -class ConnectionEventHandlerTest { - - private int modelChanges; - private int unreadReports; - private final Settings settings = new Settings(); - private final TeamspeakConnection conn = new TeamspeakConnection(settings, null, new ConnectionListener() { - @Override - public void onStatus(String status) { - } - - @Override - public void onConnected() { - } - - @Override - public void onDisconnected(String reason) { - } - - @Override - public void onModelChanged() { - modelChanges++; - } - - @Override - public void onInfoUpdated() { - } - - @Override - public void onIconsUpdated() { - } - - @Override - public void onChat(ChatScope scope, int fromClientId, String fromUniqueId, String fromName, String message) { - } - - @Override - public void onTalkStateChanged(int clientId, boolean talking) { - } - - @Override - public void onError(String message) { - } - - @Override - public void onPoke(String fromName, String message) { - } - - @Override - public void onServerLog(String message) { - } - - @Override - public void onUnreadMessagesChanged(int unread) { - unreadReports++; - } - }, new SoundNotifier(settings), ContactStore.load()); - private final ConnectionEventHandler events = new ConnectionEventHandler(conn); - private final ServerModel model = conn.getModel(); - - /** The fields of an event, parsed from the command text the server sends. */ - private static Map fields(String command) { - return MultiCommand.parse(ProtocolRole.SERVER, command).simplifyOne().toMap(); - } - - private void join(int clid, String nickname, int channel) { - events.onClientJoin(new ClientJoinEvent(fields("notifycliententerview cfid=0 ctid=" + channel - + " reasonid=0 clid=" + clid + " client_unique_identifier=uid" + clid + "==" - + " client_nickname=" + nickname + " client_input_muted=0 client_output_muted=0" - + " client_input_hardware=1 client_output_hardware=1 client_database_id=" + (100 + clid) - + " client_channel_group_id=8 client_servergroups=6,7 client_away=0 client_away_message" - + " client_type=0 client_flag_avatar=abc client_talk_power=25"))); - } - - @Test - void aJoiningClientEntersTheModelWithWhatItReported() { - model.putChannel(1, "Lobby", 0, 0); - join(5, "alice", 1); - - ClientEntry alice = model.getClient(5); - assertEquals("alice", alice.nickname); - assertEquals(1, alice.channelId); - assertEquals(105, alice.databaseId); - assertEquals(25, alice.talkPower); - assertArrayEquals(new int[]{6, 7}, alice.serverGroupIds); - assertEquals("abc", alice.avatarFlag); - assertEquals(1, modelChanges); - } - - @Test - void movesAndLeaves() { - model.putChannel(1, "Lobby", 0, 0); - model.putChannel(2, "Games", 0, 1); - join(5, "alice", 1); - - events.onClientMoved(new ClientMovedEvent(fields("notifyclientmoved ctid=2 reasonid=0 clid=5"))); - assertEquals(2, model.getClient(5).channelId); - - events.onClientLeave(new ClientLeaveEvent(fields( - "notifyclientleftview cfid=2 ctid=0 reasonid=8 reasonmsg=bye clid=5"))); - assertNull(model.getClient(5)); - } - - @Test - void aPartialUpdateLeavesTheOtherFieldsAlone() { - model.putChannel(1, "Lobby", 0, 0); - join(5, "alice", 1); - - events.onClientChanged(new ClientUpdatedEvent(fields("notifyclientupdated clid=5 client_input_muted=1"))); - - ClientEntry alice = model.getClient(5); - assertTrue(alice.inputMuted); - assertEquals("alice", alice.nickname); - assertEquals("abc", alice.avatarFlag); - } - - @Test - void tracksAClientsUnreadOfflineMessages() { - model.putChannel(1, "Lobby", 0, 0); - join(5, "alice", 1); - assertEquals(0, model.getClient(5).unreadMessages); - - events.onClientChanged(new ClientUpdatedEvent(fields("notifyclientupdated clid=5 client_unread_messages=3"))); - assertEquals(3, model.getClient(5).unreadMessages); - assertEquals(0, unreadReports, "only our own count is reported"); - } - - @Test - void clearedFieldsAreCleared() { - model.putChannel(1, "Lobby", 0, 0); - join(5, "alice", 1); - events.onClientChanged(new ClientUpdatedEvent(fields( - "notifyclientupdated clid=5 client_away=1 client_away_message=lunch"))); - assertEquals("lunch", model.getClient(5).awayMessage); - - events.onClientChanged(new ClientUpdatedEvent(fields( - "notifyclientupdated clid=5 client_away_message client_flag_avatar"))); - - ClientEntry alice = model.getClient(5); - assertTrue(alice.away); - assertEquals("", alice.awayMessage); - assertEquals("", alice.avatarFlag); - } - - @Test - void serverGroupsComeAndGo() { - model.putChannel(1, "Lobby", 0, 0); - join(5, "alice", 1); - - events.onServerGroupClientAdded(new ServerGroupClientAddedEvent(fields( - "notifyservergroupclientadded name=Admin sgid=9 cldbid=105 clid=5"))); - assertTrue(model.getClient(5).inServerGroup(9)); - - events.onServerGroupClientDeleted(new ServerGroupClientDeletedEvent(fields( - "notifyservergroupclientdeleted name=Guest sgid=6 cldbid=105 clid=5"))); - assertArrayEquals(new int[]{7, 9}, model.getClient(5).serverGroupIds); - } - - @Test - void channelsAreCreatedEditedMovedAndDeleted() { - model.putChannel(1, "Lobby", 0, 0); - events.onChannelCreate(new ChannelCreateEvent(fields( - "notifychannelcreated cid=2 cpid=0 channel_name=Games channel_order=1" - + " channel_flag_password=1 channel_maxclients=5 channel_flag_maxclients_unlimited=0"))); - ChannelNode games = model.getChannel(2); - assertTrue(games.hasPassword); - assertEquals(5, games.maxClients); - assertEquals(List.of("Lobby", "Games"), model.buildTree().stream().map(c -> c.name).toList()); - - events.onChannelEdit(new ChannelEditedEvent(fields( - "notifychanneledited cid=2 reasonid=10 invokerid=3 invokername=bob invokeruid=bobuid=" - + " channel_flag_password=0 channel_topic"))); - assertFalse(games.hasPassword); - assertEquals("", games.topic); - - events.onChannelMoved(new ChannelMovedEvent(fields("notifychannelmoved cid=2 cpid=1 order=0 reasonid=1"))); - assertEquals(1, games.parentId); - assertEquals(List.of("Games"), model.buildTree().get(0).children.stream().map(c -> c.name).toList()); - - events.onChannelDeleted(new ChannelDeletedEvent(fields("notifychanneldeleted cid=2"))); - assertNull(model.getChannel(2)); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/net/DetailsTest.java b/ts3-client/core/src/test/java/com/ts3client/net/DetailsTest.java deleted file mode 100644 index 90a8e5d..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/net/DetailsTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.ts3client.net; - -import org.junit.jupiter.api.Test; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class DetailsTest { - - @Test - void serverTakesInitserverAndEditsAndBareKeys() { - ServerModel model = new ServerModel(); - model.setServerName("Test"); - Map init = new HashMap<>(); - init.put("virtualserver_version", "3.13.7"); - init.put("virtualserver_platform", "Linux"); - init.put("virtualserver_maxclients", "32"); - init.put("virtualserver_welcomemessage", "Hello"); - // An empty property comes as a bare key. - init.put("virtualserver_hostmessage", null); - model.putServerProperties(init); - model.putServerProperties(Map.of("virtualserver_hostmessage", "Be nice", "invokerid", "5")); - - Details d = Details.server(model, "host:9987"); - assertEquals("Test", d.title()); - assertEquals(new Details.Field("Version", "3.13.7 on Linux"), d.fields().get(1)); - assertEquals(new Details.Field("Clients", "0 / 32"), d.fields().get(2)); - assertEquals("Hello\n\nBe nice", d.description()); - assertEquals("", model.serverProperty("invokerid")); - } - - @Test - void channelDescriptionIsPendingUntilAnswered() { - ChannelNode ch = new ChannelNode(1, "Lobby"); - ch.topic = "Entry"; - assertTrue(Details.channel(ch).pending()); - ch.descriptionLoaded = true; - Details d = Details.channel(ch); - assertFalse(d.pending()); - assertEquals(List.of(new Details.Field("Topic", "Entry")), d.fields()); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/net/EventFieldsTest.java b/ts3-client/core/src/test/java/com/ts3client/net/EventFieldsTest.java deleted file mode 100644 index 1439128..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/net/EventFieldsTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.ts3client.net; - -import com.github.manevolent.ts3j.command.MultiCommand; -import com.github.manevolent.ts3j.event.ClientUpdatedEvent; -import com.github.manevolent.ts3j.protocol.ProtocolRole; -import org.junit.jupiter.api.Test; - -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Pins the ts3j behaviour {@code ConnectionEventHandler.has(...)} exists for: a field - * the event never carried reads back as an empty string, so a null check would treat - * every partial update (someone muting, say) as if it reported every other field too. - */ -class EventFieldsTest { - - @Test - void missingFieldsReadBackAsEmptyStringsRatherThanNull() { - ClientUpdatedEvent e = new ClientUpdatedEvent(Map.of("clid", "7", "client_input_muted", "1")); - assertNotNull(e.get("client_is_recording")); - assertEquals("", e.get("client_is_recording")); - assertEquals("", e.get("client_nickname")); - } - - /** What {@code reported(...)} relies on: a cleared field still arrives, just without a value. */ - @Test - void clearedFieldsAreStillInTheMap() { - Map fields = MultiCommand.parse(ProtocolRole.SERVER, - "notifyclientupdated clid=7 client_flag_avatar client_description=").simplifyOne().toMap(); - ClientUpdatedEvent e = new ClientUpdatedEvent(fields); - assertTrue(e.getMap().containsKey("client_flag_avatar")); - assertTrue(e.getMap().containsKey("client_description")); - assertFalse(e.getMap().containsKey("client_away_message")); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/net/ServerLogEntryTest.java b/ts3-client/core/src/test/java/com/ts3client/net/ServerLogEntryTest.java deleted file mode 100644 index 0630a4d..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/net/ServerLogEntryTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.ts3client.net; - -import com.ts3client.net.ServerLogEntry.Level; -import org.junit.jupiter.api.Test; - -import java.time.LocalDateTime; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -class ServerLogEntryTest { - - @Test - void readsTheServersLineFormat() { - ServerLogEntry e = ServerLogEntry.parse("2026-10-04 13:11:01.038554|WARNING |VirtualServer |1 |" - + "client 'a|b'(id:19) was added to servergroup 'Server Admin'(id:6)"); - assertEquals(LocalDateTime.of(2026, 10, 4, 13, 11, 1, 38_554_000), e.timestamp()); - assertEquals(Level.WARNING, e.level()); - assertEquals("VirtualServer", e.channel()); - assertEquals("client 'a|b'(id:19) was added to servergroup 'Server Admin'(id:6)", e.message()); - } - - @Test - void keepsTheRestOfALineWithACutOffTimestamp() { - ServerLogEntry e = ServerLogEntry.parse("6-10-01 23:26:51.007742|INFO |VirtualServerBase|1 |listening on 0.0.0.0:9990"); - assertNull(e.timestamp()); - assertEquals(Level.INFO, e.level()); - assertEquals("VirtualServerBase", e.channel()); - assertEquals("listening on 0.0.0.0:9990", e.message()); - } - - @Test - void keepsAnUnreadableLineWhole() { - ServerLogEntry e = ServerLogEntry.parse("2026-10-04 00:23:41.975519|INFO "); - assertNull(e.timestamp()); - assertEquals(Level.INFO, e.level()); - assertEquals("2026-10-04 00:23:41.975519|INFO ", e.message()); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/net/ServerModelRulesTest.java b/ts3-client/core/src/test/java/com/ts3client/net/ServerModelRulesTest.java deleted file mode 100644 index 428bc64..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/net/ServerModelRulesTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.ts3client.net; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class ServerModelRulesTest { - - private final ServerModel model = new ServerModel(); - - private void grant(String permission, int value) { - model.putPermissionName(permission); - model.putSelfPermissionValue(permissionId(permission), value); - } - - private int permissionId(String name) { - for (int id = 0; ; id++) { - if (name.equals(model.permissionName(id))) return id; - } - } - - private static Group group(int addPower, int removePower) { - return new Group(9, "Group", 0, 0, 1, addPower, removePower); - } - - @Test - void groupNeedsEnoughAddPowerAndRemovePowerToTakeAway() { - grant("i_group_member_add_power", 50); - grant("i_group_member_remove_power", 20); - - assertTrue(model.canToggleGroup(group(50, 0), false)); - assertFalse(model.canToggleGroup(group(51, 0), false)); - assertTrue(model.canToggleGroup(group(50, 20), true)); - assertFalse(model.canToggleGroup(group(50, 21), true)); - } - - @Test - void unlimitedPowerIsMinusOneOnEitherSide() { - grant("i_group_member_add_power", 75); - grant("i_group_member_remove_power", -1); - - assertFalse(model.canToggleGroup(group(-1, 0), false), "a group needing unlimited power"); - assertTrue(model.canToggleGroup(group(75, 1000), true), "unlimited remove power"); - } - - @Test - void joiningNeedsAVisibleChannelWithRoom() { - ChannelNode channel = model.putChannel(1, "Full", 0, 0); - model.putClient(5, "Someone", 1); - assertFalse(model.canJoinChannel(1), "not subscribed"); - - channel.subscribed = true; - assertTrue(model.canJoinChannel(1)); - channel.maxClients = 1; - assertFalse(model.canJoinChannel(1), "full"); - assertFalse(model.canJoinChannel(2), "unknown"); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/net/ServerModelTreeTest.java b/ts3-client/core/src/test/java/com/ts3client/net/ServerModelTreeTest.java deleted file mode 100644 index bd3c5a4..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/net/ServerModelTreeTest.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.ts3client.net; - -import org.junit.jupiter.api.Test; - -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; - -/** The channel tree: TS3 orders siblings as a chain of "sits below" links, not by a key. */ -class ServerModelTreeTest { - - private final ServerModel model = new ServerModel(); - - private static List names(List channels) { - return channels.stream().map(c -> c.name).toList(); - } - - @Test - void ordersSiblingsByTheirChainWhateverOrderTheyArrivedIn() { - model.putChannel(3, "C", 0, 2); - model.putChannel(1, "A", 0, 0); - model.putChannel(2, "B", 0, 1); - assertEquals(List.of("A", "B", "C"), names(model.buildTree())); - } - - @Test - void keepsChannelsWhoseLinksAreBroken() { - model.putChannel(1, "A", 0, 0); - model.putChannel(2, "B", 0, 1); - model.putChannel(3, "C", 0, 1); // claims the same place as B - model.putChannel(4, "D", 0, 99); // sits below a channel that does not exist - List tree = names(model.buildTree()); - assertEquals(4, tree.size()); - assertEquals(List.of("A", "B"), tree.subList(0, 2)); - } - - @Test - void nestsChannelsAndPutsOrphansAtTheTop() { - model.putChannel(1, "Lobby", 0, 0); - model.putChannel(2, "Games", 1, 0); - model.putChannel(3, "Lost", 42, 0); - List roots = model.buildTree(); - assertEquals(List.of("Lobby", "Lost"), names(roots).stream().sorted().toList()); - assertEquals(List.of("Games"), names(model.getChannel(1).children)); - } - - @Test - void aRemovedChannelsFollowerMovesUp() { - model.putChannel(1, "A", 0, 0); - model.putChannel(2, "B", 0, 1); - model.putChannel(3, "C", 0, 2); - model.removeChannel(2); - assertEquals(List.of("A", "C"), names(model.buildTree())); - } - - @Test - void reorderingRepairsTheLinksTheServerDoesNotResend() { - model.putChannel(1, "A", 0, 0); - model.putChannel(2, "B", 0, 1); - model.putChannel(3, "C", 0, 2); - model.relinkChannel(3, 0, 0); // C to the top - assertEquals(List.of("C", "A", "B"), names(model.buildTree())); - model.relinkChannel(3, 0, 2); // and back below B - assertEquals(List.of("A", "B", "C"), names(model.buildTree())); - } - - @Test - void movingUnderAnotherParentClosesTheGap() { - model.putChannel(1, "A", 0, 0); - model.putChannel(2, "B", 0, 1); - model.putChannel(3, "C", 0, 2); - model.relinkChannel(2, 1, 0); - assertEquals(List.of("A", "C"), names(model.buildTree())); - assertEquals(List.of("B"), names(model.getChannel(1).children)); - } - - @Test - void listsClientsByTalkPowerThenNameAndHidesQueryClients() { - model.putChannel(1, "Lobby", 0, 0); - model.putClient(10, "zed", 1); - model.putClient(11, "Amy", 1); - model.putClient(12, "bob", 1).talkPower = 50; - model.putClient(13, "serveradmin", 1).type = 1; - model.buildTree(); - assertEquals(List.of("bob", "Amy", "zed"), - model.getChannel(1).clients.stream().map(c -> c.nickname).toList()); - } - - @Test - void findsChannelsByPathIdOrPlainName() { - model.putChannel(1, "Lobby", 0, 0); - ChannelNode games = model.putChannel(2, "Games", 1, 0); - assertEquals("Lobby/Games", model.channelPath(2)); - assertSame(games, model.findChannelByPath("/lobby/games/")); - assertSame(games, model.findChannelByPath("/2")); - assertSame(games, model.findChannelByPath("Games"), "a moved channel is still found by name"); - assertNull(model.findChannelByPath("Lobby/Music")); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/net/avatar/AvatarNamingTest.java b/ts3-client/core/src/test/java/com/ts3client/net/avatar/AvatarNamingTest.java deleted file mode 100644 index 650d168..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/net/avatar/AvatarNamingTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.ts3client.net.avatar; - -import org.junit.jupiter.api.Test; - -import java.nio.charset.StandardCharsets; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class AvatarNamingTest { - - @Test - void fileNameEncodesDecodedUidNibbleWise() { - // base64 of 0x00 0x01 ... 0x13 - String uid = "AAECAwQFBgcICQoLDA0ODxAREhM="; - assertEquals("avatar_aaabacadaeafagahaiajakalamanaoapbabbbcbd", AvatarNaming.fileName(uid)); - assertEquals("avatar_" + "p".repeat(40), - AvatarNaming.fileName("//////////////////////////8=")); - } - - @Test - void fileNameRejectsMalformedIds() { - assertNull(AvatarNaming.fileName("")); - assertNull(AvatarNaming.fileName("not base64!")); - assertNull(AvatarNaming.fileName("AAEC")); // decodes, but not to 20 bytes - assertNull(AvatarNaming.fileName(null)); - } - - @Test - void flagIsLowercaseMd5() { - assertEquals("9e107d9d372bb6826bd81d3542a419d6", - AvatarNaming.flag("The quick brown fox jumps over the lazy dog".getBytes(StandardCharsets.US_ASCII))); - assertTrue(AvatarNaming.isFlag("9e107d9d372bb6826bd81d3542a419d6")); - assertFalse(AvatarNaming.isFlag("")); - assertFalse(AvatarNaming.isFlag("zz107d9d372bb6826bd81d3542a419d6")); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/net/avatar/AvatarRepositoryTest.java b/ts3-client/core/src/test/java/com/ts3client/net/avatar/AvatarRepositoryTest.java deleted file mode 100644 index 73dd09e..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/net/avatar/AvatarRepositoryTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.ts3client.net.avatar; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import java.io.File; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class AvatarRepositoryTest { - - private static final byte[] GIF = "GIF89a-not-really-an-image".getBytes(); - private static final String UID = "AAECAwQFBgcICQoLDA0ODxAREhM="; - - @TempDir - File cache; - - @Test - void downloadsOnceThenServesFromMemoryAndDisk() throws Exception { - AtomicInteger fetches = new AtomicInteger(); - CountDownLatch loaded = new CountDownLatch(1); - AvatarRepository repo = new AvatarRepository(uid -> { - fetches.incrementAndGet(); - return GIF; - }, loaded::countDown, cache); - String flag = AvatarNaming.flag(GIF); - - assertNull(repo.get(UID, flag)); - assertTrue(loaded.await(5, TimeUnit.SECONDS)); - Avatar avatar = repo.get(UID, flag); - assertNotNull(avatar); - assertEquals(ImageFormat.GIF, avatar.format()); - assertTrue(avatar.isAnimated()); - assertEquals(new File(cache, flag + ".gif"), avatar.file()); - assertEquals(1, fetches.get()); - - // A fresh repository over the same directory needs no download. - AvatarRepository again = new AvatarRepository(uid -> { - throw new AssertionError("should not fetch"); - }, null, cache); - assertNotNull(again.get(UID, flag)); - } - - @Test - void rejectsFilesWhoseMd5DoesNotMatchTheFlag() throws Exception { - AtomicInteger fetches = new AtomicInteger(); - AvatarRepository repo = new AvatarRepository(uid -> { - fetches.incrementAndGet(); - return GIF; - }, null, cache); - String wrongFlag = "0123456789abcdef0123456789abcdef"; - - assertNull(repo.get(UID, wrongFlag)); - Thread.sleep(300); - assertNull(repo.get(UID, wrongFlag)); - Thread.sleep(300); - assertEquals(1, fetches.get(), "a mismatch is not retried"); - assertEquals(0, cache.list().length); - } - - @Test - void ignoresClientsWithoutAnAvatar() { - AvatarRepository repo = new AvatarRepository(uid -> { - throw new AssertionError("should not fetch"); - }, null, cache); - assertNull(repo.get(UID, "")); - assertNull(repo.get(UID, null)); - } - - @Test - void putMakesAnUploadedAvatarAvailableImmediately() { - AvatarRepository repo = new AvatarRepository(uid -> null, null, cache); - Avatar avatar = repo.put(GIF); - assertEquals(AvatarNaming.flag(GIF), avatar.flag()); - assertEquals(avatar, repo.get(UID, avatar.flag())); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/net/avatar/ImageFormatTest.java b/ts3-client/core/src/test/java/com/ts3client/net/avatar/ImageFormatTest.java deleted file mode 100644 index a809b62..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/net/avatar/ImageFormatTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.ts3client.net.avatar; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -class ImageFormatTest { - - @Test - void detectsByMagicBytes() { - assertEquals(ImageFormat.PNG, ImageFormat.detect(new byte[]{(byte) 0x89, 'P', 'N', 'G', 13, 10, 26, 10})); - assertEquals(ImageFormat.JPEG, ImageFormat.detect(new byte[]{(byte) 0xFF, (byte) 0xD8, (byte) 0xFF, (byte) 0xE0, 0, 16})); - assertEquals(ImageFormat.GIF, ImageFormat.detect("GIF89a".getBytes())); - assertEquals(ImageFormat.BMP, ImageFormat.detect("BM\0\0\0\0".getBytes())); - assertNull(ImageFormat.detect("".getBytes())); - assertNull(ImageFormat.detect(new byte[3])); - assertNull(ImageFormat.detect(null)); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/net/ban/BanPatternTest.java b/ts3-client/core/src/test/java/com/ts3client/net/ban/BanPatternTest.java deleted file mode 100644 index 34ea737..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/net/ban/BanPatternTest.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.ts3client.net.ban; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class BanPatternTest { - - @Test - void wildcardIpv4TurnsStarsIntoAddressGroups() { - assertEquals("192\\.168\\.[0-9]+\\.[0-9]+", BanPattern.WILDCARD_IPV4.ipToRegex("192.168.*.*")); - assertEquals("2001:db8:[0-9a-fA-F]+:[0-9a-fA-F]+", BanPattern.WILDCARD_IPV6.ipToRegex("2001:db8:*:*")); - } - - @Test - void wildcardNamesMatchAnything() { - assertEquals("Troll.*", BanPattern.WILDCARD_IPV4.nameToRegex("Troll*")); - assertEquals("\\[Bot\\].*", BanPattern.WILDCARD_IPV6.nameToRegex("[Bot]*")); - } - - @Test - void fixedStringsAreTakenLiterally() { - assertEquals("10\\.0\\.0\\.1", BanPattern.FIXED_STRING.ipToRegex("10.0.0.1")); - assertEquals("a\\*b\\?\\(c\\)\\$\\^\\|\\\\", BanPattern.FIXED_STRING.nameToRegex("a*b?(c)$^|\\")); - } - - @Test - void regularExpressionsPassThrough() { - assertEquals("^Troll[0-9]{2}$", BanPattern.REGULAR_EXPRESSION.nameToRegex("^Troll[0-9]{2}$")); - } - - @Test - void decodeRecoversTheNotationThatProducedTheExpression() { - BanPattern.Decoded d = BanPattern.decode("192\\.168\\.[0-9]+\\.[0-9]+", "Troll.*"); - assertEquals(BanPattern.WILDCARD_IPV4, d.pattern); - assertEquals("192.168.*.*", d.ip); - assertEquals("Troll*", d.name); - - d = BanPattern.decode("fe80:[0-9a-fA-F]+", ""); - assertEquals(BanPattern.WILDCARD_IPV6, d.pattern); - assertEquals("fe80:*", d.ip); - - d = BanPattern.decode("", "a\\*b"); - assertEquals(BanPattern.FIXED_STRING, d.pattern); - assertEquals("a*b", d.name); - - d = BanPattern.decode("", "^Troll[0-9]{2}$"); - assertEquals(BanPattern.REGULAR_EXPRESSION, d.pattern); - assertEquals("^Troll[0-9]{2}$", d.name); - } - - @Test - void plainAddressesDecodeAsWildcardsLikeTheDialogDefault() { - BanPattern.Decoded d = BanPattern.decode("10\\.0\\.0\\.1", ""); - assertEquals(BanPattern.WILDCARD_IPV4, d.pattern); - assertEquals("10.0.0.1", d.ip); - } - - @Test - void validityFollowsJavaRegexSyntax() { - assertTrue(BanPattern.isValidRegex("")); - assertTrue(BanPattern.isValidRegex("^a.*$")); - assertFalse(BanPattern.isValidRegex("(unclosed")); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/net/ban/BanUnitTest.java b/ts3-client/core/src/test/java/com/ts3client/net/ban/BanUnitTest.java deleted file mode 100644 index 006661c..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/net/ban/BanUnitTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.ts3client.net.ban; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -class BanUnitTest { - - @Test - void lengthsShowInTheLargestUnitThatDividesThem() { - assertEquals(BanUnit.DAYS, BanUnit.largestFor(2 * 86400)); - assertEquals(BanUnit.HOURS, BanUnit.largestFor(90 * 60 * 2)); - assertEquals(BanUnit.MINUTES, BanUnit.largestFor(120)); - assertEquals(BanUnit.SECONDS, BanUnit.largestFor(61)); - assertEquals(2, BanUnit.DAYS.amountOf(2 * 86400)); - } - - @Test - void noLengthIsPermanent() { - assertEquals(BanUnit.PERMANENT, BanUnit.largestFor(0)); - assertEquals(BanUnit.PERMANENT, BanUnit.largestFor(-1)); - assertEquals(0, BanUnit.PERMANENT.toSeconds(30)); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/session/ServerLinkTest.java b/ts3-client/core/src/test/java/com/ts3client/session/ServerLinkTest.java deleted file mode 100644 index 0868cdd..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/session/ServerLinkTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.ts3client.session; - -import com.ts3client.config.Bookmark; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -class ServerLinkTest { - - @Test - void readsEveryParameter() { - ServerLink link = ServerLink.parse("ts3server://ts.example.com?port=9988&nickname=Bob%20B" - + "&password=s+cret&channel=Lobby/Games&channelpassword=pw&token=abc&addbookmark=Example"); - assertEquals("ts.example.com", link.address); - assertEquals(9988, link.port); - assertEquals("Bob B", link.nickname); - assertEquals("s+cret", link.password); - assertEquals("Lobby/Games", link.channel); - assertEquals("pw", link.channelPassword); - assertEquals("abc", link.token); - assertEquals("Example", link.bookmarkLabel); - } - - @Test - void aBareHostTakesTheDefaults() { - ServerLink link = ServerLink.parse("TS3SERVER://ts.example.com/"); - assertEquals("ts.example.com", link.address); - assertEquals(9987, link.port); - assertEquals("", link.channel); - assertEquals("", link.token); - } - - @Test - void readsThePortFromTheAuthority() { - assertEquals(1234, ServerLink.parse("ts3server://1.2.3.4:1234").port); - ServerLink v6 = ServerLink.parse("ts3server://[2001:db8::1]:5000?nickname=x"); - assertEquals("2001:db8::1", v6.address); - assertEquals(5000, v6.port); - } - - @Test - void aChannelIdWinsOverThePath() { - assertEquals("/42", ServerLink.parse("ts3server://h?channel=Old%20name&cid=42").channel); - assertEquals("Lobby", ServerLink.parse("ts3server://h?cid=0&channel=Lobby").channel); - } - - @Test - void namesNoServerWithoutAHost() { - assertNull(ServerLink.parse("ts3server://?port=1")); - assertNull(ServerLink.parse("https://example.com")); - } - - @Test - void bookmarksUnderTheAskedName() { - Bookmark b = ServerLink.parse("ts3server://h?addbookmark=Mine&cid=3&channelpassword=x").toBookmark(); - assertEquals("Mine", b.label); - assertEquals("/3", b.channel); - assertEquals("x", b.channelPassword); - assertEquals("h", ServerLink.parse("ts3server://h").toBookmark().label); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/sound/NotificationSettingsTest.java b/ts3-client/core/src/test/java/com/ts3client/sound/NotificationSettingsTest.java deleted file mode 100644 index 0ce3e73..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/sound/NotificationSettingsTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.ts3client.sound; - -import org.junit.jupiter.api.Test; - -import java.util.Properties; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class NotificationSettingsTest { - - @Test - void defaultsFollowTheEventCatalogue() { - NotificationSettings s = new NotificationSettings(); - assertTrue(s.isImportant(SoundEvent.OTHER_RECEIVED_POKE)); - assertFalse(s.isImportant(SoundEvent.YOU_SWITCHED_CHANNEL)); - assertTrue(s.isEnabled(SoundEvent.YOU_SWITCHED_CHANNEL)); - assertFalse(s.isEnabled(SoundEvent.SPECIAL_MIC_CLICK_SELF_ON)); - } - - @Test - void onlyDeviationsArePersisted() { - NotificationSettings s = new NotificationSettings(); - s.setImportant(SoundEvent.YOU_SWITCHED_CHANNEL, true); - s.setEnabled(SoundEvent.CHAT_RECEIVED_MESSAGE_CHANNEL, false); - - Properties props = new Properties(); - s.store(props); - assertEquals(2, props.size()); - - NotificationSettings loaded = new NotificationSettings(); - loaded.load(props); - assertTrue(loaded.isImportant(SoundEvent.YOU_SWITCHED_CHANNEL)); - assertFalse(loaded.isEnabled(SoundEvent.CHAT_RECEIVED_MESSAGE_CHANNEL)); - assertTrue(loaded.isImportant(SoundEvent.OTHER_RECEIVED_POKE)); - } - - @Test - void storeClearsStaleEntries() { - Properties props = new Properties(); - NotificationSettings s = new NotificationSettings(); - s.setEnabled(SoundEvent.SERVER_ERROR, false); - s.store(props); - assertEquals(1, props.size()); - - s.setEnabled(SoundEvent.SERVER_ERROR, true); - s.store(props); - assertTrue(props.isEmpty()); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/sound/SoundPackTest.java b/ts3-client/core/src/test/java/com/ts3client/sound/SoundPackTest.java deleted file mode 100644 index c794460..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/sound/SoundPackTest.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.ts3client.sound; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import java.io.File; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - -class SoundPackTest { - - private static final String INI = """ - [info] - # a comment - name = Test Pack - version = 1.0 - author = Somebody - - [soundfiles] - CONNECTION_CONNECTED = play("connected.wav") - CONNECTION_DISCONNECTED = - CHANNEL_CREATED_BY_OTHER = say("Channel ${channelname} was created by ${clientname}") - CLIENT_MOVED_TO_CURRENT_CHANNEL_STAYS = play("${clientType}_moved_tocurrentchannel.wav") - NOT_AN_EVENT = play("nothing.wav") - """; - - private SoundPack load(Path dir) throws Exception { - Files.writeString(dir.resolve("settings.ini"), INI, StandardCharsets.UTF_8); - Files.writeString(dir.resolve("connected.wav"), "not really audio"); - Files.writeString(dir.resolve("Neutral_Moved_ToCurrentChannel.wav"), "not really audio"); - SoundPack pack = SoundPack.load(dir.toFile()); - assertNotNull(pack); - return pack; - } - - @Test - void readsPackInfo(@TempDir Path dir) throws Exception { - SoundPack pack = load(dir); - assertEquals(dir.getFileName().toString(), pack.id()); - assertEquals("Test Pack", pack.name()); - assertEquals("Somebody", pack.author()); - assertEquals("1.0", pack.version()); - } - - @Test - void mapsEventsAndSkipsEmptyOnes(@TempDir Path dir) throws Exception { - SoundPack pack = load(dir); - assertEquals(new SoundScript(SoundScript.Kind.PLAY, "connected.wav"), - pack.script(SoundEvent.CONNECTION_CONNECTED)); - assertNull(pack.script(SoundEvent.CONNECTION_DISCONNECTED)); - assertEquals(SoundScript.Kind.SAY, pack.script(SoundEvent.CHANNEL_CREATED_BY_OTHER).kind()); - } - - @Test - void resolvesVariables(@TempDir Path dir) throws Exception { - SoundPack pack = load(dir); - String spoken = pack.script(SoundEvent.CHANNEL_CREATED_BY_OTHER) - .resolve(Map.of("channelname", "Lobby", "clientname", "Bob")); - assertEquals("Channel Lobby was created by Bob", spoken); - } - - @Test - void findsFilesRegardlessOfCase(@TempDir Path dir) throws Exception { - SoundPack pack = load(dir); - String name = pack.script(SoundEvent.CLIENT_MOVED_TO_CURRENT_CHANNEL_STAYS) - .resolve(Map.of("clientType", "neutral")); - assertEquals("neutral_moved_tocurrentchannel.wav", name); - File file = pack.file(name); - assertNotNull(file); - assertEquals("Neutral_Moved_ToCurrentChannel.wav", file.getName()); - } - - @Test - void unknownEntriesAreIgnored(@TempDir Path dir) throws Exception { - SoundPack pack = load(dir); - assertNull(pack.file("nothing.wav")); - } - - @Test - void directoryWithoutIniIsNotAPack(@TempDir Path dir) { - assertNull(SoundPack.load(dir.toFile())); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/sound/WaveFileTest.java b/ts3-client/core/src/test/java/com/ts3client/sound/WaveFileTest.java deleted file mode 100644 index 9e018d6..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/sound/WaveFileTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.ts3client.sound; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import java.io.File; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.file.Files; -import java.nio.file.Path; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -class WaveFileTest { - - @TempDir - Path dir; - - /** Builds a wave file around raw sample bytes. */ - private File wave(int format, int channels, int bits, boolean extensible, byte[] data) throws IOException { - int fmtSize = extensible ? 40 : 16; - ByteBuffer b = ByteBuffer.allocate(12 + 8 + fmtSize + 8 + data.length).order(ByteOrder.LITTLE_ENDIAN); - b.put("RIFF".getBytes()).putInt(b.capacity() - 8).put("WAVE".getBytes()); - b.put("fmt ".getBytes()).putInt(fmtSize); - b.putShort((short) (extensible ? 0xFFFE : format)).putShort((short) channels).putInt(44100) - .putInt(44100 * channels * bits / 8).putShort((short) (channels * bits / 8)).putShort((short) bits); - if (extensible) { - b.putShort((short) 22).putShort((short) bits).putInt(0).putShort((short) format).put(new byte[14]); - } - b.put("data".getBytes()).putInt(data.length).put(data); - File file = dir.resolve("test.wav").toFile(); - Files.write(file.toPath(), b.array()); - return file; - } - - @Test - void readsSixteenBitMono() throws IOException { - WaveFile.Audio audio = WaveFile.readMono(wave(1, 1, 16, false, new byte[]{0, 0x40, 0, (byte) 0xC0})); - assertEquals(44100, audio.sampleRate()); - assertArrayEquals(new float[]{0.5f, -0.5f}, audio.samples()); - } - - @Test - void averagesStereoDown() throws IOException { - WaveFile.Audio audio = WaveFile.readMono(wave(1, 2, 16, false, new byte[]{0, 0x40, 0, 0})); - assertArrayEquals(new float[]{0.25f}, audio.samples()); - } - - @Test - void readsUnsignedEightBit() throws IOException { - WaveFile.Audio audio = WaveFile.readMono(wave(1, 1, 8, false, new byte[]{(byte) 192, 64, (byte) 128})); - assertArrayEquals(new float[]{0.5f, -0.5f, 0f}, audio.samples()); - } - - @Test - void readsTwentyFourBitThroughAnExtensibleHeader() throws IOException { - WaveFile.Audio audio = WaveFile.readMono(wave(1, 1, 24, true, new byte[]{0, 0, 0x40, 0, 0, (byte) 0xC0})); - assertArrayEquals(new float[]{0.5f, -0.5f}, audio.samples()); - } - - @Test - void readsFloat() throws IOException { - byte[] data = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putFloat(0.25f).putFloat(-1f).array(); - assertArrayEquals(new float[]{0.25f, -1f}, WaveFile.readMono(wave(3, 1, 32, false, data)).samples()); - } - - @Test - void rejectsCompressedAudio() { - assertThrows(IOException.class, () -> WaveFile.readMono(wave(2, 1, 4, false, new byte[4]))); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/teamspeak/SyncItemsTest.java b/ts3-client/core/src/test/java/com/ts3client/teamspeak/SyncItemsTest.java deleted file mode 100644 index ff0e3a4..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/teamspeak/SyncItemsTest.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.ts3client.teamspeak; - -import com.ts3client.config.IdentityStore; -import org.junit.jupiter.api.Test; - -import java.io.File; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * The fixture is the {@code ProtobufItems} table a fresh official client wrote - * (config, hotkey profile, "Default" identity, "TeamSpeak Public" bookmark, - * checksum), plus a folder, two more bookmarks, a deleted bookmark and a - * whisper list appended in the same encoding. - */ -class SyncItemsTest { - - private static final String IDENTITY_UUID = "965483cf-210f-dd22-ee1f-33591b0587a4"; - private static final String FOLDER_UUID = "0f0f0f0f-0000-4000-8000-000000000001"; - - static File fixture() { - return new File(SyncItemsTest.class.getResource("/teamspeak/sync.db").getFile()); - } - - @Test - void readsBookmarksIdentitiesAndFoldersOnly() throws Exception { - List items = TeamSpeakSettingsDb.readSyncItems(fixture()); - assertEquals(5, items.size()); - assertEquals(List.of(IDENTITY_UUID, "ea120ce1-b68b-b314-46ee-e16b3bf10342", FOLDER_UUID, - "bbbbbbbb-0000-4000-8000-000000000002", "bbbbbbbb-0000-4000-8000-000000000003"), - items.stream().map(SyncItem::uuid).toList()); - } - - @Test - void decodesTheClientsOwnIdentityAndBookmark() throws Exception { - List items = TeamSpeakSettingsDb.readSyncItems(fixture()); - - SyncItem.Identity identity = (SyncItem.Identity) items.get(0); - assertEquals("Default", identity.name()); - assertEquals("SyncTester", identity.nickname()); - assertEquals("", identity.parentUuid()); - assertTrue(identity.isDefault()); - assertTrue(identity.identity().matches("\\d+V[\\w+/=]+")); - assertNotNull(IdentityStore.parseIdentityString(identity.identity()).getUid()); - - SyncItem.Bookmark bookmark = (SyncItem.Bookmark) items.get(1); - assertEquals("TeamSpeak Public", bookmark.name()); - assertEquals("voice.teamspeak.com", bookmark.address()); - assertEquals(9987, bookmark.port()); - assertEquals("", bookmark.identityUuid(), "connects with the default identity"); - assertEquals("", bookmark.nickname()); - assertFalse(bookmark.autoconnect()); - } - - @Test - void decodesFoldersAndEveryBookmarkField() throws Exception { - List items = TeamSpeakSettingsDb.readSyncItems(fixture()); - - SyncItem.Folder folder = (SyncItem.Folder) items.get(2); - assertEquals("Clan servers", folder.name()); - - SyncItem.Bookmark inFolder = (SyncItem.Bookmark) items.get(3); - assertEquals(FOLDER_UUID, inFolder.parentUuid()); - assertEquals("Lixko", inFolder.name()); - assertEquals(IDENTITY_UUID, inFolder.identityUuid()); - assertEquals("server.lixko.eu", inFolder.address()); - assertEquals("Bookmark Nick", inFolder.nickname()); - assertEquals("hunter2", inFolder.serverPassword()); - assertEquals("Lobby/Games", inFolder.defaultChannel()); - assertEquals("chanpw", inFolder.defaultChannelPassword()); - assertTrue(inFolder.autoconnect()); - - SyncItem.Bookmark byId = (SyncItem.Bookmark) items.get(4); - assertEquals(9988, byId.port()); - assertEquals(42, byId.defaultChannelId()); - assertEquals("", byId.identityUuid()); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/teamspeak/SyncOrderTest.java b/ts3-client/core/src/test/java/com/ts3client/teamspeak/SyncOrderTest.java deleted file mode 100644 index 2e3a663..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/teamspeak/SyncOrderTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.ts3client.teamspeak; - -import org.junit.jupiter.api.Test; - -import java.io.File; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -class SyncOrderTest { - - /** - * Written by the official client: Charlie, Alpha and Bravo added in that order, Bravo dragged - * to the top, Charlie removed, then a folder with Delta and Echo added below TeamSpeak Public. - */ - @Test - void readsBookmarksInTheOrderTheOfficialClientListsThem() throws Exception { - File db = new File(SyncOrderTest.class.getResource("/teamspeak/reordered.db").getFile()); - assertEquals(List.of("Bravo", "TeamSpeak Public", "[New Folder]", "Delta", "Echo", "Alpha"), - names(TeamSpeakSettingsDb.readSyncItems(db))); - } - - @Test - void putsItemsWithBrokenLinksLastInStoredOrder() { - List items = List.of( - folder("f", "", "b"), - bookmark("x", "", "lost"), - bookmark("c", "f", ""), - bookmark("a", "", ""), - bookmark("y", "gone", ""), - bookmark("b", "", "a")); - assertEquals(List.of("a", "b", "[f]", "c", "x", "y"), names(SyncOrder.sorted(items))); - } - - @Test - void survivesALoop() { - List items = List.of(bookmark("a", "", "b"), bookmark("b", "", "a")); - assertEquals(List.of("a", "b"), names(SyncOrder.sorted(items))); - } - - private static SyncItem.Bookmark bookmark(String uuid, String parent, String previous) { - return new SyncItem.Bookmark(uuid, parent, previous, uuid, uuid + ".example", 9987, "", "", "", "", "", "", - 0, false); - } - - private static SyncItem.Folder folder(String uuid, String parent, String previous) { - return new SyncItem.Folder(uuid, parent, previous, uuid); - } - - private static List names(List items) { - return items.stream().map(i -> i instanceof SyncItem.Bookmark b ? b.name() - : i instanceof SyncItem.Folder f ? "[" + f.name() + "]" : null) - .filter(n -> n != null).toList(); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/teamspeak/TeamSpeakImporterTest.java b/ts3-client/core/src/test/java/com/ts3client/teamspeak/TeamSpeakImporterTest.java deleted file mode 100644 index 30d88f1..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/teamspeak/TeamSpeakImporterTest.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.ts3client.teamspeak; - -import com.ts3client.config.AppDirs; -import com.ts3client.config.Bookmark; -import com.ts3client.config.Bookmarks; -import com.ts3client.config.IdentityEntry; -import com.ts3client.config.IdentityStore; -import com.ts3client.config.Settings; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import java.nio.file.Path; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class TeamSpeakImporterTest { - - /** Each test starts from an empty profile; the shared test home keeps identities from earlier runs. */ - @BeforeEach - void freshProfile(@TempDir Path dir) { - AppDirs.init(dir.resolve("profile").toFile(), dir.resolve("chats")); - } - - @AfterEach - void defaultProfile() { - AppDirs.init(null, null); - } - - @Test - void importsBookmarksWithTheIdentitiesTheyUse() throws Exception { - Settings settings = new Settings(); - settings.nickname = "Fallback"; - IdentityStore identities = IdentityStore.load(settings); - Bookmarks bookmarks = new Bookmarks(); - bookmarks.add(new Bookmark("TeamSpeak Public", "VOICE.teamspeak.com", 9987, "me", "")); - - TeamSpeakImporter importer = new TeamSpeakImporter(identities, bookmarks, settings); - TeamSpeakImporter.Result result = importer.importBookmarks(SyncItemsTest.fixture()); - assertEquals(1, result.identitiesAdded()); - assertEquals(2, result.bookmarksAdded()); - assertEquals(1, result.bookmarksKnown()); - - IdentityEntry imported = identities.all().get(0); - assertEquals("Default", imported.getName()); - assertEquals(imported.getId(), settings.defaultIdentityId); - assertTrue(imported.getFile().isFile()); - - List all = bookmarks.all(); - assertEquals(3, all.size()); - Bookmark lixko = all.get(1); - assertEquals("Lixko", lixko.label); - assertEquals("Bookmark Nick", lixko.nickname); - assertEquals("hunter2", lixko.password); - assertEquals("Lobby/Games", lixko.channel); - assertEquals("chanpw", lixko.channelPassword); - assertEquals(imported.getId(), lixko.identityId); - assertTrue(lixko.connectOnStartup); - - Bookmark byId = all.get(2); - assertEquals("/42", byId.channel); - assertEquals("", byId.nickname, "takes the identity's nickname as it connects"); - assertEquals("SyncTester", imported.getNickname()); - assertEquals("", byId.identityId, "connects with whatever the default identity is"); - assertEquals("SyncTester", settings.nickname); - - // Running it again changes nothing. - result = importer.importBookmarks(SyncItemsTest.fixture()); - assertEquals(0, result.identitiesAdded()); - assertEquals(0, result.bookmarksAdded()); - assertEquals(3, bookmarks.all().size()); - assertEquals(1, identities.all().size()); - } - - @Test - void resolvesABookmarkNamingItsIdentity() throws Exception { - Settings settings = new Settings(); - IdentityStore identities = IdentityStore.load(settings); - Bookmarks bookmarks = new Bookmarks(); - SyncItem.Identity identity = TeamSpeakSettingsDb.readSyncItems(SyncItemsTest.fixture()).stream() - .filter(SyncItem.Identity.class::isInstance).map(SyncItem.Identity.class::cast).findFirst().orElseThrow(); - SyncItem.Bookmark bookmark = new SyncItem.Bookmark("b", "", "", "Server", "example.com", 9987, "", "", - identity.name(), "", "", "", 0, false); - - new TeamSpeakImporter(identities, bookmarks, settings).importAll(List.of(bookmark, identity)); - assertEquals(identities.all().get(0).getId(), bookmarks.all().get(0).identityId); - assertEquals("", bookmarks.all().get(0).nickname); - assertEquals(identity.nickname(), identities.all().get(0).getNickname()); - assertEquals(identity.phoneticNickname(), identities.all().get(0).getPhoneticNickname()); - } - - @Test - void importsTheSelectionWithTheIdentitiesItNeeds() throws Exception { - Settings settings = new Settings(); - IdentityStore identities = IdentityStore.load(settings); - Bookmarks bookmarks = new Bookmarks(); - TeamSpeakImporter importer = new TeamSpeakImporter(identities, bookmarks, settings); - List all = TeamSpeakSettingsDb.readSyncItems(SyncItemsTest.fixture()); - SyncItem.Bookmark lixko = all.stream().filter(SyncItem.Bookmark.class::isInstance) - .map(SyncItem.Bookmark.class::cast).filter(b -> b.name().equals("Lixko")).findFirst().orElseThrow(); - assertFalse(importer.isPresent(lixko)); - - TeamSpeakImporter.Result result = importer.importSelected(all, List.of(lixko)); - assertEquals(1, result.bookmarksAdded()); - assertEquals(1, result.identitiesAdded(), "the identity the bookmark connects with"); - assertEquals(identities.all().get(0).getId(), bookmarks.all().get(0).identityId); - assertTrue(importer.isPresent(lixko)); - assertTrue(all.stream().filter(SyncItem.Identity.class::isInstance).allMatch(importer::isPresent)); - } - - @Test - void identityImportRecognisesAKnownKey() throws Exception { - Settings settings = new Settings(); - IdentityStore identities = IdentityStore.load(settings); - int before = identities.all().size(); - TeamSpeakImporter importer = new TeamSpeakImporter(identities, new Bookmarks(), settings); - - TeamSpeakImporter.Result first = importer.importIdentities(SyncItemsTest.fixture()); - TeamSpeakImporter.Result second = importer.importIdentities(SyncItemsTest.fixture()); - assertEquals(1, first.identities()); - assertEquals(1, second.identitiesKnown()); - assertEquals(before + first.identitiesAdded(), identities.all().size()); - assertNotNull(identities.byId(settings.defaultIdentityId)); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/teamspeak/TeamSpeakSettingsDbTest.java b/ts3-client/core/src/test/java/com/ts3client/teamspeak/TeamSpeakSettingsDbTest.java deleted file mode 100644 index 58ff690..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/teamspeak/TeamSpeakSettingsDbTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.ts3client.teamspeak; - -import com.ts3client.contacts.Contact; -import com.ts3client.contacts.ContactType; -import com.ts3client.contacts.NicknameDisplay; -import org.junit.jupiter.api.Test; - -import java.io.File; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class TeamSpeakSettingsDbTest { - - private static File fixture() { - return new File(TeamSpeakSettingsDbTest.class.getResource("/teamspeak/settings.db").getFile()); - } - - @Test - void readsEveryContactOutOfTheDatabase() throws Exception { - List contacts = TeamSpeakSettingsDb.readContacts(fixture()); - assertEquals(60, contacts.size()); - - Contact alice = byUid(contacts, "AbCdEfGh1234567890abcdefghijk="); - assertEquals("Alice", alice.nickname); - assertEquals(ContactType.FRIEND, alice.type); - assertTrue(alice.hasVolumeModifier); - assertEquals(-6.0, alice.volumeModifier); - assertEquals("Test Server", alice.lastSeenServerName); - assertEquals(2024, alice.lastSeen.getYear()); - - Contact bob = byUid(contacts, "Zyxwvutsrqponmlkjihgfedcba00="); - assertEquals(ContactType.BLOCKED, bob.type); - assertTrue(bob.automute); - assertTrue(bob.ignorePokes); - assertTrue(!bob.whisperAllowed); - assertEquals(NicknameDisplay.ONLY_CUSTOM, bob.nicknameDisplay); - } - - /** The third record spills onto overflow pages at the fixture's 512-byte page size. */ - @Test - void followsOverflowPagesAndKeepsUnicode() throws Exception { - Contact carol = byUid(TeamSpeakSettingsDb.readContacts(fixture()), "Neutral0000000000000000000000="); - assertEquals("Carol Ünïcødé", carol.nickname); - assertEquals("Karol", carol.phoneticNickname); - assertEquals("X".repeat(900), carol.lastSeenServerName); - } - - @Test - void parsesColumnNamesOutOfCreateTable() { - assertEquals(List.of("timestamp", "key", "value"), SqliteReader.columnNames( - "CREATE TABLE Contacts (timestamp INTEGER UNSIGNED NOT NULL, key VARCHAR NOT NULL UNIQUE, value VARCHAR)")); - assertEquals(List.of("a", "b"), SqliteReader.columnNames( - "CREATE TABLE \"t\"(\"a\" TEXT, [b] INT, PRIMARY KEY (a, b))")); - } - - private static Contact byUid(List contacts, String uid) { - for (Contact c : contacts) if (c.uniqueId.equals(uid)) return c; - assertNotNull(null, "no contact " + uid); - return null; - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/text/BBCodeLinksTest.java b/ts3-client/core/src/test/java/com/ts3client/text/BBCodeLinksTest.java deleted file mode 100644 index 28e8108..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/text/BBCodeLinksTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.ts3client.text; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * The server log's renderer: it turns the client's own links into anchors and leaves - * everything else — names carrying bracket markup included — as plain text. - */ -class BBCodeLinksTest { - - @Test - void rendersClientAndChannelLinks() { - String log = TsLink.clientBBCode(7, "uid=", "Bob") + " connected to channel \"" - + TsLink.channelBBCode(3, "Lobby") + "\""; - String html = BBCode.linksToHtml(log); - assertTrue(html.contains("href=\"client://7/uid=~Bob\""), html); - assertTrue(html.contains(">Bob"), html); - assertTrue(html.contains("href=\"channel://3/Lobby\""), html); - assertTrue(html.contains(">Lobby"), html); - } - - @Test - void rendersTheOfflineMessagesLink() { - String html = BBCode.linksToHtml("You have " + TsLink.offlineMessagesBBCode("2 unread offline messages")); - assertTrue(html.contains("href=\"offline://\""), html); - assertTrue(html.contains(">2 unread offline messages"), html); - assertTrue(TsLink.isOfflineMessages("offline://")); - } - - @Test - void leavesOtherMarkupLiteral() { - assertEquals("[b]not bold[/b] & <i>", BBCode.linksToHtml("[b]not bold[/b] & ")); - } - - @Test - void keepsBracketsInsideALabelLiteral() { - String html = BBCode.linksToHtml(TsLink.channelBBCode(3, "[cspacer]---")); - assertTrue(html.contains(">[cspacer]---"), html); - } - - @Test - void rejectsHrefsThatAreNotLinks() { - assertEquals("[url=javascript:alert(1)]x[/url]", BBCode.linksToHtml("[url=javascript:alert(1)]x[/url]")); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/text/BBCodePlainTest.java b/ts3-client/core/src/test/java/com/ts3client/text/BBCodePlainTest.java deleted file mode 100644 index 9df318a..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/text/BBCodePlainTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.ts3client.text; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** Messages shown where no formatting renders, such as a system notification. */ -class BBCodePlainTest { - - @Test - void dropsMarkupAndKeepsText() { - assertEquals("Hello bold & and a link", - BBCode.toPlain("Hello [b]bold[/b] & and [url=https://x.y]a link[/url]")); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/text/BBCodeTagsTest.java b/ts3-client/core/src/test/java/com/ts3client/text/BBCodeTagsTest.java deleted file mode 100644 index 7e3c888..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/text/BBCodeTagsTest.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.ts3client.text; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; - -/** The block tags TeamSpeak's own client renders in descriptions. */ -class BBCodeTagsTest { - - @Test - void rulesStandAlone() { - assertEquals("a
    b", BBCode.toHtml("a[hr]b")); - assertEquals("a
    b", BBCode.toHtml("a[hr][/hr]b")); - } - - @Test - void alignsBlocks() { - assertEquals("
    x
    y
    ", - BBCode.toHtml("[right]x[/right][justify]y[/justify]")); - } - - @Test - void numbersLists() { - assertEquals("
    1. one
    2. two
    ", BBCode.toHtml("[list=1][*]one[*]two[/list]")); - assertEquals("
    1. x
    ", BBCode.toHtml("[list=a][*]x[/list]")); - } - - @Test - void buildsTablesOnlyWhereTheyNest() { - assertEquals("
    hd
    ", - BBCode.toHtml("[table][tr][th]h[/th][td]d[/td][/tr][/table]")); - assertEquals("[td]loose[/td]", BBCode.toHtml("[td]loose[/td]")); - } - - @Test - void showsPicturesOnlyWhereAsked() { - String bb = "[img]https://example.com/a.png[/img]"; - assertEquals("", BBCode.toHtml(bb, true)); - assertEquals("https://example.com/a.png", - BBCode.toHtml(bb)); - } - - @Test - void linksPicturesInsideALink() { - assertEquals("", - BBCode.toHtml("[url=https://x.org][img]http://x.org/b.gif[/img][/url]", true)); - } - - @Test - void showsNoPictureFromElsewhereThanTheWeb() { - assertEquals("[img]file:///etc/passwd[/img]", BBCode.toHtml("[img]file:///etc/passwd[/img]", true)); - assertFalse(BBCode.toHtml("[img=https://x.org/a.png]", true).contains("", BBCode.toHtml("[img]https://x.org/a.png?a=1&b=2[/img]", true)); - } - - @Test - void shortensLongAddressesToHostAndFile() { - assertEquals("https://x.org/a.png", BBCode.shortAddress("https://x.org/a.png")); - assertEquals("upload.wikimedia.org/…/250px-Example.png", BBCode.shortAddress( - "https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/Example.png/250px-Example.png")); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/text/ChatHtmlAttachmentTest.java b/ts3-client/core/src/test/java/com/ts3client/text/ChatHtmlAttachmentTest.java deleted file mode 100644 index 5aab69d..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/text/ChatHtmlAttachmentTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.ts3client.text; - -import com.ts3client.chatlog.ChatLogScope; -import com.ts3client.chatlog.ChatLogStore; -import com.ts3client.myts.ChatAttachment; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import java.nio.file.Path; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class ChatHtmlAttachmentTest { - - private static final String ROOM = "+Tyg2JtxE8vRNZp+JiUBnmBh0MY="; - private static final ChatAttachment PICTURE = ChatAttachment.of("f1", "abc", "cat.png", 532); - private static final ChatAttachment FILE = ChatAttachment.of("f2", "abc", "notes <1>.txt", 3 << 20); - - @Test - void showsAPictureAsOne() { - String html = ChatHtml.message(5, "uid", "alice", PICTURE.toMessage(), ROOM); - assertTrue(html.contains(""), html); - assertFalse(html.contains("msg_type"), html); - } - - @Test - void showsAnyOtherFileAsALinkWithItsSize() { - String html = ChatHtml.message(5, "uid", "alice", FILE.toMessage(), ROOM); - assertTrue(html.contains("href=\"" + FILE.href(ROOM) + "\">notes <1>.txt"), html); - assertTrue(html.contains("(3.0 MB)"), html); - } - - @Test - void namesTheFileWhereItCannotBeFetched() { - String html = ChatHtml.message(5, "uid", "alice", PICTURE.toMessage()); - assertFalse(html.contains(" history = logs.channelHtmlHistory(); - String html = ChatHtml.logEntry(history.get(history.size() - 1), ROOM); - assertTrue(html.contains(""), html); - assertFalse(html.contains("msg_type"), html); - } - - @Test - void previewsAFileByItsName() { - assertEquals("cat.png", ChatHtml.plainMessage(PICTURE.toMessage())); - assertEquals("hi", ChatHtml.plainMessage("[b]hi[/b]")); - } -} diff --git a/ts3-client/core/src/test/java/com/ts3client/text/TextQueryTest.java b/ts3-client/core/src/test/java/com/ts3client/text/TextQueryTest.java deleted file mode 100644 index 6d6a304..0000000 --- a/ts3-client/core/src/test/java/com/ts3client/text/TextQueryTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.ts3client.text; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class TextQueryTest { - - @Test - void ignoresCaseUnlessAsked() { - assertTrue(new TextQuery("hello", false, false, false).matches("Say HELLO there")); - assertFalse(new TextQuery("hello", true, false, false).matches("Say HELLO there")); - assertTrue(new TextQuery("čau", false, false, false).matches("ČAU")); - } - - @Test - void wholeWordsStopAtLettersAndDigitsOnly() { - TextQuery q = new TextQuery("cat", false, true, false); - assertTrue(q.matches("the cat sat")); - assertTrue(q.matches("(cat)")); - assertFalse(q.matches("concatenate")); - assertFalse(q.matches("cat2")); - assertTrue(new TextQuery("@all", false, true, false).matches("hey @all!")); - } - - @Test - void literalUnlessRegex() { - assertFalse(new TextQuery("a.c", false, false, false).matches("abc")); - assertTrue(new TextQuery("a.c", false, false, true).matches("abc")); - } - - @Test - void invalidRegexMatchesNothing() { - TextQuery q = new TextQuery("(", false, false, true); - assertTrue(q.isInvalid()); - assertFalse(q.matches("(")); - } - - @Test - void plainTextOfHtml() { - assertEquals("<\"x\"> a & b", HtmlText.plain("<"x"> a & b")); - assertEquals("line\nnext", HtmlText.plain("line
    next")); - assertEquals("é", HtmlText.plain("é")); - } -} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/FakeOpus.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/FakeOpus.java new file mode 100644 index 0000000..0a6a8c0 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/FakeOpus.java @@ -0,0 +1,70 @@ +package eu.lixko.ts3j.client.audio; + +import eu.lixko.ts3j.client.audio.opus.OpusCodec; +import eu.lixko.ts3j.client.audio.opus.OpusDecoder; +import eu.lixko.ts3j.client.audio.opus.OpusEncoder; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Stands in for libopus: a "packet" of n bytes decodes to n 20 ms frames holding the first byte + * divided by 100 in every sample. Concealment yields -1 and recovery -2, so both are easy to spot. + */ +final class FakeOpus implements OpusCodec { + + static final float CONCEALED = -1f; + static final float RECOVERED = -2f; + + int resets; + final List concealedFrameSizes = new ArrayList<>(); + + static byte[] packet(int value) { + return new byte[]{(byte) value}; + } + + @Override + public OpusEncoder createEncoder(int sampleRate, int frameSize, int channels, Application application) { + throw new UnsupportedOperationException(); + } + + @Override + public OpusDecoder createDecoder(int sampleRate, int maxFrameSize, int channels) { + return new OpusDecoder() { + @Override + public int decode(byte[] packet, float[] out) { + int frames = VoiceFormat.FRAME_SIZE * packet.length; + Arrays.fill(out, 0, frames * channels, packet[0] / 100f); + return frames; + } + + @Override + public int conceal(float[] out, int frameSize) { + concealedFrameSizes.add(frameSize); + Arrays.fill(out, 0, frameSize * channels, CONCEALED); + return frameSize; + } + + @Override + public int recover(byte[] next, float[] out, int frameSize) { + Arrays.fill(out, 0, frameSize * channels, RECOVERED); + return frameSize; + } + + @Override + public void reset() { + resets++; + } + + @Override + public void close() { + } + }; + } + + @Override + public String version() { + return "fake"; + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/JitterBufferTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/JitterBufferTest.java new file mode 100644 index 0000000..5c469d6 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/JitterBufferTest.java @@ -0,0 +1,374 @@ +package eu.lixko.ts3j.client.audio; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class JitterBufferTest { + + private static final int SPAN = JitterBuffer.TEAMSPEAK_TICKS_PER_FRAME; + + private static JitterBuffer buffer() { + return JitterBuffer.forTeamSpeakVoice(SPAN); + } + + /** Frame {@code n} of a stream, tagged so it can be identified on the way out. */ + private static byte[] frame(int n) { + return new byte[]{(byte) n}; + } + + private static void put(JitterBuffer b, int n) { + b.put(frame(n), n * SPAN, SPAN); + } + + /** Pulls one frame, returning its tag, or -1 for concealment. */ + private static int pull(JitterBuffer b) { + JitterBuffer.Status status = b.get(SPAN); + int tag = status == JitterBuffer.Status.OK ? b.payload()[0] : -1; + b.tick(); + return tag; + } + + @Test + void playsAnUndisturbedStreamInOrder() { + JitterBuffer b = buffer(); + List played = new ArrayList<>(); + for (int i = 0; i < 20; i++) { + put(b, i); + played.add(pull(b)); + } + // The buffer holds some delay back, so the tail is still queued; nothing is reordered. + List real = played.stream().filter(n -> n >= 0).toList(); + assertEquals(real.stream().sorted().toList(), real); + assertTrue(real.size() >= 15, "most frames should have played: " + played); + } + + @Test + void aLargerMarginBuffersThatMuchMore() { + JitterBuffer b = buffer(); + int n = 0; + int lastPlayed = -1; + for (; n < 60; n++) { + put(b, n); + int tag = pull(b); + if (tag >= 0) lastPlayed = tag; + } + int before = n - 1 - lastPlayed; + + b.setMargin(b.margin() + 5 * SPAN); + for (; n < 120; n++) { + put(b, n); + int tag = pull(b); + if (tag >= 0) lastPlayed = tag; + } + assertEquals(before + 5, n - 1 - lastPlayed); + } + + @Test + void reordersPacketsThatArriveOutOfOrder() { + JitterBuffer b = buffer(); + // Prime a delay so a swapped pair still lands in time. + for (int i = 0; i < 12; i++) { + put(b, i); + pull(b); + } + + put(b, 13); + put(b, 12); + put(b, 14); + + List played = new ArrayList<>(); + for (int i = 0; i < 6; i++) played.add(pull(b)); + List real = played.stream().filter(n -> n >= 0).toList(); + assertEquals(real.stream().sorted().toList(), real, "played out of order: " + played); + assertTrue(real.contains(12) && real.contains(13) && real.contains(14), "lost a frame: " + played); + } + + @Test + void reportsMissingFramesInsteadOfSkippingAhead() { + JitterBuffer b = buffer(); + for (int i = 0; i < 30; i++) { + if (i != 20) put(b, i); + } + + int concealed = 0; + int played = 0; + for (int i = 0; i < 30; i++) { + if (pull(b) < 0) concealed++; + else played++; + } + assertTrue(concealed >= 1, "the gap should have been concealed"); + assertEquals(29, played, "every delivered frame should still be played"); + } + + @Test + void everyGetYieldsExactlyOneFrameOfAudio() { + JitterBuffer b = buffer(); + Random random = new Random(7); + long ticks = 0; + for (int i = 0; i < 200; i++) { + if (random.nextInt(10) != 0) put(b, i); + b.get(SPAN); + assertEquals(0, b.span() % SPAN, "a partial frame cannot be rendered"); + assertTrue(b.span() > 0); + ticks += b.span(); + b.tick(); + } + // Concealment for a growing delay may run long, but audio never stops or doubles up. + assertTrue(ticks >= 200L * SPAN, "output underran: " + ticks); + } + + @Test + void growsTheDelayWhenArrivalsAreJittery() { + JitterBuffer b = buffer(); + Random random = new Random(11); + + // Deliver in bursts: frames pile up, then nothing arrives for a while. + int next = 0; + int concealedEarly = 0; + int concealedLate = 0; + for (int i = 0; i < 400; i++) { + if (i % 5 == 0) { + int burst = 3 + random.nextInt(4); + for (int j = 0; j < burst && next < 400; j++) put(b, next++); + } + boolean concealed = pull(b) < 0; + if (i < 100) concealedEarly += concealed ? 1 : 0; + else if (i >= 300) concealedLate += concealed ? 1 : 0; + } + + assertTrue(concealedLate < concealedEarly, + "the buffer should settle: " + concealedEarly + " -> " + concealedLate); + } + + @Test + void staysStableAcrossTimestampWraparound() { + JitterBuffer b = buffer(); + // Start just below the point where the tick counter overflows. + int base = Integer.MAX_VALUE - 5 * SPAN; + for (int i = 0; i < 40; i++) { + b.put(frame(i), base + i * SPAN, SPAN); + } + int played = 0; + for (int i = 0; i < 40; i++) { + if (b.get(SPAN) == JitterBuffer.Status.OK) { + assertNotNull(b.payload()); + played++; + } + b.tick(); + } + assertTrue(played >= 35, "wraparound lost frames: " + played); + } + + @Test + void resetForgetsTheTimelineSoTheNextBurstResyncs() { + JitterBuffer b = buffer(); + for (int i = 0; i < 10; i++) { + put(b, i); + pull(b); + } + b.reset(); + assertTrue(b.isEmpty()); + + // A new burst numbered far away must still play, not be treated as hopelessly late. + b.put(frame(1), 500 * SPAN, SPAN); + assertEquals(JitterBuffer.Status.OK, b.get(SPAN)); + assertEquals(1, b.payload()[0]); + } + + @Test + void dropsPacketsThatArriveHopelesslyLate() { + JitterBuffer b = buffer(); + for (int i = 0; i < 40; i++) { + put(b, i); + pull(b); + } + assertFalse(b.isEmpty() && b.bufferedSpan() != 0); + + // A frame from far in the past has nowhere to go and must not stall the stream. + b.put(frame(99), 0, SPAN); + for (int i = 0; i < 5; i++) { + assertTrue(pull(b) != 99, "a hopelessly late frame was played"); + } + } + + @Test + void teamSpeakConfigurationMatchesTheShippedClient() { + JitterBuffer b = JitterBuffer.forTeamSpeakVoice(JitterBuffer.TEAMSPEAK_TICKS_PER_FRAME); + assertEquals(60, JitterBuffer.TEAMSPEAK_TICKS_PER_FRAME); + assertEquals(60, b.margin()); + } + + /** Plays until nothing is held, leaving the position just past the last real frame. */ + private static void drain(JitterBuffer b) { + for (int i = 0; i < 100 && !b.isEmpty(); i++) pull(b); + } + + @Test + void offersTheFollowingPacketToRebuildALostOne() { + JitterBuffer b = buffer(); + for (int i = 0; i < 12; i++) put(b, i); + drain(b); + + // The frame due now never arrives, but the one after it is already here, + // carrying the FEC copy that can rebuild it. + int due = b.position(); + b.put(frame(13), due + SPAN, SPAN); + + assertEquals(JitterBuffer.Status.MISSING, b.get(SPAN)); + assertNotNull(b.nextPayload(), "the successor should be offered for FEC recovery"); + assertEquals(13, b.nextPayload()[0]); + b.tick(); + + // And it is still there to be played normally afterwards. + assertEquals(13, pull(b)); + } + + @Test + void offersNothingWhenTheSuccessorIsAlsoLost() { + JitterBuffer b = buffer(); + for (int i = 0; i < 12; i++) put(b, i); + drain(b); + + // Two frames in a row are gone; FEC only reaches back one. + int due = b.position(); + b.put(frame(15), due + 2 * SPAN, SPAN); + + assertEquals(JitterBuffer.Status.MISSING, b.get(SPAN)); + assertNull(b.nextPayload(), "a double loss cannot be rebuilt from FEC"); + } + + @Test + void aPauseInSpeechCostsNothingWhenTheClockStopsToo() { + JitterBuffer b = buffer(); + for (int i = 0; i < 40; i++) { + put(b, i); + pull(b); + } + drain(b); + + // Silence. No packets arrive and nothing is pulled, so the position stays put — + // which is what lets the sender's numbering still line up when speech resumes. + int paused = b.position(); + assertEquals(paused, b.position()); + + b.put(frame(7), paused, SPAN); + assertEquals(JitterBuffer.Status.OK, b.get(SPAN), "the next burst should play, not be judged late"); + assertEquals(7, b.payload()[0]); + } + + @Test + void keepsItsEstimateAcrossAPause() { + JitterBuffer b = buffer(); + Random random = new Random(5); + int next = 0; + for (int i = 0; i < 300; i++) { + if (i % 4 == 0) { + for (int j = 0, burst = 2 + random.nextInt(4); j < burst; j++) put(b, next++); + } + pull(b); + } + drain(b); + + JitterBuffer fresh = buffer(); + assertTrue(concealedInBurst(b, b.position() / SPAN) <= concealedInBurst(fresh, 1000), + "a buffer that survived the pause should conceal no more than a cold one"); + } + + /** Plays a short jittery burst through a buffer and counts the concealed frames. */ + private static int concealedInBurst(JitterBuffer b, int firstFrame) { + Random random = new Random(9); + int concealed = 0; + int next = firstFrame; + for (int i = 0; i < 60; i++) { + if (i % 4 == 0) { + for (int j = 0, burst = 2 + random.nextInt(4); j < burst; j++) { + b.put(frame(next), next * SPAN, SPAN); + next++; + } + } + if (pull(b) < 0) concealed++; + } + return concealed; + } + + @Test + void resetForgetsTheNetworkEstimateToo() { + JitterBuffer b = buffer(); + for (int i = 0; i < 100; i++) { + put(b, i); + pull(b); + } + b.reset(); + // With no timings recorded there is nothing to justify moving the delay. + assertTrue(b.isEmpty()); + assertEquals(0, b.heldFrames(SPAN)); + } + + @Test + void heldFramesCountsWhatIsWaiting() { + JitterBuffer b = buffer(); + assertEquals(0, b.heldFrames(SPAN)); + put(b, 0); + put(b, 1); + put(b, 2); + assertEquals(3, b.heldFrames(SPAN)); + } + + @Test + void aShortUtteranceComesOutWhole() { + JitterBuffer b = buffer(); + int played = 0; + // Five frames, one per frame period — a single short word. + for (int i = 0; i < 5; i++) { + put(b, i); + if (pull(b) >= 0) played++; + } + // Then whatever the delay is still holding back. + for (int i = 0; i < 20 && !b.isEmpty(); i++) { + if (pull(b) >= 0) played++; + } + assertEquals(5, played, "every frame of a short utterance must be heard"); + } + + @Test + void pullingOnlyWhenAPacketIsWaitingStarvesTheStream() { + // The buffer adapts its delay in tick(), which only runs on a pull. A consumer that + // skips the pull whenever the buffer happens to be empty pins the delay at zero — + // and at zero delay the buffer is empty much of the time, so it never recovers. + int periods = 300; + assertEquals(periods, emitted(true), "a frame per period keeps the device fed"); + + int gated = emitted(false); + assertTrue(gated < periods * 9 / 10, + "gating the pull on a non-empty buffer should visibly starve the device: " + gated); + } + + /** Runs a jittery arrival schedule for 300 periods, counting frames actually emitted. */ + private static int emitted(boolean pullEveryPeriod) { + JitterBuffer b = buffer(); + Random random = new Random(13); + int next = 0; + int frames = 0; + for (int i = 0; i < 300; i++) { + // Arrivals clump and stall, as they do on a real connection. + if (random.nextInt(4) != 0) { + for (int j = 0, burst = random.nextInt(3); j < burst; j++) put(b, next++); + } + if (pullEveryPeriod || !b.isEmpty()) { + b.get(SPAN); + b.tick(); + frames++; + } + } + return frames; + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/MixedPlayoutTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/MixedPlayoutTest.java new file mode 100644 index 0000000..2d68420 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/MixedPlayoutTest.java @@ -0,0 +1,102 @@ +package eu.lixko.ts3j.client.audio; + +import com.github.manevolent.ts3j.enums.CodecType; +import com.github.manevolent.ts3j.protocol.ProtocolRole; +import com.github.manevolent.ts3j.protocol.packet.PacketBody0Voice; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class MixedPlayoutTest { + + /** A mono line that records every frame written and blocks until the test lets it go on. */ + private static final class RecordingLine implements AudioPlayback { + final BlockingQueue firstSamples = new LinkedBlockingQueue<>(); + final Semaphore permits = new Semaphore(0); + + @Override + public int channels() { + return 1; + } + + @Override + public void start() { + } + + @Override + public void write(byte[] buffer, int offset, int length) { + firstSamples.add((short) ((buffer[offset + 1] << 8) | (buffer[offset] & 0xFF))); + permits.acquireUninterruptibly(); + } + + @Override + public void drain() { + } + + @Override + public void close() { + } + } + + @Test + void mixesSimultaneousSpeakersOntoOneLine() throws Exception { + RecordingLine line = new RecordingLine(); + AudioIo io = new AudioIo() { + @Override + public List inputDevices() { + return List.of(); + } + + @Override + public List outputDevices() { + return List.of(); + } + + @Override + public AudioCapture openCapture(String deviceId, int preferredChannels) { + throw new UnsupportedOperationException(); + } + + @Override + public AudioPlayback openPlayback(String deviceId, int preferredChannels) { + return line; + } + }; + StreamingVoiceOutput output = new StreamingVoiceOutput(io, new FakeOpus(), "", StreamingVoiceOutput.Lines.SHARED); + try { + for (int i = 0; i < 10; i++) { + output.handleVoice(voice(1, i, 25)); + output.handleVoice(voice(2, i, 50)); + } + line.permits.release(100); + + short expected = (short) Math.round(0.75f * 32767f); + boolean mixed = false; + for (int i = 0; i < 20 && !mixed; i++) { + Short sample = line.firstSamples.poll(1, TimeUnit.SECONDS); + assertNotNull(sample, "the mixer stopped writing"); + mixed = sample == expected; + } + assertTrue(mixed, "no frame carried both speakers"); + } finally { + output.shutdown(); + line.permits.release(1000); + } + } + + private static PacketBody0Voice voice(int clientId, int packetId, int value) { + PacketBody0Voice voice = new PacketBody0Voice(ProtocolRole.SERVER); + voice.setClientId(clientId); + voice.setPacketId(packetId); + voice.setCodecType(CodecType.OPUS_VOICE); + voice.setCodecData(FakeOpus.packet(value)); + return voice; + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/VoiceStreamTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/VoiceStreamTest.java new file mode 100644 index 0000000..7b0c6f0 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/VoiceStreamTest.java @@ -0,0 +1,246 @@ +package eu.lixko.ts3j.client.audio; + +import com.github.manevolent.ts3j.enums.CodecType; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class VoiceStreamTest { + + private final FakeOpus opus = new FakeOpus(); + private final List talk = new ArrayList<>(); + private final VoiceStream stream = new VoiceStream(7, opus, (id, talking) -> talk.add(talking)); + private final float[] out = new float[VoiceStream.MAX_FRAME * 2]; + + private boolean offer(int packetId, int value) { + return stream.offer(packetId, CodecType.OPUS_VOICE, FakeOpus.packet(value)); + } + + private void offerEnd(int packetId) { + stream.offer(packetId, CodecType.OPUS_VOICE, new byte[0]); + } + + /** Pulls one frame and returns its first sample, or NaN if nothing was played. */ + private float pull() { + int frames = stream.pull(out, 1, 1.0); + return frames > 0 ? out[0] : Float.NaN; + } + + @Test + void playsPacketsInOrderWhateverOrderTheyArriveIn() { + assertTrue(offer(10, 1)); + assertFalse(offer(12, 3)); + assertFalse(offer(11, 2)); + + assertEquals(0.01f, pull()); + assertEquals(0.02f, pull()); + assertEquals(0.03f, pull()); + assertEquals(List.of(true), talk); + } + + @Test + void tapHearsTheSpeakerInMonoAtFullVolume() { + List tapped = new ArrayList<>(); + stream.setTap((clientId, mono, frames) -> { + assertEquals(7, clientId); + assertEquals(VoiceFormat.FRAME_SIZE, frames); + tapped.add(mono[frames - 1]); + }); + stream.offer(0, CodecType.OPUS_MUSIC, FakeOpus.packet(40)); + stream.pull(out, 2, 0.5); + assertEquals(0.2f, out[1]); + assertEquals(List.of(0.4f), tapped); + } + + @Test + void rebuildsALostPacketFromTheOneAfterIt() { + offer(0, 1); + offer(2, 3); + assertEquals(0.01f, pull()); + assertEquals(FakeOpus.RECOVERED, pull()); + assertEquals(0.03f, pull()); + assertEquals(List.of(), opus.concealedFrameSizes); + } + + @Test + void concealsALostPacketWhenTheNextIsMissingToo() { + offer(0, 1); + offer(3, 4); + assertEquals(0.01f, pull()); + assertEquals(FakeOpus.CONCEALED, pull()); + assertEquals(FakeOpus.RECOVERED, pull()); + assertEquals(0.04f, pull()); + assertEquals(List.of(VoiceFormat.FRAME_SIZE), opus.concealedFrameSizes); + } + + @Test + void anExtraDelayLeadsANewSpeakerInWithSilence() { + stream.setExtraDelay(2 * JitterBuffer.TEAMSPEAK_TICKS_PER_FRAME); + offer(0, 1); + assertEquals(0f, pull()); + offer(1, 2); + assertEquals(0f, pull()); + assertEquals(0.01f, pull()); + assertEquals(0.02f, pull()); + assertEquals(List.of(), opus.concealedFrameSizes); + } + + @Test + void dropsPacketsThatArriveTooLate() { + offer(0, 1); + offer(1, 2); + pull(); + pull(); + assertFalse(offer(0, 9)); + } + + @Test + void aLateCopyAfterTheBurstDoesNotStartAnother() { + offer(0, 1); + offerEnd(1); + pull(); + pull(); + assertFalse(offer(0, 1)); + assertFalse(stream.isPlaying()); + assertEquals(List.of(true, false), talk); + } + + @Test + void countsWhatCameInAndWhatWasMissing() { + offer(0, 1); + offer(2, 3); + offer(1, 2); // out of order, still in time + offer(2, 3); // a copy + pull(); + pull(); + pull(); + pull(); // 3 never arrives: concealed + offer(3, 4); // too late, dropped + offer(3, 4); // a copy of that + assertEquals(new VoiceReceiveStats(6, 3, 1, 0, 1, 1, 2), stream.stats()); + } + + @Test + void theTalkersStopEndsTheBurst() { + offer(0, 1); + offerEnd(1); + assertEquals(0.01f, pull()); + assertEquals(VoiceStream.IDLE, stream.pull(out, 1, 1.0)); + assertFalse(stream.isPlaying()); + assertEquals(List.of(true, false), talk); + } + + @Test + void theNextBurstCarriesOnWhereTheLastStopped() { + offer(0, 1); + offerEnd(1); + pull(); + pull(); + + assertTrue(offer(2, 2), "the next packet starts a new burst"); + assertEquals(0f, pull(), "the stop's slot is the talker's own silence, not a loss"); + assertEquals(0.02f, pull()); + assertEquals(0, opus.resets, "the decoder keeps its state between bursts"); + assertEquals(List.of(), opus.concealedFrameSizes); + } + + @Test + void givesUpOnABurstWhoseStopWasLost() { + offer(0, 1); + pull(); + int concealed = 0; + while (stream.pull(out, 1, 1.0) != VoiceStream.IDLE) concealed++; + assertTrue(concealed > 0 && concealed < 10, "concealed " + concealed + " frames"); + assertEquals(List.of(true, false), talk); + } + + @Test + void playsALongPacketOneFrameAtATime() { + stream.offer(0, CodecType.OPUS_VOICE, new byte[]{40, 0}); + offer(1, 50); + assertEquals(VoiceFormat.FRAME_SIZE, stream.pull(out, 1, 1.0)); + assertEquals(0.4f, out[0]); + assertEquals(VoiceFormat.FRAME_SIZE, stream.pull(out, 1, 1.0)); + assertEquals(0.4f, out[0]); + assertEquals(0.5f, pull()); + } + + @Test + void stopFromAnotherThreadEndsTheBurst() { + offer(0, 1); + stream.stop(); + assertEquals(VoiceStream.IDLE, stream.pull(out, 1, 1.0)); + assertEquals(List.of(true, false), talk); + } + + @Test + void spreadsMonoOverStereoWithGain() { + offer(0, 50); + assertEquals(VoiceFormat.FRAME_SIZE, stream.pull(out, 2, 0.5)); + assertEquals(0.25f, out[0]); + assertEquals(0.25f, out[1]); + assertEquals(0.25f, out[2 * VoiceFormat.FRAME_SIZE - 1]); + } + + @Test + void neverHandsOutMoreThanOneFrame() { + for (int i = 0; i < 50; i++) offer(i, 1); + for (int i = 0; i < 50; i++) assertTrue(stream.pull(out, 1, 1.0) <= VoiceFormat.FRAME_SIZE); + } + + /** + * Packets sent every 20 ms arrive up to 60 ms late. A fixed delay short of that conceals + * constantly; the adaptive one should learn the spread and stop concealing. + */ + @Test + void learnsADelayThatRidesOutJitter() { + Random random = new Random(1); + int packets = 1500; + long[] arrival = new long[packets]; + for (int i = 0; i < packets; i++) arrival[i] = i * 20L + random.nextInt(61); + + int next = 0; + int concealedLate = 0; + for (long now = 0; now < packets * 20L; now += 20) { + for (; next < packets && arrival[next] <= now; next++) offer(next, 1); + // arrivals are not in order, but whatever is due by now has been offered + float sample = pull(); + if (now >= packets * 10L && sample == FakeOpus.CONCEALED) concealedLate++; + } + assertTrue(concealedLate < packets / 2 / 50, "concealed " + concealedLate + " frames in the second half"); + } + + /** + * Every packet is sent twice, the copy 120 ms after the original, and a tenth of the + * originals are lost. The copies arrive too late for a buffer tuned to the originals, so + * it has to learn from them and grow until they are in time to stand in. + */ + @Test + void growsToWaitForRedundantCopies() { + Random random = new Random(1); + int packets = 1500; + List arrivals = new ArrayList<>(); + for (int i = 0; i < packets; i++) { + if (random.nextInt(10) != 0) arrivals.add(new long[]{i * 20L, i}); + arrivals.add(new long[]{i * 20L + 120, i}); + } + arrivals.sort((x, y) -> Long.compare(x[0], y[0])); + + int next = 0; + int concealedLate = 0; + for (long now = 0; now < packets * 20L; now += 20) { + for (; next < arrivals.size() && arrivals.get(next)[0] <= now; next++) { + offer((int) arrivals.get(next)[1], 1); + } + float sample = pull(); + if (now >= packets * 10L && sample == FakeOpus.CONCEALED) concealedLate++; + } + assertTrue(concealedLate < packets / 2 / 100, "concealed " + concealedLate + " frames in the second half"); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/processing/AudioProcessorTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/processing/AudioProcessorTest.java new file mode 100644 index 0000000..16319c1 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/processing/AudioProcessorTest.java @@ -0,0 +1,194 @@ +package eu.lixko.ts3j.client.audio.processing; + +import eu.lixko.ts3j.client.audio.processing.ns.SuppressionLevel; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.Random; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Checks the chain against WebRTC itself. The {@code golden-*.s16} resources are + * {@link #testSignal()} run through upstream APM (webrtc-audio-processing 2.1 for noise + * suppression, 1.3 for the transient suppressor, which 2.x no longer ships), configured as + * TS3 configures it, and stored as 16-bit PCM. + */ +class AudioProcessorTest { + + private static final int RATE = AudioProcessor.SAMPLE_RATE; + private static final int FRAME = AudioProcessor.FRAME_SIZE; + + /** 10 ms frames in which the test signal has a key click, reported as key presses. */ + static final int[] KEY_FRAMES = {66, 72, 79, 85, 90, 97}; + private static final Set KEYS = Set.of(66, 72, 79, 85, 90, 97); + + /** + * One second of microphone-like input: quiet pink noise throughout, a voiced harmonic + * burst from 0.3 to 0.6 s, and key clicks after it. + */ + static float[] testSignal() { + Random random = new Random(11); + float[] x = new float[RATE]; + double b0 = 0, b1 = 0, b2 = 0; + for (int i = 0; i < x.length; i++) { + double w = random.nextGaussian(); + b0 = 0.99765 * b0 + w * 0.0990460; + b1 = 0.96300 * b1 + w * 0.2965164; + b2 = 0.57000 * b2 + w * 1.0526913; + double noise = (b0 + b1 + b2 + w * 0.1848) * 0.0012; + + double t = (double) i / RATE; + double voice = 0; + if (t >= 0.3 && t < 0.6) { + double envelope = Math.sin(Math.PI * (t - 0.3) / 0.3); + for (int h = 1; h <= 20; h++) { + voice += Math.sin(2 * Math.PI * 140 * h * t + h) / h; + } + voice *= 0.08 * envelope; + } + x[i] = (float) (noise + voice); + } + for (int frame : KEY_FRAMES) { + int start = frame * FRAME + 100; + for (int k = 0; k < 480; k++) { + x[start + k] += (float) (random.nextGaussian() * 0.1 * Math.exp(-k / 96.0)); + } + } + return x; + } + + private static float[] run(AudioProcessor processor, float[] input, Set keyFrames) { + float[] x = input.clone(); + float[] frame = new float[FRAME]; + for (int f = 0; f * FRAME + FRAME <= x.length; f++) { + if (keyFrames.contains(f)) processor.keyPressed(); + System.arraycopy(x, f * FRAME, frame, 0, FRAME); + processor.process(frame, FRAME); + System.arraycopy(frame, 0, x, f * FRAME, FRAME); + } + return x; + } + + private static void assertMatchesGolden(String name, float[] actual) throws IOException { + short[] golden = loadGolden(name); + assertEquals(golden.length, actual.length); + double maxDiff = 0; + double sumSquares = 0; + for (int i = 0; i < actual.length; i++) { + double d = actual[i] * 32768.0 - golden[i]; + maxDiff = Math.max(maxDiff, Math.abs(d)); + sumSquares += d * d; + } + double rms = Math.sqrt(sumSquares / actual.length); + // The reference is quantised to 16 bits, and float rounding differs slightly from + // upstream's: anything within a few LSB is the same signal. + assertTrue(maxDiff <= 4, name + ": max deviation " + maxDiff + " LSB"); + assertTrue(rms <= 0.6, name + ": RMS deviation " + rms + " LSB"); + } + + private static short[] loadGolden(String name) throws IOException { + try (InputStream in = AudioProcessorTest.class.getResourceAsStream(name)) { + assertNotNull(in, name); + ByteBuffer bytes = ByteBuffer.wrap(in.readAllBytes()).order(ByteOrder.LITTLE_ENDIAN); + short[] out = new short[bytes.remaining() / 2]; + bytes.asShortBuffer().get(out); + return out; + } + } + + @Test + void everythingOffPassesAudioThroughUntouched() { + float[] x = testSignal(); + assertArrayEquals(x, run(new AudioProcessor(), x, KEYS)); + } + + @Test + void noiseSuppressionMatchesWebRtcAtEveryLevel() throws IOException { + for (int level = 0; level <= 3; level++) { + AudioProcessor p = new AudioProcessor(); + p.setNoiseSuppression(true); + p.setSuppressionLevel(SuppressionLevel.fromDenoiserLevel(level)); + assertMatchesGolden("golden-ns" + level + ".s16", run(p, testSignal(), Set.of())); + } + } + + @Test + void typingAttenuationMatchesWebRtc() throws IOException { + AudioProcessor p = new AudioProcessor(); + p.setNoiseSuppression(true); + p.setSuppressionLevel(SuppressionLevel.DB_12); + p.setTransientSuppression(true); + assertMatchesGolden("golden-ns1-typing.s16", run(p, testSignal(), KEYS)); + } + + @Test + void typingAttenuationOnlyDelaysWithoutKeyPresses() { + float[] x = testSignal(); + AudioProcessor p = new AudioProcessor(); + p.setTransientSuppression(true); + float[] y = run(p, x, Set.of()); + int delay = 1024 - FRAME; + for (int i = delay; i < x.length; i++) { + assertEquals(x[i - delay], y[i], 0.0f); + } + } + + @Test + void gainControlRaisesQuietSpeechAndLeavesSilenceAlone() { + AudioProcessor p = new AudioProcessor(); + p.setGainControl(true); + float[] silence = run(p, new float[RATE], Set.of()); + for (float s : silence) assertEquals(0.0f, s, 0.0f); + + // 3 s of quiet voiced "words" at about -40 dBFS over a -70 dBFS noise floor. The + // pauses matter: without them AGC2 would take the voice for the noise floor. + Random random = new Random(5); + float[] quiet = new float[RATE * 3]; + for (int i = 0; i < quiet.length; i++) { + double t = (double) i / RATE; + double v = 0; + if (t % 0.5 < 0.3) { + for (int h = 1; h <= 20; h++) v += Math.sin(2 * Math.PI * 130 * h * t + h) / h; + v *= 0.004 * Math.sin(Math.PI * (t % 0.5) / 0.3); + } + quiet[i] = (float) (v + random.nextGaussian() * 0.0003); + } + float[] out = run(p, quiet, Set.of()); + assertTrue(rms(out, RATE * 2, RATE * 3) > 4 * rms(quiet, RATE * 2, RATE * 3), + "quiet speech should be raised by more than 12 dB"); + } + + @Test + void gainBoostLetsTheNoiseFloorRiseFurther() { + // -60 dBFS of noise alone: AGC2 starts at 15 dB of gain and, with no speech to + // raise it, can only lower it, down to what keeps the noise under its cap. + Random random = new Random(3); + float[] noise = new float[RATE * 3]; + for (int i = 0; i < noise.length; i++) noise[i] = (float) (random.nextGaussian() * 0.001); + + AudioProcessor plain = new AudioProcessor(); + plain.setGainControl(true); + AudioProcessor boosted = new AudioProcessor(); + boosted.setGainControl(true); + boosted.setGainBoost(20); + + double plainDb = 20 * Math.log10(rms(run(plain, noise, Set.of()), RATE * 2, RATE * 3)); + double boostedDb = 20 * Math.log10(rms(run(boosted, noise, Set.of()), RATE * 2, RATE * 3)); + assertEquals(-50, plainDb, 1.5, "the noise is held at AGC2's -50 dBFS cap"); + assertEquals(-45, boostedDb, 1.5, "with the cap 20 dB higher, the initial 15 dB of gain stays"); + } + + private static double rms(float[] x, int from, int to) { + double sum = 0; + for (int i = from; i < to; i++) sum += x[i] * x[i]; + return Math.sqrt(sum / (to - from)); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/vad/RealFftTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/vad/RealFftTest.java new file mode 100644 index 0000000..c8686a4 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/vad/RealFftTest.java @@ -0,0 +1,58 @@ +package eu.lixko.ts3j.client.audio.vad; + +import org.junit.jupiter.api.Test; + +import java.util.Random; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class RealFftTest { + + /** + * The rnn_vad transform length is 480 = 2^5 * 3 * 5, so the mixed-radix path has to be + * right for factors other than powers of two. + */ + @Test + void matchesDirectDftForMixedRadixLengths() { + for (int n : new int[]{480, 240, 512, 64, 60, 210, 100}) { + RealFft fft = new RealFft(n); + Random random = new Random(n); + float[] in = new float[n]; + float[] out = new float[n]; + for (int i = 0; i < n; i++) { + in[i] = (float) random.nextGaussian(); + } + fft.forward(in, out); + + for (int k = 0; k <= n / 2; k++) { + double re = 0; + double im = 0; + for (int t = 0; t < n; t++) { + double angle = -2 * Math.PI * k * t / n; + re += in[t] * Math.cos(angle); + im += in[t] * Math.sin(angle); + } + double gotRe; + double gotIm; + if (k == 0) { + gotRe = out[0]; + gotIm = 0; + } else if (k == n / 2) { + gotRe = out[1]; // Packed layout keeps Nyquist in slot 1. + gotIm = 0; + } else { + gotRe = out[2 * k]; + gotIm = out[2 * k + 1]; + } + assertEquals(re, gotRe, 1e-2, "n=" + n + " bin=" + k + " real"); + assertEquals(im, gotIm, 1e-2, "n=" + n + " bin=" + k + " imag"); + } + } + } + + @Test + void rejectsOddLengths() { + org.junit.jupiter.api.Assertions.assertThrows( + IllegalArgumentException.class, () -> new RealFft(481)); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/vad/RnnVadTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/vad/RnnVadTest.java new file mode 100644 index 0000000..5d1da68 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/audio/vad/RnnVadTest.java @@ -0,0 +1,129 @@ +package eu.lixko.ts3j.client.audio.vad; + +import org.junit.jupiter.api.Test; + +import java.util.Random; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Behavioural checks on the {@code rnn_vad} port. The network weights are the ones the TS3 + * client links, so these also pin the detector's agreement with it. + */ +class RnnVadTest { + + private static final int FRAMES = 60; + + @Test + void silenceScoresZero() { + float[] x = new float[RnnVad.FRAME_SIZE * FRAMES]; + double[] probabilities = run(x); + for (double p : probabilities) { + assertEquals(0.0, p, 0.0, "silence must not score above zero"); + } + } + + @Test + void voicedSpeechLikeSignalScoresHigh() { + float[] x = synth(FRAMES, t -> { + double sum = 0; + for (int h = 1; h <= 30 && 120 * h < 8000; h++) { + double f = 120 * h; + double gain = formant(f, 700, 90) + formant(f, 1220, 110) + formant(f, 2600, 160); + sum += gain * Math.sin(2 * Math.PI * f * t + h); + } + // A slow tremolo keeps it from looking like a stationary tone. + return 0.25 * (0.6 + 0.4 * Math.sin(2 * Math.PI * 5 * t)) * sum / 6.0; + }); + // Skip the first frames: the pitch buffer and GRU need history. + assertTrue(meanFrom(run(x), 20) > 0.8, "a voiced signal should score high"); + } + + @Test + void quietPinkNoiseScoresLow() { + Random random = new Random(3); + float[] x = new float[RnnVad.FRAME_SIZE * FRAMES]; + double b0 = 0; + double b1 = 0; + double b2 = 0; + for (int i = 0; i < x.length; i++) { + double w = random.nextGaussian(); + b0 = 0.99765 * b0 + w * 0.0990460; + b1 = 0.96300 * b1 + w * 0.2965164; + b2 = 0.57000 * b2 + w * 1.0526913; + // About -45 dBFS: representative of room tone rather than loud hiss. + x[i] = (float) ((b0 + b1 + b2 + w * 0.1848) * 0.0011); + } + assertTrue(meanFrom(run(x), 20) < 0.2, "quiet room tone should not read as speech"); + } + + @Test + void estimatesPitchPeriodExactly() { + // The pitch feature is fed to the network as 0.01 * (period48k - 300). + for (double f0 : new double[]{80, 100, 120, 150, 200, 250, 300, 400}) { + RnnVad vad = new RnnVad(); + float[] x = synth(FRAMES, t -> { + double sum = 0; + for (int h = 1; h <= 40 && f0 * h < 11000; h++) { + sum += Math.sin(2 * Math.PI * f0 * h * t) / h; + } + return 0.2 * sum; + }); + for (int f = 0; f < FRAMES; f++) { + vad.process(x, f * RnnVad.FRAME_SIZE); + } + assertEquals(48000 / f0, vad.pitchPeriod48kHz(), 1e-9, + "pitch period for f0=" + f0); + } + } + + @Test + void resetClearsState() { + float[] x = synth(FRAMES, t -> 0.3 * Math.sin(2 * Math.PI * 200 * t)); + RnnVad vad = new RnnVad(); + for (int f = 0; f < FRAMES; f++) { + vad.process(x, f * RnnVad.FRAME_SIZE); + } + assertTrue(vad.probability() > 0.0); + vad.reset(); + assertEquals(0.0, vad.probability(), 0.0); + } + + // ---- helpers ---- + + private interface Signal { + double at(double t); + } + + private static double formant(double f, double centre, double bandwidth) { + double d = (f - centre) / bandwidth; + return 1.0 / (1.0 + d * d); + } + + private static float[] synth(int frames, Signal signal) { + float[] x = new float[RnnVad.FRAME_SIZE * frames]; + for (int i = 0; i < x.length; i++) { + x[i] = (float) signal.at((double) i / RnnVad.SAMPLE_RATE); + } + return x; + } + + private static double[] run(float[] x) { + RnnVad vad = new RnnVad(); + int frames = x.length / RnnVad.FRAME_SIZE; + double[] probabilities = new double[frames]; + for (int i = 0; i < frames; i++) { + probabilities[i] = vad.process(x, i * RnnVad.FRAME_SIZE); + } + return probabilities; + } + + private static double meanFrom(double[] values, int start) { + double sum = 0; + for (int i = start; i < values.length; i++) { + sum += values[i]; + } + return sum / (values.length - start); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/chatlog/ChatLogStoreTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/chatlog/ChatLogStoreTest.java new file mode 100644 index 0000000..edb53da --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/chatlog/ChatLogStoreTest.java @@ -0,0 +1,99 @@ +package eu.lixko.ts3j.client.chatlog; + +import eu.lixko.ts3j.client.text.TextQuery; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ChatLogStoreTest { + + @TempDir + Path temp; + + @Test + void writesTs3CompatibleClientLogNamesAndEntries() throws Exception { + ChatLogStore logs = new ChatLogStore(temp, "+Tyg2JtxE8vRNZp+JiUBnmBh0MY="); + + logs.begin(); + logs.appendPrivateMessage("cckqISCrfr6Lq2SLMC//afsbO9w=", true, + 610, "bdrlePoB9hU8K8CyjCabY07t3Wo=", "ericek111", "hello"); + + Path serverDir = temp.resolve("K1R5ZzJKdHhFOHZSTlpwK0ppVUJubUJoME1ZPQ=="); + Path clientHtml = serverDir.resolve("clients") + .resolve("Y2NrcUlTQ3JmcjZMcTJTTE1DLy9hZnNiTzl3PQ==.html"); + Path clientTxt = serverDir.resolve("clients") + .resolve("Y2NrcUlTQ3JmcjZMcTJTTE1DLy9hZnNiTzl3PQ==.txt"); + + assertTrue(Files.isRegularFile(serverDir.resolve("server.html"))); + assertTrue(Files.isRegularFile(serverDir.resolve("channel.html"))); + assertTrue(Files.isRegularFile(clientHtml)); + assertEquals(1, Files.readAllLines(clientTxt).size()); + + List history = logs.privateHtmlHistory("cckqISCrfr6Lq2SLMC//afsbO9w="); + assertEquals(1, history.size()); + assertTrue(history.get(0).contains("TextMessage_Message")); + assertTrue(history.get(0).contains("ericek111")); + assertTrue(history.get(0).contains("hello")); + } + + @Test + void searchReachesPastTheLoadedHistory() throws Exception { + ChatLogStore logs = new ChatLogStore(temp, "+Tyg2JtxE8vRNZp+JiUBnmBh0MY="); + logs.appendMessage(ChatLogScope.CHANNEL, false, 5, "uid", "alice", "the needle is here"); + for (int i = 0; i < ChatLogStore.HISTORY_LIMIT; i++) { + logs.appendMessage(ChatLogScope.CHANNEL, false, 5, "uid", "alice", "filler " + i); + } + logs.appendServerEvent("a NEEDLE of the server"); + + assertTrue(logs.channelHtmlHistory().stream().noneMatch(e -> e.contains("needle"))); + ChatLogStore.SearchResult channel = logs.search(ChatLogScope.CHANNEL, null, + new TextQuery("needle", false, false, false), 10); + assertEquals(1, channel.total()); + assertTrue(channel.entries().get(0).contains("the needle is here")); + + ChatLogStore.SearchResult server = logs.search(ChatLogScope.SERVER, null, + new TextQuery("needle", true, false, false), 10); + assertEquals(0, server.total()); + + ChatLogStore.SearchResult capped = logs.search(ChatLogScope.CHANNEL, null, + new TextQuery("filler", false, false, false), 10); + assertEquals(ChatLogStore.HISTORY_LIMIT, capped.total()); + assertEquals(10, capped.entries().size()); + assertTrue(capped.truncated()); + assertTrue(capped.entries().get(9).contains("filler " + (ChatLogStore.HISTORY_LIMIT - 1))); + } + + @Test + void readsAMessageWithLineBreaksBackWhole() throws Exception { + ChatLogStore logs = new ChatLogStore(temp, "+Tyg2JtxE8vRNZp+JiUBnmBh0MY="); + logs.appendMessage(ChatLogScope.CHANNEL, false, 5, "uid", "alice", "first line\n\nthird line"); + logs.appendMessage(ChatLogScope.CHANNEL, false, 5, "uid", "bob", "reply"); + + List history = logs.channelHtmlHistory(); + assertEquals(2, history.size()); + assertTrue(history.get(0).contains("first line

    third line"), history.get(0)); + assertTrue(history.get(1).contains("reply")); + } + + @Test + void historyComesFromTheEndOfALongLog() throws Exception { + ChatLogStore logs = new ChatLogStore(temp, "+Tyg2JtxE8vRNZp+JiUBnmBh0MY="); + logs.appendMessage(ChatLogScope.CHANNEL, false, 5, "uid", "alice", "start"); + Path txt = logs.serverDir().resolve("channel.txt"); + StringBuilder filler = new StringBuilder(); + for (int i = 0; i < 200_000; i++) filler.append("<12:00:00> alice: žluťoučký kůň ").append(i).append('\n'); + Files.writeString(txt, filler, java.nio.file.StandardOpenOption.APPEND); + logs.appendMessage(ChatLogScope.CHANNEL, false, 5, "uid", "bob", "the latest"); + + List history = logs.channelHtmlHistory(); + assertEquals(ChatLogStore.HISTORY_LIMIT, history.size()); + assertTrue(history.get(history.size() - 1).contains("the latest")); + assertTrue(history.get(0).contains("žluťoučký kůň"), history.get(0)); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/config/IdentityStoreTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/config/IdentityStoreTest.java new file mode 100644 index 0000000..d8eb48c --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/config/IdentityStoreTest.java @@ -0,0 +1,72 @@ +package eu.lixko.ts3j.client.config; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +class IdentityStoreTest { + + @TempDir + Path dir; + + @BeforeEach + void freshProfile() { + AppDirs.init(dir.toFile(), dir.resolve("chats")); + } + + @AfterEach + void defaultProfile() { + AppDirs.init(null, null); + } + + @Test + void exportedIdentityImportsWithItsName() throws Exception { + IdentityStore store = IdentityStore.load(new Settings()); + IdentityEntry original = store.generate("Žofia's key", 0); + + ByteArrayOutputStream exported = new ByteArrayOutputStream(); + store.exportTo(original, exported); + IdentityEntry imported = store.importStream(new ByteArrayInputStream(exported.toByteArray()), null); + + assertEquals("Žofia's key", imported.getName()); + assertEquals(original.getUniqueId(), imported.getUniqueId()); + assertNotEquals(original.getId(), imported.getId()); + assertEquals(2, IdentityStore.load(new Settings()).all().size()); + } + + @Test + void nicknamesTravelWithTheIdentity() throws Exception { + IdentityStore store = IdentityStore.load(new Settings()); + IdentityEntry original = store.generate("Work", 0); + store.setNicknames(original, " Žofia ", "Zofia"); + + IdentityEntry reloaded = IdentityStore.load(new Settings()).byId(original.getId()); + assertEquals("Žofia", reloaded.getNickname()); + assertEquals("Zofia", reloaded.getPhoneticNickname()); + + ByteArrayOutputStream exported = new ByteArrayOutputStream(); + store.exportTo(original, exported); + IdentityEntry imported = store.importStream(new ByteArrayInputStream(exported.toByteArray()), null); + assertEquals("Žofia", imported.getNickname()); + assertEquals("Zofia", imported.getPhoneticNickname()); + } + + @Test + void givenNameWinsOverTheFilesOwn() throws Exception { + IdentityStore store = IdentityStore.load(new Settings()); + ByteArrayOutputStream exported = new ByteArrayOutputStream(); + store.exportTo(store.generate("First", 0), exported); + + IdentityEntry imported = store.importStream(new ByteArrayInputStream(exported.toByteArray()), "Second"); + + assertEquals("Second", imported.getName()); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/config/ProfileFilesTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/config/ProfileFilesTest.java new file mode 100644 index 0000000..60c8000 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/config/ProfileFilesTest.java @@ -0,0 +1,49 @@ +package eu.lixko.ts3j.client.config; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class ProfileFilesTest { + + @TempDir + Path dir; + + @Test + void replacesTheFileReadableByTheUserOnly() throws Exception { + File file = dir.resolve("settings.properties").toFile(); + Files.writeString(file.toPath(), "old"); + + ProfileFiles.write(file, out -> out.write("new".getBytes())); + + assertEquals("new", Files.readString(file.toPath())); + assertEquals("rw-------", PosixFilePermissions.toString(Files.getPosixFilePermissions(file.toPath()))); + try (var left = Files.list(dir)) { + assertEquals(1, left.count(), "no temporary file left behind"); + } + } + + @Test + void aFailedWriteLeavesTheOldFileAlone() throws Exception { + File file = dir.resolve("bookmarks.properties").toFile(); + Files.writeString(file.toPath(), "old"); + + assertThrows(IOException.class, () -> ProfileFiles.write(file, out -> { + out.write("half".getBytes()); + throw new IOException("crashed"); + })); + + assertEquals("old", Files.readString(file.toPath())); + try (var left = Files.list(dir)) { + assertEquals(1, left.count(), "no temporary file left behind"); + } + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/config/ServerLogSettingsTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/config/ServerLogSettingsTest.java new file mode 100644 index 0000000..53616ee --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/config/ServerLogSettingsTest.java @@ -0,0 +1,77 @@ +package eu.lixko.ts3j.client.config; + +import eu.lixko.ts3j.client.config.ServerLogSettings.Highlight; +import eu.lixko.ts3j.client.net.ServerLogEntry.Level; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Properties; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ServerLogSettingsTest { + + @Test + void whatIsStoredLoadsBack() { + ServerLogSettings saved = new ServerLogSettings(); + saved.levels.remove(Level.INFO); + saved.localTime = true; + saved.highlights.clear(); + saved.highlights.add(new Highlight("banned", 0x112233, null)); + saved.highlights.add(new Highlight("kicked", null, 0xABCDEF)); + saved.excludes.add("ping timeout"); + Properties p = new Properties(); + saved.store(p); + + ServerLogSettings loaded = new ServerLogSettings(); + loaded.load(p); + assertEquals(Set.of(Level.CRITICAL, Level.ERROR, Level.WARNING), loaded.levels); + assertTrue(loaded.localTime); + assertEquals(saved.highlights, loaded.highlights); + assertEquals(List.of("ping timeout"), loaded.excludes); + } + + @Test + void shorterListsLeaveNoStaleEntriesBehind() { + ServerLogSettings s = new ServerLogSettings(); + s.excludes.addAll(List.of("a", "b", "c")); + Properties p = new Properties(); + s.store(p); + s.excludes.clear(); + s.highlights.clear(); + s.store(p); + + assertTrue(p.stringPropertyNames().stream().noneMatch(k -> k.startsWith("serverLog.exclude."))); + assertTrue(p.stringPropertyNames().stream().noneMatch(k -> k.startsWith("serverLog.highlight."))); + ServerLogSettings loaded = new ServerLogSettings(); + loaded.load(p); + assertTrue(loaded.excludes.isEmpty()); + assertTrue(loaded.highlights.isEmpty()); + } + + @Test + void levelsAndExcludesDecideWhatShows() { + ServerLogSettings s = new ServerLogSettings(); + s.levels.remove(Level.INFO); + s.excludes.add("Ping Timeout"); + assertFalse(s.shows(Level.INFO, "client connected")); + assertTrue(s.shows(Level.WARNING, "something odd")); + assertFalse(s.shows(Level.WARNING, "dropping client because of ping timeout")); + assertTrue(s.shows(Level.DEBUG, "levels the window has no box for always show")); + } + + @Test + void theFirstMatchingKeywordWins() { + ServerLogSettings s = new ServerLogSettings(); + s.highlights.clear(); + s.highlights.add(new Highlight("error", 1, null)); + s.highlights.add(new Highlight("client", 2, null)); + assertEquals(1, s.highlightFor("ERROR client gone").foreground()); + assertEquals(2, s.highlightFor("client joined").foreground()); + assertNull(s.highlightFor("nothing here")); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/config/SettingsTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/config/SettingsTest.java new file mode 100644 index 0000000..525b9e4 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/config/SettingsTest.java @@ -0,0 +1,74 @@ +package eu.lixko.ts3j.client.config; + +import eu.lixko.ts3j.client.audio.InputLevel; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +class SettingsTest { + + @TempDir + Path dir; + + @BeforeEach + void freshProfile() { + AppDirs.init(dir.toFile(), dir.resolve("chats")); + } + + @AfterEach + void defaultProfile() { + AppDirs.init(null, null); + } + + @Test + void whatIsSavedLoadsBack() { + Settings saved = new Settings(); + saved.nickname = "Žofia"; + saved.inputMode = Settings.InputMode.PUSH_TO_TALK; + saved.vadMode = Settings.VadMode.AUTOMATIC; + saved.vadThresholdDb = -33.5; + saved.appearance = Settings.Appearance.DARK; + saved.whisperPolicy = Settings.WhisperPolicy.NOBODY; + saved.chatLogs = false; + saved.chatLogDir = "/somewhere/else"; + saved.save(); + + Settings loaded = Settings.load(); + assertEquals("Žofia", loaded.nickname); + assertEquals(Settings.InputMode.PUSH_TO_TALK, loaded.inputMode); + assertEquals(Settings.VadMode.AUTOMATIC, loaded.vadMode); + assertEquals(-33.5, loaded.vadThresholdDb); + assertEquals(Settings.Appearance.DARK, loaded.appearance); + assertEquals(Settings.WhisperPolicy.NOBODY, loaded.whisperPolicy); + assertFalse(loaded.chatLogs); + assertEquals("/somewhere/else", loaded.chatLogDir); + } + + @Test + void unknownValuesFallBackToDefaults() throws Exception { + Files.writeString(dir.resolve("settings.properties"), "inputMode=TELEPATHY\nvadMode=\n"); + Settings loaded = Settings.load(); + assertEquals(new Settings().inputMode, loaded.inputMode); + assertEquals(new Settings().vadMode, loaded.vadMode); + } + + @Test + void anOldDbfsThresholdIsConvertedOnce() throws Exception { + Files.writeString(dir.resolve("settings.properties"), "vadThresholdDb=-40.0\n"); + Settings loaded = Settings.load(); + double expected = InputLevel.powerToDb(Math.pow(10.0, -40.0 / 10.0)); + assertEquals(expected, loaded.vadThresholdDb, 1e-9); + + loaded.save(); + String saved = Files.readString(dir.resolve("settings.properties")); + assertFalse(saved.contains("vadThresholdDb"), "the old key is dropped once converted"); + assertEquals(expected, Settings.load().vadThresholdDb, 1e-9); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/contacts/ContactStoreTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/contacts/ContactStoreTest.java new file mode 100644 index 0000000..3690f55 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/contacts/ContactStoreTest.java @@ -0,0 +1,121 @@ +package eu.lixko.ts3j.client.contacts; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.time.LocalDateTime; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ContactStoreTest { + + @TempDir + File dir; + + @Test + void addsWithTheTypeDefaultsAndPersistsInTeamSpeakRecords() throws Exception { + File file = new File(dir, "contacts.txt"); + ContactStore store = new ContactStore(file); + ContactDefaults defaults = new ContactDefaults(); + defaults.of(ContactType.BLOCKED).ignorePokes = true; + defaults.of(ContactType.BLOCKED).ignoreWhisper = true; + defaults.of(ContactType.BLOCKED).nicknameDisplay = NicknameDisplay.ONLY_NICKNAME; + + AtomicInteger changes = new AtomicInteger(); + store.addListener(changes::incrementAndGet); + Contact bob = store.add("bob=", "Bob", ContactType.BLOCKED, defaults); + assertTrue(bob.ignorePokes); + assertTrue(!bob.whisperAllowed); + assertEquals(NicknameDisplay.ONLY_NICKNAME, bob.nicknameDisplay); + assertEquals("Bob2", store.displayName("bob=", "Bob2")); + bob.nicknameDisplay = NicknameDisplay.BOTH; + assertEquals("Bob (Bob2)", store.displayName("bob=", "Bob2")); + assertEquals(1, changes.get()); + + // Adding again only re-types; the edited flags stay. + bob.ignorePrivateMessages = true; + store.put(bob); + Contact again = store.add("bob=", "Other", ContactType.FRIEND, defaults); + assertTrue(again.ignorePrivateMessages); + assertEquals(ContactType.FRIEND, again.type); + assertEquals(ContactType.FRIEND, store.typeOf("bob=")); + assertNull(store.typeOf("nobody")); + + String text = Files.readString(file.toPath(), StandardCharsets.UTF_8); + assertTrue(text.startsWith("IDS=bob=\nNickname=Bob\nFriend=0\n"), text); + + ContactStore reloaded = new ContactStore(file); + reloaded.readFile(); + Contact back = reloaded.find("bob="); + assertNotNull(back); + assertTrue(back.ignorePrivateMessages); + assertEquals(ContactType.FRIEND, back.type); + } + + @Test + void markSeenRecordsOnceAMinute() { + ContactStore store = new ContactStore(new File(dir, "c.txt")); + store.add("a=", "A", ContactType.NEUTRAL, new ContactDefaults()); + AtomicInteger changes = new AtomicInteger(); + store.addListener(changes::incrementAndGet); + + store.markSeen("a=", "Server", "host:9987"); + store.markSeen("a=", "Server", "host:9987"); + store.markSeen("missing", "Server", "host:9987"); + assertEquals(1, changes.get()); + Contact a = store.find("a="); + assertEquals("Server", a.lastSeenServerName); + assertTrue(a.lastSeen.isAfter(LocalDateTime.now().minusMinutes(1))); + + store.markSeen("a=", "Other", "other:9987"); + assertEquals(2, changes.get()); + assertEquals("other:9987", a.lastSeenServerAddress); + } + + @Test + void sightingsWaitForTheNextSave() throws Exception { + File file = new File(dir, "s.txt"); + ContactStore store = new ContactStore(file); + store.add("a=", "A", ContactType.NEUTRAL, new ContactDefaults()); + long written = file.lastModified(); + String before = Files.readString(file.toPath(), StandardCharsets.UTF_8); + + store.markSeen("a=", "Server", "host:9987"); + assertEquals(before, Files.readString(file.toPath(), StandardCharsets.UTF_8)); + store.flush(); + assertTrue(Files.readString(file.toPath(), StandardCharsets.UTF_8).contains("LastSeenServerAddress=host:9987")); + + // An edit's save takes a waiting sighting along; the flush then has nothing left to write. + store.markSeen("a=", "Other", "other:9987"); + store.put(store.find("a=")); + assertTrue(Files.readString(file.toPath(), StandardCharsets.UTF_8).contains("LastSeenServerAddress=other:9987")); + assertTrue(file.setLastModified(written)); + store.flush(); + assertEquals(written, file.lastModified()); + } + + @Test + void mergeAddsNewAndOverwritesExisting() { + ContactStore store = new ContactStore(new File(dir, "m.txt")); + store.add("a=", "A", ContactType.NEUTRAL, new ContactDefaults()); + Contact importedA = new Contact("a="); + importedA.nickname = "A imported"; + importedA.type = ContactType.FRIEND; + Contact importedB = new Contact("b="); + importedB.nickname = "B"; + assertEquals(1, store.merge(List.of(importedA, importedB))); + assertEquals(2, store.all().size()); + assertEquals("A imported", store.find("a=").nickname); + assertEquals(ContactType.FRIEND, store.find("a=").type); + store.remove("a="); + assertEquals(1, store.all().size()); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/contacts/ContactTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/contacts/ContactTest.java new file mode 100644 index 0000000..9a4b25f --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/contacts/ContactTest.java @@ -0,0 +1,83 @@ +package eu.lixko.ts3j.client.contacts; + +import org.junit.jupiter.api.Test; + +import java.time.LocalDateTime; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ContactTest { + + @Test + void recordRoundTripsInTeamSpeakFormat() { + Contact c = new Contact("AbCdEfGh1234567890abcdefghijk="); + c.nickname = "Alice"; + c.type = ContactType.FRIEND; + c.automute = true; + c.ignorePokes = true; + c.nicknameDisplay = NicknameDisplay.ONLY_CUSTOM; + c.hasVolumeModifier = true; + c.volumeModifier = -6; + c.whisperAllowed = false; + c.phoneticNickname = "Ah-lees"; + c.lastSeen = LocalDateTime.of(2024, 3, 1, 18, 33, 34); + c.lastSeenServerName = "Test Server"; + c.lastSeenServerAddress = "server.lixko.eu:9987"; + + String record = c.toRecord(); + assertTrue(record.startsWith("IDS=AbCdEfGh1234567890abcdefghijk=\nNickname=Alice\nFriend=0\nAutomute=1\n")); + assertTrue(record.contains("\nVolumeModifier=-6\n")); + assertTrue(record.contains("\nWhisperAllow=0\n")); + assertTrue(record.contains("\nLastSeen=2024-03-01T18:33:34\n")); + + Contact parsed = Contact.parseRecord(record); + assertEquals(c.uniqueId, parsed.uniqueId); + assertEquals("Alice", parsed.nickname); + assertEquals(ContactType.FRIEND, parsed.type); + assertTrue(parsed.automute); + assertTrue(parsed.ignorePokes); + assertFalse(parsed.ignorePublicMessages); + assertEquals(NicknameDisplay.ONLY_CUSTOM, parsed.nicknameDisplay); + assertTrue(parsed.hasVolumeModifier); + assertEquals(-6.0, parsed.volumeModifier); + assertFalse(parsed.whisperAllowed); + assertEquals("Ah-lees", parsed.phoneticNickname); + assertEquals(c.lastSeen, parsed.lastSeen); + assertEquals("server.lixko.eu:9987", parsed.lastSeenServerAddress); + assertEquals(record, parsed.toRecord()); + } + + @Test + void missingFieldsFallBackToTeamSpeakDefaults() { + Contact c = Contact.parseRecord("IDS=abc=\nNickname=X\nFriend=1\n"); + assertEquals(ContactType.BLOCKED, c.type); + assertTrue(c.whisperAllowed); + assertEquals(NicknameDisplay.BOTH, c.nicknameDisplay); + assertNull(c.lastSeen); + assertNull(Contact.parseRecord("Nickname=nobody\n")); + } + + @Test + void displayNameFollowsTheShowType() { + Contact c = new Contact("u"); + c.nickname = "Custom"; + assertEquals("Custom (Live)", c.displayName("Live")); + assertEquals("Live", c.displayName("Live") == null ? null : NicknameDisplay.ONLY_NICKNAME.render("Custom", "Live")); + c.nicknameDisplay = NicknameDisplay.ONLY_CUSTOM; + assertEquals("Custom", c.displayName("Live")); + c.nickname = ""; + assertEquals("Live", c.displayName("Live")); + } + + @Test + void volumeModifierIsDecibels() { + Contact c = new Contact("u"); + assertEquals(1.0, c.volumeGain()); + c.hasVolumeModifier = true; + c.volumeModifier = -6; + assertEquals(0.501, c.volumeGain(), 0.001); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/gfx/CountryFlagsTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/gfx/CountryFlagsTest.java new file mode 100644 index 0000000..c715f32 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/gfx/CountryFlagsTest.java @@ -0,0 +1,22 @@ +package eu.lixko.ts3j.client.gfx; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class CountryFlagsTest { + + @Test + void namesCountriesInEnglishAndLeavesOddCodesAsTheyAre() { + assertEquals("Slovakia", CountryFlags.name("SK")); + assertEquals("Germany", CountryFlags.name("de")); + assertEquals("not a code", CountryFlags.name("not a code")); + } + + @Test + void hasNoFlagForNoCountry() { + assertNull(CountryFlags.png("")); + assertNull(CountryFlags.png(null)); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/gfx/IconPackTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/gfx/IconPackTest.java new file mode 100644 index 0000000..0522305 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/gfx/IconPackTest.java @@ -0,0 +1,160 @@ +package eu.lixko.ts3j.client.gfx; + +import eu.lixko.ts3j.client.net.ClientStatus; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.File; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class IconPackTest { + + private static final String INI = """ + [info] + name = Test Icons + + [options] + FALLBACK = false + + [gfxfiles] + # a comment + CONNECT = connect.svg + DISCONNECT = Disconnect.SVG + CHANNEL_GREEN= channel_green.png + MISSING = not_shipped.svg + EMPTY = + """; + + private static File zip(Path dir, String name, Map entries) throws Exception { + File file = dir.resolve(name).toFile(); + try (OutputStream out = Files.newOutputStream(file.toPath()); + ZipOutputStream zip = new ZipOutputStream(out)) { + for (Map.Entry e : entries.entrySet()) { + zip.putNextEntry(new ZipEntry(e.getKey())); + zip.write(e.getValue().getBytes(StandardCharsets.UTF_8)); + zip.closeEntry(); + } + } + return file; + } + + @Test + void readsTheMappingOfAModernPack(@TempDir Path dir) throws Exception { + IconPack pack = IconPack.load(zip(dir, "test_pack.zip", Map.of( + "settings.ini", INI, + "connect.svg", "", + "disconnect.svg", "disconnect", + "channel_green.png", "png bytes", + "emoticons/smile.svg", ""))); + assertNotNull(pack); + + assertEquals("test_pack.zip", pack.id()); + assertEquals("Test Icons", pack.name()); + assertFalse(pack.fallsBack()); + + assertArrayEquals("".getBytes(StandardCharsets.UTF_8), pack.icon("CONNECT", 16)); + assertTrue(pack.isVector("CONNECT", 16)); + assertFalse(pack.isVector("CHANNEL_GREEN", 16)); + // Keys are case-insensitive, as are the file names pack authors write. + assertArrayEquals("disconnect".getBytes(StandardCharsets.UTF_8), + pack.icon("disconnect", 16)); + + assertNull(pack.icon("MISSING", 16), "mapped to a file the pack does not ship"); + assertNull(pack.icon("EMPTY", 16)); + assertNull(pack.icon("NOT_IN_THE_PACK", 16)); + } + + @Test + void fallsBackByDefault(@TempDir Path dir) throws Exception { + IconPack pack = IconPack.load(zip(dir, "p.zip", Map.of( + "settings.ini", "[gfxfiles]\nCONNECT = connect.svg\n", + "connect.svg", ""))); + assertNotNull(pack); + assertTrue(pack.fallsBack()); + } + + @Test + void resolvesLegacyPacksByFileName(@TempDir Path dir) throws Exception { + IconPack pack = IconPack.load(zip(dir, "default.zip", Map.of( + "16x16_connect.png", "small", + "32x32_connect.png", "large", + "24x24_upload_avatar.png", "avatar", + "group_100.png", "group", + "emoticons/smile.png", "ignored"))); + assertNotNull(pack); + assertEquals("Default", pack.name()); + + // The smallest image that still covers the requested size wins. + assertArrayEquals("small".getBytes(StandardCharsets.UTF_8), pack.icon("CONNECT", 16)); + assertArrayEquals("large".getBytes(StandardCharsets.UTF_8), pack.icon("CONNECT", 32)); + assertArrayEquals("large".getBytes(StandardCharsets.UTF_8), pack.icon("CONNECT", 64)); + + assertArrayEquals("avatar".getBytes(StandardCharsets.UTF_8), pack.icon("UPLOAD_AVATAR", 16)); + assertArrayEquals("group".getBytes(StandardCharsets.UTF_8), pack.icon("GROUP_100", 16)); + assertFalse(pack.has("SMILE"), "emoticons are not icons of the user interface"); + } + + @Test + void readsUnpackedDirectories(@TempDir Path dir) throws Exception { + Path unpacked = Files.createDirectory(dir.resolve("my_icons")); + Files.writeString(unpacked.resolve("settings.ini"), "[gfxfiles]\nCONNECT = connect.svg\n"); + Files.writeString(unpacked.resolve("connect.svg"), ""); + + IconPack pack = IconPack.load(unpacked.toFile()); + assertNotNull(pack); + assertEquals("My Icons", pack.name()); + assertArrayEquals("".getBytes(StandardCharsets.UTF_8), pack.icon("CONNECT", 16)); + } + + @Test + void ignoresWhatIsNotAPack(@TempDir Path dir) throws Exception { + assertNull(IconPack.load(dir.resolve("nope.zip").toFile())); + assertNull(IconPack.load(Files.createDirectory(dir.resolve("empty")).toFile())); + assertNull(IconPack.load(null)); + } + + @Test + void shipsAMaterialPackForEveryIconTheTreeDraws() { + IconPack pack = IconPacks.material(); + assertNotNull(pack); + assertEquals("Material", pack.name()); + assertFalse(pack.fallsBack()); + assertNull(pack.source()); + for (ClientStatus status : ClientStatus.values()) { + String key = IconKeys.client(status); + assertTrue(pack.isVector(key, 16), key); + assertNotNull(pack.icon(key, 16), key); + } + for (boolean password : new boolean[]{false, true}) { + for (boolean full : new boolean[]{false, true}) { + for (boolean subscribed : new boolean[]{false, true}) { + for (String key : IconKeys.channel(password, full, subscribed)) { + assertNotNull(pack.icon(key, 16), key); + } + } + } + } + } + + @Test + void setsTheColourVectorArtPaintsWith() { + byte[] svg = "".getBytes(StandardCharsets.UTF_8); + assertEquals("", + new String(IconPack.withCurrentColor(svg, 0xFF0A0B0C), StandardCharsets.UTF_8)); + byte[] fixed = "".getBytes(StandardCharsets.UTF_8); + assertTrue(fixed == IconPack.withCurrentColor(fixed, 0)); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/hotkey/HotkeyEngineTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/hotkey/HotkeyEngineTest.java new file mode 100644 index 0000000..1e9b82d --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/hotkey/HotkeyEngineTest.java @@ -0,0 +1,120 @@ +package eu.lixko.ts3j.client.hotkey; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class HotkeyEngineTest { + + private static final HotkeyKey CTRL = HotkeyKey.keyboard(37); + private static final HotkeyKey K = HotkeyKey.keyboard(45); + private static final HotkeyKey MOUSE4 = HotkeyKey.mouse(8); + + private final List fired = new ArrayList<>(); + private final Hotkeys hotkeys = new Hotkeys(); + private final HotkeyEngine engine = new HotkeyEngine(hotkeys, + (hotkey, active) -> fired.add(hotkey.action + (active ? ":on" : ":off"))); + + private Hotkey bind(HotkeyAction action, Hotkey.Trigger trigger, HotkeyKey... keys) { + Hotkey h = new Hotkey(action, new HotkeyCombo(List.of(keys))); + h.trigger = trigger; + hotkeys.add(h); + return h; + } + + @Test + void firesOnKeyDownOnlyWhenEveryKeyIsHeld() { + bind(HotkeyAction.MIC_TOGGLE, Hotkey.Trigger.KEY_DOWN, CTRL, K); + + engine.onInput(K, true); + assertTrue(fired.isEmpty(), "one key of the combination is not enough"); + engine.onInput(CTRL, true); + assertEquals(List.of("MIC_TOGGLE:on"), fired); + + // Releasing and re-pressing arms it again, but only once per completion. + engine.onInput(CTRL, false); + engine.onInput(CTRL, true); + assertEquals(List.of("MIC_TOGGLE:on", "MIC_TOGGLE:on"), fired); + } + + @Test + void keyUpTriggerFiresOnRelease() { + bind(HotkeyAction.SPEAKER_TOGGLE, Hotkey.Trigger.KEY_UP, MOUSE4); + + engine.onInput(MOUSE4, true); + assertTrue(fired.isEmpty()); + engine.onInput(MOUSE4, false); + assertEquals(List.of("SPEAKER_TOGGLE:on"), fired); + } + + @Test + void momentaryActionReportsPressAndRelease() { + bind(HotkeyAction.PTT_ACTIVATE, Hotkey.Trigger.KEY_UP, MOUSE4); + + engine.onInput(MOUSE4, true); + engine.onInput(MOUSE4, false); + // The trigger setting does not apply: push-to-talk always spans the hold. + assertEquals(List.of("PTT_ACTIVATE:on", "PTT_ACTIVATE:off"), fired); + } + + @Test + void disabledAndUnsupportedBindingsStaySilent() { + bind(HotkeyAction.MIC_TOGGLE, Hotkey.Trigger.KEY_DOWN, K).enabled = false; + bind(HotkeyAction.RECORDING_START, Hotkey.Trigger.KEY_DOWN, MOUSE4); + + engine.onInput(K, true); + engine.onInput(MOUSE4, true); + assertTrue(fired.isEmpty()); + } + + @Test + void recordingCapturesTheCombinationInsteadOfFiring() { + bind(HotkeyAction.MIC_TOGGLE, Hotkey.Trigger.KEY_DOWN, K); + List recorded = new ArrayList<>(); + engine.record(new HotkeyEngine.Recorder() { + @Override + public void onRecording(HotkeyCombo combo) { + } + + @Override + public void onRecorded(HotkeyCombo combo) { + recorded.add(combo); + } + }); + + engine.onInput(CTRL, true); + engine.onInput(K, true); + engine.onInput(K, false); + engine.onInput(CTRL, false); + + assertTrue(fired.isEmpty(), "bindings must not fire while recording"); + assertEquals(1, recorded.size()); + assertEquals(List.of(CTRL, K), recorded.get(0).keys()); + } + + @Test + void actionsCarryTeamSpeaksTreeGrouping() { + assertEquals("Sounds", HotkeyAction.SOUNDPACK_ACTIVATE.group()); + assertEquals("Microphone", HotkeyAction.MIC_TOGGLE.group()); + // TS3 leaves a handful of actions ungrouped, listed straight under their category. + assertEquals("", HotkeyAction.NICKNAME_CHANGE.group()); + assertEquals("", HotkeyAction.BRING_TO_FRONT.group()); + + Hotkey pack = new Hotkey(HotkeyAction.SOUNDPACK_ACTIVATE, new HotkeyCombo(List.of(K))); + pack.argument = "Default Sound Pack (Male)"; + assertEquals("Sounds / Activate Soundpack / Default Sound Pack (Male)", pack.path()); + assertEquals("Bring Client to Front", + new Hotkey(HotkeyAction.BRING_TO_FRONT, new HotkeyCombo(List.of(K))).path()); + } + + @Test + void combinationsSurviveARoundTripThroughText() { + HotkeyCombo combo = new HotkeyCombo(List.of(CTRL, MOUSE4)); + assertEquals("Keyboard:37+Mouse:8", combo.toString()); + assertEquals(combo, HotkeyCombo.parse(combo.toString())); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/AccountInfoTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/AccountInfoTest.java new file mode 100644 index 0000000..b1acfc1 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/AccountInfoTest.java @@ -0,0 +1,33 @@ +package eu.lixko.ts3j.client.myts; + +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class AccountInfoTest { + + private static String base32(String text) { + return AccountInfo.base32(text.getBytes(StandardCharsets.US_ASCII)); + } + + @Test + void encodesRfc4648VectorsLowercaseAndUnpadded() { + assertEquals("", base32("")); + assertEquals("my", base32("f")); + assertEquals("mzxq", base32("fo")); + assertEquals("mzxw6", base32("foo")); + assertEquals("mzxw6yq", base32("foob")); + assertEquals("mzxw6ytb", base32("fooba")); + assertEquals("mzxw6ytboi", base32("foobar")); + } + + @Test + void toleratesAReplyWithoutIdentityData() { + AccountInfo info = AccountInfo.of("tester", "u", null, 0); + assertEquals("", info.userId()); + assertNull(info.created()); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/ChatAttachmentTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/ChatAttachmentTest.java new file mode 100644 index 0000000..321c971 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/ChatAttachmentTest.java @@ -0,0 +1,69 @@ +package eu.lixko.ts3j.client.myts; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ChatAttachmentTest { + + /** As TeamSpeak 6 sends it: JSON.stringify of its object, keys in this order. */ + private static final String TS6_MESSAGE = "{\"msg_type\":\"ts.file.myts\",\"file_id\":\"YWx1aW1hZWJp\"," + + "\"chat_user_id\":\"@agl7x5qxz7h7pqrfz7xyzedmlkbpstkbbkxw7gxltefsa3p7eexri===:chat-1.tmspk.net\"," + + "\"file_name\":\"cat picture.PNG\",\"file_size\":532,\"body\":\"cat picture.PNG\",\"v2\":true}"; + + @Test + void readsTheMessageTeamSpeak6Sends() { + ChatAttachment a = ChatAttachment.parse(TS6_MESSAGE); + assertEquals("YWx1aW1hZWJp", a.fileId()); + assertEquals("agl7x5qxz7h7pqrfz7xyzedmlkbpstkbbkxw7gxltefsa3p7eexri===", a.senderUserId()); + assertEquals("cat picture.PNG", a.fileName()); + assertEquals(532, a.fileSize()); + assertTrue(a.isImage()); + assertEquals("", a.caption()); + } + + @Test + void writesWhatItReads() { + assertEquals(TS6_MESSAGE, ChatAttachment.parse(TS6_MESSAGE).toMessage()); + } + + @Test + void namesItsSenderAsTeamSpeak6Does() { + ChatAttachment a = ChatAttachment.of("id", "aeqlaxceldn5xjqkgnzdd3bjsxety4k46mzr7v5sd4xwtpyv5yfm2", "a.txt", 3); + assertEquals("@aeqlaxceldn5xjqkgnzdd3bjsxety4k46mzr7v5sd4xwtpyv5yfm2===:chat-1.tmspk.net", a.senderChatId()); + assertFalse(a.isImage()); + ChatAttachment back = ChatAttachment.parse(a.toMessage()); + assertEquals(a, back); + } + + @Test + void keepsQuotesAndBracketsInNames() { + ChatAttachment a = new ChatAttachment("f", "@u:h", "say \"hi\" [b]x[/b].gif", 1, "line\nbreak"); + assertEquals(a, ChatAttachment.parse(a.toMessage())); + assertEquals("line\nbreak", a.caption()); + } + + @Test + void ignoresOtherMessages() { + assertNull(ChatAttachment.parse("hello")); + assertNull(ChatAttachment.parse("{\"msg_type\":\"ts.file.myts\"}")); + assertNull(ChatAttachment.parse("{\"msg_type\":\"other\",\"file_id\":\"a\",\"chat_user_id\":\"@b:c\"} ts.file.myts")); + assertNull(ChatAttachment.parse("{\"msg_type\":\"ts.file.myts\", broken")); + } + + @Test + void hrefNamesEverythingNeededToFetchIt() { + ChatAttachment a = ChatAttachment.parse(TS6_MESSAGE); + String href = a.href("+Tyg2JtxE8vRNZp/JiUBnmBh0MY="); + assertTrue(ChatAttachment.isHref(href)); + ChatAttachment.Ref ref = ChatAttachment.Ref.parse(href); + assertEquals("+Tyg2JtxE8vRNZp/JiUBnmBh0MY=", ref.room()); + assertEquals(a.senderUserId(), ref.owner()); + assertEquals("YWx1aW1hZWJp", ref.fileId()); + assertEquals("cat picture.PNG", ref.fileName()); + assertFalse(href.contains(" ")); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/MyTeamSpeakLoginTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/MyTeamSpeakLoginTest.java new file mode 100644 index 0000000..798e053 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/MyTeamSpeakLoginTest.java @@ -0,0 +1,65 @@ +package eu.lixko.ts3j.client.myts; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class MyTeamSpeakLoginTest { + + @Test + void staysSignedInWithoutKeepingThePassword(@TempDir File dir) throws Exception { + File file = new File(dir, "myteamspeak.properties"); + MyTeamSpeakTest.ReplayServer server = new MyTeamSpeakTest.ReplayServer(); + MyTeamSpeakLogin login = new MyTeamSpeakLogin(file, new MyTeamSpeak(server)); + assertFalse(login.isSignedIn()); + + login.signIn(MyTsCryptoTest.EMAIL, MyTsCryptoTest.PASSWORD); + assertTrue(login.isSignedIn()); + assertEquals("tester", login.username()); + assertFalse(Files.readString(file.toPath(), StandardCharsets.ISO_8859_1).contains(MyTsCryptoTest.PASSWORD)); + + MyTeamSpeakLogin restarted = new MyTeamSpeakLogin(file, new MyTeamSpeak(server)); + assertTrue(restarted.isSignedIn()); + assertEquals(MyTsCryptoTest.EMAIL, restarted.email()); + assertEquals("tester", restarted.username()); + assertEquals(1, restarted.fetch().bookmarks()); + + restarted.signOut(); + assertFalse(file.exists()); + assertFalse(restarted.isSignedIn()); + } + + @Test + void aFailedSignInKeepsNothing(@TempDir File dir) { + File file = new File(dir, "myteamspeak.properties"); + MyTeamSpeakTest.ReplayServer server = new MyTeamSpeakTest.ReplayServer(); + server.loginError = MyTsException.LOGIN_FAILED; + MyTeamSpeakLogin login = new MyTeamSpeakLogin(file, new MyTeamSpeak(server)); + + assertThrows(MyTsException.class, () -> login.signIn(MyTsCryptoTest.EMAIL, "wrong")); + assertFalse(login.isSignedIn()); + assertFalse(file.exists()); + } + + @Test + void signsOutWhenThePasswordChangedElsewhere(@TempDir File dir) throws Exception { + File file = new File(dir, "myteamspeak.properties"); + MyTeamSpeakTest.ReplayServer server = new MyTeamSpeakTest.ReplayServer(); + MyTeamSpeakLogin login = new MyTeamSpeakLogin(file, new MyTeamSpeak(server)); + login.signIn(MyTsCryptoTest.EMAIL, MyTsCryptoTest.PASSWORD); + + server.loginError = MyTsException.LOGIN_FAILED; + MyTsException e = assertThrows(MyTsException.class, login::fetch); + assertTrue(e.credentialsRejected()); + assertFalse(login.isSignedIn()); + assertFalse(file.exists()); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/MyTeamSpeakTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/MyTeamSpeakTest.java new file mode 100644 index 0000000..1076d2a --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/MyTeamSpeakTest.java @@ -0,0 +1,125 @@ +package eu.lixko.ts3j.client.myts; + +import eu.lixko.ts3j.client.proto.ProtobufReader; +import eu.lixko.ts3j.client.proto.ProtobufWriter; +import eu.lixko.ts3j.client.teamspeak.SyncItem; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class MyTeamSpeakTest { + + private static final String SESSION = "00000000-1111-2222-3333-444444444444"; + + static MyTeamSpeak.Credentials credentials(String password) throws MyTsException { + return MyTeamSpeak.Credentials.derive(MyTsCryptoTest.EMAIL, password); + } + + /** Replays the captured account: answers each call and records it. */ + static final class ReplayServer implements MyTsTransport { + final List calls = new ArrayList<>(); + int loginError = 200; + String loginToken; + + @Override + public byte[] call(String endpoint, String method, byte[] request) throws IOException { + calls.add(endpoint + "/" + method); + return switch (method) { + case "login" -> login(request); + case "requestServerItems" -> items(request); + default -> new byte[0]; + }; + } + + private byte[] login(byte[] request) throws IOException { + ProtobufReader r = new ProtobufReader(request); + while (r.next()) { + if (r.fieldNumber() == 2) loginToken = r.readString(); + else r.skip(); + } + if (loginError != 200) return new ProtobufWriter().varint(5, loginError).toByteArray(); + return new ProtobufWriter() + .bytes(1, MyTsCryptoTest.KEY_PACKAGE) + .string(2, SESSION) + .varint(5, 200) + .string(4, "828613f7-3cde-45e6-993e-c57ee979a39f") + .string(8, "tester") + .message(9, new ProtobufWriter().varint(3, 1_770_000_000L) + .bytes(4, java.util.HexFormat.of().parseHex( + "0120b05c4b1a2d3e4f5061728394a5b6c7d8e9f00112233445566778899aabbccd"))) + .toByteArray(); + } + + private byte[] items(byte[] request) throws IOException { + ProtobufReader r = new ProtobufReader(request); + while (r.next()) { + if (r.fieldNumber() == 1) assertEquals(SESSION, r.readString()); + else r.skip(); + } + try { + ProtobufWriter bookmark = new ProtobufWriter() + .string(1, "43c5d058-4803-3cd8-b844-15fdcc92e730") + .string(2, "5d831e3c-d5aa-0e66-7af2-a0feb13af048") + .bytes(3, MyTsCryptoTest.itemFrame()); + ProtobufWriter tombstone = new ProtobufWriter().string(1, "gone").varint(4, 1); + // Sent though not asked for, and in the clear. + ProtobufWriter addOn = new ProtobufWriter() + .string(1, "38aa56e2-55ae-b37a-a7db-7a11832a9812") + .bytes(3, new ProtobufWriter().string(2, "38aa56e2-55ae-b37a-a7db-7a11832a9812") + .varint(6, 4).toByteArray()); + return new ProtobufWriter() + .varint(1, 301) + .message(2, new ProtobufWriter().varint(1, 0).string(2, "v").message(3, bookmark).message(3, tombstone)) + .message(2, new ProtobufWriter().varint(1, 1).varint(4, 1)) + .message(2, new ProtobufWriter().varint(1, 4).string(2, "v").message(3, addOn)) + .string(3, "g") + .toByteArray(); + } catch (java.security.GeneralSecurityException e) { + throw new AssertionError(e); + } + } + } + + @Test + void downloadsAndDecryptsTheAccount() throws Exception { + ReplayServer server = new ReplayServer(); + MyTeamSpeak.Account account = new MyTeamSpeak(server).download(credentials(MyTsCryptoTest.PASSWORD)); + + assertEquals("tester", account.username()); + assertEquals("828613f7-3cde-45e6-993e-c57ee979a39f", account.info().uuid()); + assertEquals(java.time.Instant.ofEpochSecond(1_770_000_000L), account.info().created()); + assertEquals("aeqlaxcldiwt4t2qmfzihfffw3d5r2pqaejcgncfkztxrcm2vo6m2", account.info().userId()); + assertEquals(1, account.items().size()); + SyncItem.Bookmark bookmark = assertInstanceOf(SyncItem.Bookmark.class, account.items().get(0)); + assertEquals("server.lixko.eu", bookmark.address()); + assertEquals(9987, bookmark.port()); + assertEquals("niger", bookmark.nickname()); + assertEquals(MyTsCryptoTest.LOGIN_TOKEN, server.loginToken); + assertEquals(List.of("authentication/login", "synchronization/requestServerItems", + "authentication/deleteSession"), server.calls); + } + + @Test + void reportsAWrongPassword() { + ReplayServer server = new ReplayServer(); + server.loginError = 202; + MyTsException e = assertThrows(MyTsException.class, + () -> new MyTeamSpeak(server).download(credentials("wrong"))); + assertEquals(202, e.code()); + assertEquals(List.of("authentication/login"), server.calls); + } + + @Test + void signsOutWhenTheKeyDoesNotOpen() { + // The server accepted the login token but the key does not open with this password. + ReplayServer server = new ReplayServer(); + assertThrows(MyTsException.class, () -> new MyTeamSpeak(server).download(credentials("other"))); + assertEquals("authentication/deleteSession", server.calls.get(server.calls.size() - 1)); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/MyTsCryptoTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/MyTsCryptoTest.java new file mode 100644 index 0000000..25a1625 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/MyTsCryptoTest.java @@ -0,0 +1,117 @@ +package eu.lixko.ts3j.client.myts; + +import org.junit.jupiter.api.Test; + +import javax.crypto.Cipher; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.HexFormat; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Vectors from the official client (see CRYPTO_RE_SALT.md). The sign-in sample is a login the client + * computed for an address with no account; the item is a real captured one with its item key. + */ +class MyTsCryptoTest { + + static final String EMAIL = "probe.nobody@example.com"; + static final String PASSWORD = "wrongpassword1"; + static final String LOGIN_TOKEN = "kJLau9cQuYPQi/hi0ey4dPBChwvTMhz2lfAYHWQnNNtaVffCzHHac8mIFVb2FpN4"; + static final byte[] ITEM_KEY = hex("22efa5d631ddaa11ec97ccb82846b4d24598a9376319f444b5065cd47b391b2d"); + + /** {@code LoginSession.key} sealing {@link #ITEM_KEY} for {@link #EMAIL}, laid out as the server sends it. */ + static final byte[] KEY_PACKAGE = keyPackage(); + + /** A bookmark: server.lixko.eu:9987, nickname "niger". */ + static final byte[] ITEM_DATA = hex("122434336335643035382d343830332d336364382d623834342d3135666463633932653733301a24" + + "64373663663736312d316163332d373434662d366234312d36363633386362643165303320003000" + + "3a00420048f7f5dbd506820189010a19457269c48d516f76205465616d537065616b207365727665" + + "72120f7365727665722e6c69786b6f2e657518834e22056e696765722a00320744656661756c743a" + + "0042004a0050005a0744656661756c74620744656661756c746a0070007a1c2b547967324a747845" + + "3876524e5a702b4a6955426e6d4268304d593d8a0100900100980100b00101"); + + /** The capture cut the frame 37 bytes into its SHA-512 trailer, so the test completes it. */ + static byte[] itemFrame() throws GeneralSecurityException { + byte[] captured = hex("1114428e2059c038f339b1c1a6bc4eb0eac1f4479ec2764ea53c0b4dd0fc4626" + + "4642cab8908d295933fac43152154f58990909e933d899b86d4776ae8c52f61575b33932d4667fc3f" + + "b50e78a2a056dc6c8cd74e3e2446275e0d351c7139bc686a3555b4dd3dd6fdfae1c7176e84f99b3" + + "0df52dbe9b95e28d9545e2dd3188fec7e34ac233fb7de6d21db8795a45186ff91a01d23189d072d6" + + "afb60cad9b1c834e35acf04006daa1d6e439750afaa00a4c63e53f10cf54d2820108c1b859b394d0" + + "ba7d80b38de402b631da9ba4daedbff4d9de85cdeae7466b516ac5abe9af4d43e9df1c9bf8951d1" + + "2e9f5c42ce7cf802443d4bc051902164ec510126130dd962e54778518ae0a44947e6dd19975eef8b" + + "33ce8"); + byte[] hash = MessageDigest.getInstance("SHA-512").digest(ITEM_DATA); + byte[] frame = Arrays.copyOf(captured, 16 + ITEM_DATA.length + hash.length); + System.arraycopy(hash, 0, frame, 16 + ITEM_DATA.length, hash.length); + return frame; + } + + @Test + void derivesTheOfficialLoginToken() throws GeneralSecurityException { + assertEquals(LOGIN_TOKEN, MyTsCrypto.loginToken(EMAIL, PASSWORD)); + } + + @Test + void emailCaseDoesNotMatter() throws GeneralSecurityException { + assertEquals(LOGIN_TOKEN, MyTsCrypto.loginToken("Probe.Nobody@EXAMPLE.com", PASSWORD)); + } + + /** The same construction opened a real account's key; this pins it for the sample address. */ + @Test + void derivesTheAccountKey() throws GeneralSecurityException { + assertArrayEquals(hex("f0e2ba6d60d69c8eb6bb9e56f0093490db7379b3f4df5475599ddad2a750d00d"), + MyTsCrypto.accountKey(EMAIL, PASSWORD)); + } + + @Test + void unwrapsTheItemKey() throws GeneralSecurityException { + assertArrayEquals(ITEM_KEY, MyTsCrypto.unwrapItemKey(MyTsCrypto.accountKey(EMAIL, PASSWORD), KEY_PACKAGE)); + } + + @Test + void wrongPasswordCannotUnwrap() throws GeneralSecurityException { + byte[] accountKey = MyTsCrypto.accountKey(EMAIL, "not the password"); + assertThrows(GeneralSecurityException.class, () -> MyTsCrypto.unwrapItemKey(accountKey, KEY_PACKAGE)); + } + + @Test + void decryptsAnItem() throws GeneralSecurityException { + assertArrayEquals(ITEM_DATA, MyTsCrypto.decryptItem(itemFrame(), ITEM_KEY)); + } + + @Test + void rejectsATamperedItem() throws GeneralSecurityException { + byte[] frame = itemFrame(); + frame[40] ^= 1; + assertThrows(GeneralSecurityException.class, () -> MyTsCrypto.decryptItem(frame, ITEM_KEY)); + } + + /** {@code 02 || tag || iv || ciphertext}; JCA puts the tag last, the server first. */ + private static byte[] keyPackage() { + try { + byte[] iv = hex("0102030405060708090a0b0c"); + Cipher gcm = Cipher.getInstance("AES/GCM/NoPadding"); + gcm.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(MyTsCrypto.accountKey(EMAIL, PASSWORD), "AES"), + new GCMParameterSpec(128, iv)); + byte[] sealed = gcm.doFinal(ITEM_KEY); + byte[] out = new byte[1 + 16 + 12 + 32]; + out[0] = 2; + System.arraycopy(sealed, 32, out, 1, 16); + System.arraycopy(iv, 0, out, 17, 12); + System.arraycopy(sealed, 0, out, 29, 32); + return out; + } catch (GeneralSecurityException e) { + throw new AssertionError(e); + } + } + + static byte[] hex(String s) { + return HexFormat.of().parseHex(s); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/MyTsFilesTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/MyTsFilesTest.java new file mode 100644 index 0000000..c725722 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/myts/MyTsFilesTest.java @@ -0,0 +1,88 @@ +package eu.lixko.ts3j.client.myts; + +import eu.lixko.ts3j.client.proto.ProtobufReader; +import eu.lixko.ts3j.client.proto.ProtobufWriter; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class MyTsFilesTest { + + /** The account replay, plus the file service: hands out made-up addresses. */ + static final class FileServer implements MyTsTransport { + final MyTeamSpeakTest.ReplayServer accounts = new MyTeamSpeakTest.ReplayServer(); + final List requests = new ArrayList<>(); + int expireNext; + + @Override + public byte[] call(String endpoint, String method, byte[] request) throws IOException, MyTsException { + if (!endpoint.equals("user")) return accounts.call(endpoint, method, request); + accounts.calls.add(endpoint + "/" + method); + if (expireNext > 0) { + expireNext--; + return new ProtobufWriter().varint(2, 109).toByteArray(); + } + ProtobufReader r = new ProtobufReader(request); + StringBuilder fields = new StringBuilder(method); + while (r.next()) fields.append(' ').append(r.fieldNumber()).append('=').append(r.readString()); + requests.add(fields.toString()); + return new ProtobufWriter().varint(1, 1).string(5, "file1").string(6, "https://store/" + method) + .toByteArray(); + } + } + + private static MyTsFiles signedIn(File dir, FileServer server) throws Exception { + MyTeamSpeakLogin login = new MyTeamSpeakLogin(new File(dir, "myts.properties"), new MyTeamSpeak(server)); + login.signIn(MyTsCryptoTest.EMAIL, MyTsCryptoTest.PASSWORD); + server.accounts.calls.clear(); + return new MyTsFiles(login, new MyTeamSpeak(server)); + } + + @Test + void asksUnderTheAccountsIdAndKeepsTheSession(@TempDir File dir) throws Exception { + FileServer server = new FileServer(); + MyTsFiles files = signedIn(dir, server); + + MyTsFiles.Upload upload = files.requestUpload("room="); + assertEquals("file1", upload.fileId()); + assertEquals("aeqlaxcldiwt4t2qmfzihfffw3d5r2pqaejcgncfkztxrcm2vo6m2===", upload.senderUserId()); + assertEquals("https://store/requestDownloadFile", files.requestDownload("owner", "room=", "file9")); + + String session = "00000000-1111-2222-3333-444444444444"; + assertEquals(List.of("requestUploadFile 1=" + session + " 2=" + upload.senderUserId() + " 3=room=", + "requestDownloadFile 1=" + session + " 2=owner 3=room= 4=file9"), server.requests); + assertEquals(List.of("authentication/login", "user/requestUploadFile", "user/requestDownloadFile"), + server.accounts.calls); + + files.close(); + assertEquals("authentication/deleteSession", server.accounts.calls.get(3)); + } + + @Test + void signsInAgainWhenTheSessionRanOut(@TempDir File dir) throws Exception { + FileServer server = new FileServer(); + MyTsFiles files = signedIn(dir, server); + files.requestUpload("room"); + server.expireNext = 1; + server.accounts.calls.clear(); + + files.requestUpload("room"); + assertEquals(List.of("user/requestUploadFile", "authentication/login", "user/requestUploadFile"), + server.accounts.calls); + } + + @Test + void needsASignIn(@TempDir File dir) { + FileServer server = new FileServer(); + MyTeamSpeakLogin login = new MyTeamSpeakLogin(new File(dir, "myts.properties"), new MyTeamSpeak(server)); + MyTsFiles files = new MyTsFiles(login, new MyTeamSpeak(server)); + assertThrows(MyTsException.class, () -> files.requestUpload("room")); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ConnectionEventHandlerTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ConnectionEventHandlerTest.java new file mode 100644 index 0000000..cba0eb7 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ConnectionEventHandlerTest.java @@ -0,0 +1,211 @@ +package eu.lixko.ts3j.client.net; + +import com.github.manevolent.ts3j.command.MultiCommand; +import com.github.manevolent.ts3j.event.ChannelCreateEvent; +import com.github.manevolent.ts3j.event.ChannelDeletedEvent; +import com.github.manevolent.ts3j.event.ChannelEditedEvent; +import com.github.manevolent.ts3j.event.ChannelMovedEvent; +import com.github.manevolent.ts3j.event.ClientJoinEvent; +import com.github.manevolent.ts3j.event.ClientLeaveEvent; +import com.github.manevolent.ts3j.event.ClientMovedEvent; +import com.github.manevolent.ts3j.event.ClientUpdatedEvent; +import com.github.manevolent.ts3j.event.ServerGroupClientAddedEvent; +import com.github.manevolent.ts3j.event.ServerGroupClientDeletedEvent; +import com.github.manevolent.ts3j.protocol.ProtocolRole; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.contacts.ContactStore; +import eu.lixko.ts3j.client.sound.SoundNotifier; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** Feeds the handler events as the server words them and checks what the model makes of them. */ +class ConnectionEventHandlerTest { + + private int modelChanges; + private int unreadReports; + private final Settings settings = new Settings(); + private final TeamspeakConnection conn = new TeamspeakConnection(settings, null, new ConnectionListener() { + @Override + public void onStatus(String status) { + } + + @Override + public void onConnected() { + } + + @Override + public void onDisconnected(String reason) { + } + + @Override + public void onModelChanged() { + modelChanges++; + } + + @Override + public void onInfoUpdated() { + } + + @Override + public void onIconsUpdated() { + } + + @Override + public void onChat(ChatScope scope, int fromClientId, String fromUniqueId, String fromName, String message) { + } + + @Override + public void onTalkStateChanged(int clientId, boolean talking) { + } + + @Override + public void onError(String message) { + } + + @Override + public void onPoke(String fromName, String message) { + } + + @Override + public void onServerLog(String message) { + } + + @Override + public void onUnreadMessagesChanged(int unread) { + unreadReports++; + } + }, new SoundNotifier(settings), ContactStore.load()); + private final ConnectionEventHandler events = new ConnectionEventHandler(conn); + private final ServerModel model = conn.getModel(); + + /** The fields of an event, parsed from the command text the server sends. */ + private static Map fields(String command) { + return MultiCommand.parse(ProtocolRole.SERVER, command).simplifyOne().toMap(); + } + + private void join(int clid, String nickname, int channel) { + events.onClientJoin(new ClientJoinEvent(fields("notifycliententerview cfid=0 ctid=" + channel + + " reasonid=0 clid=" + clid + " client_unique_identifier=uid" + clid + "==" + + " client_nickname=" + nickname + " client_input_muted=0 client_output_muted=0" + + " client_input_hardware=1 client_output_hardware=1 client_database_id=" + (100 + clid) + + " client_channel_group_id=8 client_servergroups=6,7 client_away=0 client_away_message" + + " client_type=0 client_flag_avatar=abc client_talk_power=25"))); + } + + @Test + void aJoiningClientEntersTheModelWithWhatItReported() { + model.putChannel(1, "Lobby", 0, 0); + join(5, "alice", 1); + + ClientEntry alice = model.getClient(5); + assertEquals("alice", alice.nickname); + assertEquals(1, alice.channelId); + assertEquals(105, alice.databaseId); + assertEquals(25, alice.talkPower); + assertArrayEquals(new int[]{6, 7}, alice.serverGroupIds); + assertEquals("abc", alice.avatarFlag); + assertEquals(1, modelChanges); + } + + @Test + void movesAndLeaves() { + model.putChannel(1, "Lobby", 0, 0); + model.putChannel(2, "Games", 0, 1); + join(5, "alice", 1); + + events.onClientMoved(new ClientMovedEvent(fields("notifyclientmoved ctid=2 reasonid=0 clid=5"))); + assertEquals(2, model.getClient(5).channelId); + + events.onClientLeave(new ClientLeaveEvent(fields( + "notifyclientleftview cfid=2 ctid=0 reasonid=8 reasonmsg=bye clid=5"))); + assertNull(model.getClient(5)); + } + + @Test + void aPartialUpdateLeavesTheOtherFieldsAlone() { + model.putChannel(1, "Lobby", 0, 0); + join(5, "alice", 1); + + events.onClientChanged(new ClientUpdatedEvent(fields("notifyclientupdated clid=5 client_input_muted=1"))); + + ClientEntry alice = model.getClient(5); + assertTrue(alice.inputMuted); + assertEquals("alice", alice.nickname); + assertEquals("abc", alice.avatarFlag); + } + + @Test + void tracksAClientsUnreadOfflineMessages() { + model.putChannel(1, "Lobby", 0, 0); + join(5, "alice", 1); + assertEquals(0, model.getClient(5).unreadMessages); + + events.onClientChanged(new ClientUpdatedEvent(fields("notifyclientupdated clid=5 client_unread_messages=3"))); + assertEquals(3, model.getClient(5).unreadMessages); + assertEquals(0, unreadReports, "only our own count is reported"); + } + + @Test + void clearedFieldsAreCleared() { + model.putChannel(1, "Lobby", 0, 0); + join(5, "alice", 1); + events.onClientChanged(new ClientUpdatedEvent(fields( + "notifyclientupdated clid=5 client_away=1 client_away_message=lunch"))); + assertEquals("lunch", model.getClient(5).awayMessage); + + events.onClientChanged(new ClientUpdatedEvent(fields( + "notifyclientupdated clid=5 client_away_message client_flag_avatar"))); + + ClientEntry alice = model.getClient(5); + assertTrue(alice.away); + assertEquals("", alice.awayMessage); + assertEquals("", alice.avatarFlag); + } + + @Test + void serverGroupsComeAndGo() { + model.putChannel(1, "Lobby", 0, 0); + join(5, "alice", 1); + + events.onServerGroupClientAdded(new ServerGroupClientAddedEvent(fields( + "notifyservergroupclientadded name=Admin sgid=9 cldbid=105 clid=5"))); + assertTrue(model.getClient(5).inServerGroup(9)); + + events.onServerGroupClientDeleted(new ServerGroupClientDeletedEvent(fields( + "notifyservergroupclientdeleted name=Guest sgid=6 cldbid=105 clid=5"))); + assertArrayEquals(new int[]{7, 9}, model.getClient(5).serverGroupIds); + } + + @Test + void channelsAreCreatedEditedMovedAndDeleted() { + model.putChannel(1, "Lobby", 0, 0); + events.onChannelCreate(new ChannelCreateEvent(fields( + "notifychannelcreated cid=2 cpid=0 channel_name=Games channel_order=1" + + " channel_flag_password=1 channel_maxclients=5 channel_flag_maxclients_unlimited=0"))); + ChannelNode games = model.getChannel(2); + assertTrue(games.hasPassword); + assertEquals(5, games.maxClients); + assertEquals(List.of("Lobby", "Games"), model.buildTree().stream().map(c -> c.name).toList()); + + events.onChannelEdit(new ChannelEditedEvent(fields( + "notifychanneledited cid=2 reasonid=10 invokerid=3 invokername=bob invokeruid=bobuid=" + + " channel_flag_password=0 channel_topic"))); + assertFalse(games.hasPassword); + assertEquals("", games.topic); + + events.onChannelMoved(new ChannelMovedEvent(fields("notifychannelmoved cid=2 cpid=1 order=0 reasonid=1"))); + assertEquals(1, games.parentId); + assertEquals(List.of("Games"), model.buildTree().get(0).children.stream().map(c -> c.name).toList()); + + events.onChannelDeleted(new ChannelDeletedEvent(fields("notifychanneldeleted cid=2"))); + assertNull(model.getChannel(2)); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/DetailsTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/DetailsTest.java new file mode 100644 index 0000000..6b0704b --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/DetailsTest.java @@ -0,0 +1,47 @@ +package eu.lixko.ts3j.client.net; + +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class DetailsTest { + + @Test + void serverTakesInitserverAndEditsAndBareKeys() { + ServerModel model = new ServerModel(); + model.setServerName("Test"); + Map init = new HashMap<>(); + init.put("virtualserver_version", "3.13.7"); + init.put("virtualserver_platform", "Linux"); + init.put("virtualserver_maxclients", "32"); + init.put("virtualserver_welcomemessage", "Hello"); + // An empty property comes as a bare key. + init.put("virtualserver_hostmessage", null); + model.putServerProperties(init); + model.putServerProperties(Map.of("virtualserver_hostmessage", "Be nice", "invokerid", "5")); + + Details d = Details.server(model, "host:9987"); + assertEquals("Test", d.title()); + assertEquals(new Details.Field("Version", "3.13.7 on Linux"), d.fields().get(1)); + assertEquals(new Details.Field("Clients", "0 / 32"), d.fields().get(2)); + assertEquals("Hello\n\nBe nice", d.description()); + assertEquals("", model.serverProperty("invokerid")); + } + + @Test + void channelDescriptionIsPendingUntilAnswered() { + ChannelNode ch = new ChannelNode(1, "Lobby"); + ch.topic = "Entry"; + assertTrue(Details.channel(ch).pending()); + ch.descriptionLoaded = true; + Details d = Details.channel(ch); + assertFalse(d.pending()); + assertEquals(List.of(new Details.Field("Topic", "Entry")), d.fields()); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/EventFieldsTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/EventFieldsTest.java new file mode 100644 index 0000000..d9527a5 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/EventFieldsTest.java @@ -0,0 +1,40 @@ +package eu.lixko.ts3j.client.net; + +import com.github.manevolent.ts3j.command.MultiCommand; +import com.github.manevolent.ts3j.event.ClientUpdatedEvent; +import com.github.manevolent.ts3j.protocol.ProtocolRole; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Pins the ts3j behaviour {@code ConnectionEventHandler.has(...)} exists for: a field + * the event never carried reads back as an empty string, so a null check would treat + * every partial update (someone muting, say) as if it reported every other field too. + */ +class EventFieldsTest { + + @Test + void missingFieldsReadBackAsEmptyStringsRatherThanNull() { + ClientUpdatedEvent e = new ClientUpdatedEvent(Map.of("clid", "7", "client_input_muted", "1")); + assertNotNull(e.get("client_is_recording")); + assertEquals("", e.get("client_is_recording")); + assertEquals("", e.get("client_nickname")); + } + + /** What {@code reported(...)} relies on: a cleared field still arrives, just without a value. */ + @Test + void clearedFieldsAreStillInTheMap() { + Map fields = MultiCommand.parse(ProtocolRole.SERVER, + "notifyclientupdated clid=7 client_flag_avatar client_description=").simplifyOne().toMap(); + ClientUpdatedEvent e = new ClientUpdatedEvent(fields); + assertTrue(e.getMap().containsKey("client_flag_avatar")); + assertTrue(e.getMap().containsKey("client_description")); + assertFalse(e.getMap().containsKey("client_away_message")); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ServerLogEntryTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ServerLogEntryTest.java new file mode 100644 index 0000000..6af201c --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ServerLogEntryTest.java @@ -0,0 +1,39 @@ +package eu.lixko.ts3j.client.net; + +import eu.lixko.ts3j.client.net.ServerLogEntry.Level; +import org.junit.jupiter.api.Test; + +import java.time.LocalDateTime; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class ServerLogEntryTest { + + @Test + void readsTheServersLineFormat() { + ServerLogEntry e = ServerLogEntry.parse("2026-10-04 13:11:01.038554|WARNING |VirtualServer |1 |" + + "client 'a|b'(id:19) was added to servergroup 'Server Admin'(id:6)"); + assertEquals(LocalDateTime.of(2026, 10, 4, 13, 11, 1, 38_554_000), e.timestamp()); + assertEquals(Level.WARNING, e.level()); + assertEquals("VirtualServer", e.channel()); + assertEquals("client 'a|b'(id:19) was added to servergroup 'Server Admin'(id:6)", e.message()); + } + + @Test + void keepsTheRestOfALineWithACutOffTimestamp() { + ServerLogEntry e = ServerLogEntry.parse("6-10-01 23:26:51.007742|INFO |VirtualServerBase|1 |listening on 0.0.0.0:9990"); + assertNull(e.timestamp()); + assertEquals(Level.INFO, e.level()); + assertEquals("VirtualServerBase", e.channel()); + assertEquals("listening on 0.0.0.0:9990", e.message()); + } + + @Test + void keepsAnUnreadableLineWhole() { + ServerLogEntry e = ServerLogEntry.parse("2026-10-04 00:23:41.975519|INFO "); + assertNull(e.timestamp()); + assertEquals(Level.INFO, e.level()); + assertEquals("2026-10-04 00:23:41.975519|INFO ", e.message()); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ServerModelRulesTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ServerModelRulesTest.java new file mode 100644 index 0000000..996bbe1 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ServerModelRulesTest.java @@ -0,0 +1,59 @@ +package eu.lixko.ts3j.client.net; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ServerModelRulesTest { + + private final ServerModel model = new ServerModel(); + + private void grant(String permission, int value) { + model.putPermissionName(permission); + model.putSelfPermissionValue(permissionId(permission), value); + } + + private int permissionId(String name) { + for (int id = 0; ; id++) { + if (name.equals(model.permissionName(id))) return id; + } + } + + private static Group group(int addPower, int removePower) { + return new Group(9, "Group", 0, 0, 1, addPower, removePower); + } + + @Test + void groupNeedsEnoughAddPowerAndRemovePowerToTakeAway() { + grant("i_group_member_add_power", 50); + grant("i_group_member_remove_power", 20); + + assertTrue(model.canToggleGroup(group(50, 0), false)); + assertFalse(model.canToggleGroup(group(51, 0), false)); + assertTrue(model.canToggleGroup(group(50, 20), true)); + assertFalse(model.canToggleGroup(group(50, 21), true)); + } + + @Test + void unlimitedPowerIsMinusOneOnEitherSide() { + grant("i_group_member_add_power", 75); + grant("i_group_member_remove_power", -1); + + assertFalse(model.canToggleGroup(group(-1, 0), false), "a group needing unlimited power"); + assertTrue(model.canToggleGroup(group(75, 1000), true), "unlimited remove power"); + } + + @Test + void joiningNeedsAVisibleChannelWithRoom() { + ChannelNode channel = model.putChannel(1, "Full", 0, 0); + model.putClient(5, "Someone", 1); + assertFalse(model.canJoinChannel(1), "not subscribed"); + + channel.subscribed = true; + assertTrue(model.canJoinChannel(1)); + channel.maxClients = 1; + assertFalse(model.canJoinChannel(1), "full"); + assertFalse(model.canJoinChannel(2), "unknown"); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ServerModelTreeTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ServerModelTreeTest.java new file mode 100644 index 0000000..a020642 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ServerModelTreeTest.java @@ -0,0 +1,101 @@ +package eu.lixko.ts3j.client.net; + +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +/** The channel tree: TS3 orders siblings as a chain of "sits below" links, not by a key. */ +class ServerModelTreeTest { + + private final ServerModel model = new ServerModel(); + + private static List names(List channels) { + return channels.stream().map(c -> c.name).toList(); + } + + @Test + void ordersSiblingsByTheirChainWhateverOrderTheyArrivedIn() { + model.putChannel(3, "C", 0, 2); + model.putChannel(1, "A", 0, 0); + model.putChannel(2, "B", 0, 1); + assertEquals(List.of("A", "B", "C"), names(model.buildTree())); + } + + @Test + void keepsChannelsWhoseLinksAreBroken() { + model.putChannel(1, "A", 0, 0); + model.putChannel(2, "B", 0, 1); + model.putChannel(3, "C", 0, 1); // claims the same place as B + model.putChannel(4, "D", 0, 99); // sits below a channel that does not exist + List tree = names(model.buildTree()); + assertEquals(4, tree.size()); + assertEquals(List.of("A", "B"), tree.subList(0, 2)); + } + + @Test + void nestsChannelsAndPutsOrphansAtTheTop() { + model.putChannel(1, "Lobby", 0, 0); + model.putChannel(2, "Games", 1, 0); + model.putChannel(3, "Lost", 42, 0); + List roots = model.buildTree(); + assertEquals(List.of("Lobby", "Lost"), names(roots).stream().sorted().toList()); + assertEquals(List.of("Games"), names(model.getChannel(1).children)); + } + + @Test + void aRemovedChannelsFollowerMovesUp() { + model.putChannel(1, "A", 0, 0); + model.putChannel(2, "B", 0, 1); + model.putChannel(3, "C", 0, 2); + model.removeChannel(2); + assertEquals(List.of("A", "C"), names(model.buildTree())); + } + + @Test + void reorderingRepairsTheLinksTheServerDoesNotResend() { + model.putChannel(1, "A", 0, 0); + model.putChannel(2, "B", 0, 1); + model.putChannel(3, "C", 0, 2); + model.relinkChannel(3, 0, 0); // C to the top + assertEquals(List.of("C", "A", "B"), names(model.buildTree())); + model.relinkChannel(3, 0, 2); // and back below B + assertEquals(List.of("A", "B", "C"), names(model.buildTree())); + } + + @Test + void movingUnderAnotherParentClosesTheGap() { + model.putChannel(1, "A", 0, 0); + model.putChannel(2, "B", 0, 1); + model.putChannel(3, "C", 0, 2); + model.relinkChannel(2, 1, 0); + assertEquals(List.of("A", "C"), names(model.buildTree())); + assertEquals(List.of("B"), names(model.getChannel(1).children)); + } + + @Test + void listsClientsByTalkPowerThenNameAndHidesQueryClients() { + model.putChannel(1, "Lobby", 0, 0); + model.putClient(10, "zed", 1); + model.putClient(11, "Amy", 1); + model.putClient(12, "bob", 1).talkPower = 50; + model.putClient(13, "serveradmin", 1).type = 1; + model.buildTree(); + assertEquals(List.of("bob", "Amy", "zed"), + model.getChannel(1).clients.stream().map(c -> c.nickname).toList()); + } + + @Test + void findsChannelsByPathIdOrPlainName() { + model.putChannel(1, "Lobby", 0, 0); + ChannelNode games = model.putChannel(2, "Games", 1, 0); + assertEquals("Lobby/Games", model.channelPath(2)); + assertSame(games, model.findChannelByPath("/lobby/games/")); + assertSame(games, model.findChannelByPath("/2")); + assertSame(games, model.findChannelByPath("Games"), "a moved channel is still found by name"); + assertNull(model.findChannelByPath("Lobby/Music")); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/avatar/AvatarNamingTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/avatar/AvatarNamingTest.java new file mode 100644 index 0000000..1ae7fe3 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/avatar/AvatarNamingTest.java @@ -0,0 +1,39 @@ +package eu.lixko.ts3j.client.net.avatar; + +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class AvatarNamingTest { + + @Test + void fileNameEncodesDecodedUidNibbleWise() { + // base64 of 0x00 0x01 ... 0x13 + String uid = "AAECAwQFBgcICQoLDA0ODxAREhM="; + assertEquals("avatar_aaabacadaeafagahaiajakalamanaoapbabbbcbd", AvatarNaming.fileName(uid)); + assertEquals("avatar_" + "p".repeat(40), + AvatarNaming.fileName("//////////////////////////8=")); + } + + @Test + void fileNameRejectsMalformedIds() { + assertNull(AvatarNaming.fileName("")); + assertNull(AvatarNaming.fileName("not base64!")); + assertNull(AvatarNaming.fileName("AAEC")); // decodes, but not to 20 bytes + assertNull(AvatarNaming.fileName(null)); + } + + @Test + void flagIsLowercaseMd5() { + assertEquals("9e107d9d372bb6826bd81d3542a419d6", + AvatarNaming.flag("The quick brown fox jumps over the lazy dog".getBytes(StandardCharsets.US_ASCII))); + assertTrue(AvatarNaming.isFlag("9e107d9d372bb6826bd81d3542a419d6")); + assertFalse(AvatarNaming.isFlag("")); + assertFalse(AvatarNaming.isFlag("zz107d9d372bb6826bd81d3542a419d6")); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/avatar/AvatarRepositoryTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/avatar/AvatarRepositoryTest.java new file mode 100644 index 0000000..d477f26 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/avatar/AvatarRepositoryTest.java @@ -0,0 +1,83 @@ +package eu.lixko.ts3j.client.net.avatar; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.File; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class AvatarRepositoryTest { + + private static final byte[] GIF = "GIF89a-not-really-an-image".getBytes(); + private static final String UID = "AAECAwQFBgcICQoLDA0ODxAREhM="; + + @TempDir + File cache; + + @Test + void downloadsOnceThenServesFromMemoryAndDisk() throws Exception { + AtomicInteger fetches = new AtomicInteger(); + CountDownLatch loaded = new CountDownLatch(1); + AvatarRepository repo = new AvatarRepository(uid -> { + fetches.incrementAndGet(); + return GIF; + }, loaded::countDown, cache); + String flag = AvatarNaming.flag(GIF); + + assertNull(repo.get(UID, flag)); + assertTrue(loaded.await(5, TimeUnit.SECONDS)); + Avatar avatar = repo.get(UID, flag); + assertNotNull(avatar); + assertEquals(ImageFormat.GIF, avatar.format()); + assertTrue(avatar.isAnimated()); + assertEquals(new File(cache, flag + ".gif"), avatar.file()); + assertEquals(1, fetches.get()); + + // A fresh repository over the same directory needs no download. + AvatarRepository again = new AvatarRepository(uid -> { + throw new AssertionError("should not fetch"); + }, null, cache); + assertNotNull(again.get(UID, flag)); + } + + @Test + void rejectsFilesWhoseMd5DoesNotMatchTheFlag() throws Exception { + AtomicInteger fetches = new AtomicInteger(); + AvatarRepository repo = new AvatarRepository(uid -> { + fetches.incrementAndGet(); + return GIF; + }, null, cache); + String wrongFlag = "0123456789abcdef0123456789abcdef"; + + assertNull(repo.get(UID, wrongFlag)); + Thread.sleep(300); + assertNull(repo.get(UID, wrongFlag)); + Thread.sleep(300); + assertEquals(1, fetches.get(), "a mismatch is not retried"); + assertEquals(0, cache.list().length); + } + + @Test + void ignoresClientsWithoutAnAvatar() { + AvatarRepository repo = new AvatarRepository(uid -> { + throw new AssertionError("should not fetch"); + }, null, cache); + assertNull(repo.get(UID, "")); + assertNull(repo.get(UID, null)); + } + + @Test + void putMakesAnUploadedAvatarAvailableImmediately() { + AvatarRepository repo = new AvatarRepository(uid -> null, null, cache); + Avatar avatar = repo.put(GIF); + assertEquals(AvatarNaming.flag(GIF), avatar.flag()); + assertEquals(avatar, repo.get(UID, avatar.flag())); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/avatar/ImageFormatTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/avatar/ImageFormatTest.java new file mode 100644 index 0000000..6d00f64 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/avatar/ImageFormatTest.java @@ -0,0 +1,20 @@ +package eu.lixko.ts3j.client.net.avatar; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class ImageFormatTest { + + @Test + void detectsByMagicBytes() { + assertEquals(ImageFormat.PNG, ImageFormat.detect(new byte[]{(byte) 0x89, 'P', 'N', 'G', 13, 10, 26, 10})); + assertEquals(ImageFormat.JPEG, ImageFormat.detect(new byte[]{(byte) 0xFF, (byte) 0xD8, (byte) 0xFF, (byte) 0xE0, 0, 16})); + assertEquals(ImageFormat.GIF, ImageFormat.detect("GIF89a".getBytes())); + assertEquals(ImageFormat.BMP, ImageFormat.detect("BM\0\0\0\0".getBytes())); + assertNull(ImageFormat.detect("".getBytes())); + assertNull(ImageFormat.detect(new byte[3])); + assertNull(ImageFormat.detect(null)); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ban/BanPatternTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ban/BanPatternTest.java new file mode 100644 index 0000000..254f6c7 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ban/BanPatternTest.java @@ -0,0 +1,67 @@ +package eu.lixko.ts3j.client.net.ban; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class BanPatternTest { + + @Test + void wildcardIpv4TurnsStarsIntoAddressGroups() { + assertEquals("192\\.168\\.[0-9]+\\.[0-9]+", BanPattern.WILDCARD_IPV4.ipToRegex("192.168.*.*")); + assertEquals("2001:db8:[0-9a-fA-F]+:[0-9a-fA-F]+", BanPattern.WILDCARD_IPV6.ipToRegex("2001:db8:*:*")); + } + + @Test + void wildcardNamesMatchAnything() { + assertEquals("Troll.*", BanPattern.WILDCARD_IPV4.nameToRegex("Troll*")); + assertEquals("\\[Bot\\].*", BanPattern.WILDCARD_IPV6.nameToRegex("[Bot]*")); + } + + @Test + void fixedStringsAreTakenLiterally() { + assertEquals("10\\.0\\.0\\.1", BanPattern.FIXED_STRING.ipToRegex("10.0.0.1")); + assertEquals("a\\*b\\?\\(c\\)\\$\\^\\|\\\\", BanPattern.FIXED_STRING.nameToRegex("a*b?(c)$^|\\")); + } + + @Test + void regularExpressionsPassThrough() { + assertEquals("^Troll[0-9]{2}$", BanPattern.REGULAR_EXPRESSION.nameToRegex("^Troll[0-9]{2}$")); + } + + @Test + void decodeRecoversTheNotationThatProducedTheExpression() { + BanPattern.Decoded d = BanPattern.decode("192\\.168\\.[0-9]+\\.[0-9]+", "Troll.*"); + assertEquals(BanPattern.WILDCARD_IPV4, d.pattern); + assertEquals("192.168.*.*", d.ip); + assertEquals("Troll*", d.name); + + d = BanPattern.decode("fe80:[0-9a-fA-F]+", ""); + assertEquals(BanPattern.WILDCARD_IPV6, d.pattern); + assertEquals("fe80:*", d.ip); + + d = BanPattern.decode("", "a\\*b"); + assertEquals(BanPattern.FIXED_STRING, d.pattern); + assertEquals("a*b", d.name); + + d = BanPattern.decode("", "^Troll[0-9]{2}$"); + assertEquals(BanPattern.REGULAR_EXPRESSION, d.pattern); + assertEquals("^Troll[0-9]{2}$", d.name); + } + + @Test + void plainAddressesDecodeAsWildcardsLikeTheDialogDefault() { + BanPattern.Decoded d = BanPattern.decode("10\\.0\\.0\\.1", ""); + assertEquals(BanPattern.WILDCARD_IPV4, d.pattern); + assertEquals("10.0.0.1", d.ip); + } + + @Test + void validityFollowsJavaRegexSyntax() { + assertTrue(BanPattern.isValidRegex("")); + assertTrue(BanPattern.isValidRegex("^a.*$")); + assertFalse(BanPattern.isValidRegex("(unclosed")); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ban/BanUnitTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ban/BanUnitTest.java new file mode 100644 index 0000000..e95fafc --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/net/ban/BanUnitTest.java @@ -0,0 +1,24 @@ +package eu.lixko.ts3j.client.net.ban; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class BanUnitTest { + + @Test + void lengthsShowInTheLargestUnitThatDividesThem() { + assertEquals(BanUnit.DAYS, BanUnit.largestFor(2 * 86400)); + assertEquals(BanUnit.HOURS, BanUnit.largestFor(90 * 60 * 2)); + assertEquals(BanUnit.MINUTES, BanUnit.largestFor(120)); + assertEquals(BanUnit.SECONDS, BanUnit.largestFor(61)); + assertEquals(2, BanUnit.DAYS.amountOf(2 * 86400)); + } + + @Test + void noLengthIsPermanent() { + assertEquals(BanUnit.PERMANENT, BanUnit.largestFor(0)); + assertEquals(BanUnit.PERMANENT, BanUnit.largestFor(-1)); + assertEquals(0, BanUnit.PERMANENT.toSeconds(30)); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/session/ServerLinkTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/session/ServerLinkTest.java new file mode 100644 index 0000000..30b7b1e --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/session/ServerLinkTest.java @@ -0,0 +1,62 @@ +package eu.lixko.ts3j.client.session; + +import eu.lixko.ts3j.client.config.Bookmark; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class ServerLinkTest { + + @Test + void readsEveryParameter() { + ServerLink link = ServerLink.parse("ts3server://ts.example.com?port=9988&nickname=Bob%20B" + + "&password=s+cret&channel=Lobby/Games&channelpassword=pw&token=abc&addbookmark=Example"); + assertEquals("ts.example.com", link.address); + assertEquals(9988, link.port); + assertEquals("Bob B", link.nickname); + assertEquals("s+cret", link.password); + assertEquals("Lobby/Games", link.channel); + assertEquals("pw", link.channelPassword); + assertEquals("abc", link.token); + assertEquals("Example", link.bookmarkLabel); + } + + @Test + void aBareHostTakesTheDefaults() { + ServerLink link = ServerLink.parse("TS3SERVER://ts.example.com/"); + assertEquals("ts.example.com", link.address); + assertEquals(9987, link.port); + assertEquals("", link.channel); + assertEquals("", link.token); + } + + @Test + void readsThePortFromTheAuthority() { + assertEquals(1234, ServerLink.parse("ts3server://1.2.3.4:1234").port); + ServerLink v6 = ServerLink.parse("ts3server://[2001:db8::1]:5000?nickname=x"); + assertEquals("2001:db8::1", v6.address); + assertEquals(5000, v6.port); + } + + @Test + void aChannelIdWinsOverThePath() { + assertEquals("/42", ServerLink.parse("ts3server://h?channel=Old%20name&cid=42").channel); + assertEquals("Lobby", ServerLink.parse("ts3server://h?cid=0&channel=Lobby").channel); + } + + @Test + void namesNoServerWithoutAHost() { + assertNull(ServerLink.parse("ts3server://?port=1")); + assertNull(ServerLink.parse("https://example.com")); + } + + @Test + void bookmarksUnderTheAskedName() { + Bookmark b = ServerLink.parse("ts3server://h?addbookmark=Mine&cid=3&channelpassword=x").toBookmark(); + assertEquals("Mine", b.label); + assertEquals("/3", b.channel); + assertEquals("x", b.channelPassword); + assertEquals("h", ServerLink.parse("ts3server://h").toBookmark().label); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/sound/NotificationSettingsTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/sound/NotificationSettingsTest.java new file mode 100644 index 0000000..3168ae8 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/sound/NotificationSettingsTest.java @@ -0,0 +1,51 @@ +package eu.lixko.ts3j.client.sound; + +import org.junit.jupiter.api.Test; + +import java.util.Properties; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class NotificationSettingsTest { + + @Test + void defaultsFollowTheEventCatalogue() { + NotificationSettings s = new NotificationSettings(); + assertTrue(s.isImportant(SoundEvent.OTHER_RECEIVED_POKE)); + assertFalse(s.isImportant(SoundEvent.YOU_SWITCHED_CHANNEL)); + assertTrue(s.isEnabled(SoundEvent.YOU_SWITCHED_CHANNEL)); + assertFalse(s.isEnabled(SoundEvent.SPECIAL_MIC_CLICK_SELF_ON)); + } + + @Test + void onlyDeviationsArePersisted() { + NotificationSettings s = new NotificationSettings(); + s.setImportant(SoundEvent.YOU_SWITCHED_CHANNEL, true); + s.setEnabled(SoundEvent.CHAT_RECEIVED_MESSAGE_CHANNEL, false); + + Properties props = new Properties(); + s.store(props); + assertEquals(2, props.size()); + + NotificationSettings loaded = new NotificationSettings(); + loaded.load(props); + assertTrue(loaded.isImportant(SoundEvent.YOU_SWITCHED_CHANNEL)); + assertFalse(loaded.isEnabled(SoundEvent.CHAT_RECEIVED_MESSAGE_CHANNEL)); + assertTrue(loaded.isImportant(SoundEvent.OTHER_RECEIVED_POKE)); + } + + @Test + void storeClearsStaleEntries() { + Properties props = new Properties(); + NotificationSettings s = new NotificationSettings(); + s.setEnabled(SoundEvent.SERVER_ERROR, false); + s.store(props); + assertEquals(1, props.size()); + + s.setEnabled(SoundEvent.SERVER_ERROR, true); + s.store(props); + assertTrue(props.isEmpty()); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/sound/SoundPackTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/sound/SoundPackTest.java new file mode 100644 index 0000000..bd72ebe --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/sound/SoundPackTest.java @@ -0,0 +1,89 @@ +package eu.lixko.ts3j.client.sound; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +class SoundPackTest { + + private static final String INI = """ + [info] + # a comment + name = Test Pack + version = 1.0 + author = Somebody + + [soundfiles] + CONNECTION_CONNECTED = play("connected.wav") + CONNECTION_DISCONNECTED = + CHANNEL_CREATED_BY_OTHER = say("Channel ${channelname} was created by ${clientname}") + CLIENT_MOVED_TO_CURRENT_CHANNEL_STAYS = play("${clientType}_moved_tocurrentchannel.wav") + NOT_AN_EVENT = play("nothing.wav") + """; + + private SoundPack load(Path dir) throws Exception { + Files.writeString(dir.resolve("settings.ini"), INI, StandardCharsets.UTF_8); + Files.writeString(dir.resolve("connected.wav"), "not really audio"); + Files.writeString(dir.resolve("Neutral_Moved_ToCurrentChannel.wav"), "not really audio"); + SoundPack pack = SoundPack.load(dir.toFile()); + assertNotNull(pack); + return pack; + } + + @Test + void readsPackInfo(@TempDir Path dir) throws Exception { + SoundPack pack = load(dir); + assertEquals(dir.getFileName().toString(), pack.id()); + assertEquals("Test Pack", pack.name()); + assertEquals("Somebody", pack.author()); + assertEquals("1.0", pack.version()); + } + + @Test + void mapsEventsAndSkipsEmptyOnes(@TempDir Path dir) throws Exception { + SoundPack pack = load(dir); + assertEquals(new SoundScript(SoundScript.Kind.PLAY, "connected.wav"), + pack.script(SoundEvent.CONNECTION_CONNECTED)); + assertNull(pack.script(SoundEvent.CONNECTION_DISCONNECTED)); + assertEquals(SoundScript.Kind.SAY, pack.script(SoundEvent.CHANNEL_CREATED_BY_OTHER).kind()); + } + + @Test + void resolvesVariables(@TempDir Path dir) throws Exception { + SoundPack pack = load(dir); + String spoken = pack.script(SoundEvent.CHANNEL_CREATED_BY_OTHER) + .resolve(Map.of("channelname", "Lobby", "clientname", "Bob")); + assertEquals("Channel Lobby was created by Bob", spoken); + } + + @Test + void findsFilesRegardlessOfCase(@TempDir Path dir) throws Exception { + SoundPack pack = load(dir); + String name = pack.script(SoundEvent.CLIENT_MOVED_TO_CURRENT_CHANNEL_STAYS) + .resolve(Map.of("clientType", "neutral")); + assertEquals("neutral_moved_tocurrentchannel.wav", name); + File file = pack.file(name); + assertNotNull(file); + assertEquals("Neutral_Moved_ToCurrentChannel.wav", file.getName()); + } + + @Test + void unknownEntriesAreIgnored(@TempDir Path dir) throws Exception { + SoundPack pack = load(dir); + assertNull(pack.file("nothing.wav")); + } + + @Test + void directoryWithoutIniIsNotAPack(@TempDir Path dir) { + assertNull(SoundPack.load(dir.toFile())); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/sound/WaveFileTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/sound/WaveFileTest.java new file mode 100644 index 0000000..1dfc2c1 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/sound/WaveFileTest.java @@ -0,0 +1,74 @@ +package eu.lixko.ts3j.client.sound; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.File; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class WaveFileTest { + + @TempDir + Path dir; + + /** Builds a wave file around raw sample bytes. */ + private File wave(int format, int channels, int bits, boolean extensible, byte[] data) throws IOException { + int fmtSize = extensible ? 40 : 16; + ByteBuffer b = ByteBuffer.allocate(12 + 8 + fmtSize + 8 + data.length).order(ByteOrder.LITTLE_ENDIAN); + b.put("RIFF".getBytes()).putInt(b.capacity() - 8).put("WAVE".getBytes()); + b.put("fmt ".getBytes()).putInt(fmtSize); + b.putShort((short) (extensible ? 0xFFFE : format)).putShort((short) channels).putInt(44100) + .putInt(44100 * channels * bits / 8).putShort((short) (channels * bits / 8)).putShort((short) bits); + if (extensible) { + b.putShort((short) 22).putShort((short) bits).putInt(0).putShort((short) format).put(new byte[14]); + } + b.put("data".getBytes()).putInt(data.length).put(data); + File file = dir.resolve("test.wav").toFile(); + Files.write(file.toPath(), b.array()); + return file; + } + + @Test + void readsSixteenBitMono() throws IOException { + WaveFile.Audio audio = WaveFile.readMono(wave(1, 1, 16, false, new byte[]{0, 0x40, 0, (byte) 0xC0})); + assertEquals(44100, audio.sampleRate()); + assertArrayEquals(new float[]{0.5f, -0.5f}, audio.samples()); + } + + @Test + void averagesStereoDown() throws IOException { + WaveFile.Audio audio = WaveFile.readMono(wave(1, 2, 16, false, new byte[]{0, 0x40, 0, 0})); + assertArrayEquals(new float[]{0.25f}, audio.samples()); + } + + @Test + void readsUnsignedEightBit() throws IOException { + WaveFile.Audio audio = WaveFile.readMono(wave(1, 1, 8, false, new byte[]{(byte) 192, 64, (byte) 128})); + assertArrayEquals(new float[]{0.5f, -0.5f, 0f}, audio.samples()); + } + + @Test + void readsTwentyFourBitThroughAnExtensibleHeader() throws IOException { + WaveFile.Audio audio = WaveFile.readMono(wave(1, 1, 24, true, new byte[]{0, 0, 0x40, 0, 0, (byte) 0xC0})); + assertArrayEquals(new float[]{0.5f, -0.5f}, audio.samples()); + } + + @Test + void readsFloat() throws IOException { + byte[] data = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putFloat(0.25f).putFloat(-1f).array(); + assertArrayEquals(new float[]{0.25f, -1f}, WaveFile.readMono(wave(3, 1, 32, false, data)).samples()); + } + + @Test + void rejectsCompressedAudio() { + assertThrows(IOException.class, () -> WaveFile.readMono(wave(2, 1, 4, false, new byte[4]))); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/teamspeak/SyncItemsTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/teamspeak/SyncItemsTest.java new file mode 100644 index 0000000..6d4b4dc --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/teamspeak/SyncItemsTest.java @@ -0,0 +1,82 @@ +package eu.lixko.ts3j.client.teamspeak; + +import eu.lixko.ts3j.client.config.IdentityStore; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The fixture is the {@code ProtobufItems} table a fresh official client wrote + * (config, hotkey profile, "Default" identity, "TeamSpeak Public" bookmark, + * checksum), plus a folder, two more bookmarks, a deleted bookmark and a + * whisper list appended in the same encoding. + */ +class SyncItemsTest { + + private static final String IDENTITY_UUID = "965483cf-210f-dd22-ee1f-33591b0587a4"; + private static final String FOLDER_UUID = "0f0f0f0f-0000-4000-8000-000000000001"; + + static File fixture() { + return new File(SyncItemsTest.class.getResource("/teamspeak/sync.db").getFile()); + } + + @Test + void readsBookmarksIdentitiesAndFoldersOnly() throws Exception { + List items = TeamSpeakSettingsDb.readSyncItems(fixture()); + assertEquals(5, items.size()); + assertEquals(List.of(IDENTITY_UUID, "ea120ce1-b68b-b314-46ee-e16b3bf10342", FOLDER_UUID, + "bbbbbbbb-0000-4000-8000-000000000002", "bbbbbbbb-0000-4000-8000-000000000003"), + items.stream().map(SyncItem::uuid).toList()); + } + + @Test + void decodesTheClientsOwnIdentityAndBookmark() throws Exception { + List items = TeamSpeakSettingsDb.readSyncItems(fixture()); + + SyncItem.Identity identity = (SyncItem.Identity) items.get(0); + assertEquals("Default", identity.name()); + assertEquals("SyncTester", identity.nickname()); + assertEquals("", identity.parentUuid()); + assertTrue(identity.isDefault()); + assertTrue(identity.identity().matches("\\d+V[\\w+/=]+")); + assertNotNull(IdentityStore.parseIdentityString(identity.identity()).getUid()); + + SyncItem.Bookmark bookmark = (SyncItem.Bookmark) items.get(1); + assertEquals("TeamSpeak Public", bookmark.name()); + assertEquals("voice.teamspeak.com", bookmark.address()); + assertEquals(9987, bookmark.port()); + assertEquals("", bookmark.identityUuid(), "connects with the default identity"); + assertEquals("", bookmark.nickname()); + assertFalse(bookmark.autoconnect()); + } + + @Test + void decodesFoldersAndEveryBookmarkField() throws Exception { + List items = TeamSpeakSettingsDb.readSyncItems(fixture()); + + SyncItem.Folder folder = (SyncItem.Folder) items.get(2); + assertEquals("Clan servers", folder.name()); + + SyncItem.Bookmark inFolder = (SyncItem.Bookmark) items.get(3); + assertEquals(FOLDER_UUID, inFolder.parentUuid()); + assertEquals("Lixko", inFolder.name()); + assertEquals(IDENTITY_UUID, inFolder.identityUuid()); + assertEquals("server.lixko.eu", inFolder.address()); + assertEquals("Bookmark Nick", inFolder.nickname()); + assertEquals("hunter2", inFolder.serverPassword()); + assertEquals("Lobby/Games", inFolder.defaultChannel()); + assertEquals("chanpw", inFolder.defaultChannelPassword()); + assertTrue(inFolder.autoconnect()); + + SyncItem.Bookmark byId = (SyncItem.Bookmark) items.get(4); + assertEquals(9988, byId.port()); + assertEquals(42, byId.defaultChannelId()); + assertEquals("", byId.identityUuid()); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/teamspeak/SyncOrderTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/teamspeak/SyncOrderTest.java new file mode 100644 index 0000000..0937ca5 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/teamspeak/SyncOrderTest.java @@ -0,0 +1,55 @@ +package eu.lixko.ts3j.client.teamspeak; + +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SyncOrderTest { + + /** + * Written by the official client: Charlie, Alpha and Bravo added in that order, Bravo dragged + * to the top, Charlie removed, then a folder with Delta and Echo added below TeamSpeak Public. + */ + @Test + void readsBookmarksInTheOrderTheOfficialClientListsThem() throws Exception { + File db = new File(SyncOrderTest.class.getResource("/teamspeak/reordered.db").getFile()); + assertEquals(List.of("Bravo", "TeamSpeak Public", "[New Folder]", "Delta", "Echo", "Alpha"), + names(TeamSpeakSettingsDb.readSyncItems(db))); + } + + @Test + void putsItemsWithBrokenLinksLastInStoredOrder() { + List items = List.of( + folder("f", "", "b"), + bookmark("x", "", "lost"), + bookmark("c", "f", ""), + bookmark("a", "", ""), + bookmark("y", "gone", ""), + bookmark("b", "", "a")); + assertEquals(List.of("a", "b", "[f]", "c", "x", "y"), names(SyncOrder.sorted(items))); + } + + @Test + void survivesALoop() { + List items = List.of(bookmark("a", "", "b"), bookmark("b", "", "a")); + assertEquals(List.of("a", "b"), names(SyncOrder.sorted(items))); + } + + private static SyncItem.Bookmark bookmark(String uuid, String parent, String previous) { + return new SyncItem.Bookmark(uuid, parent, previous, uuid, uuid + ".example", 9987, "", "", "", "", "", "", + 0, false); + } + + private static SyncItem.Folder folder(String uuid, String parent, String previous) { + return new SyncItem.Folder(uuid, parent, previous, uuid); + } + + private static List names(List items) { + return items.stream().map(i -> i instanceof SyncItem.Bookmark b ? b.name() + : i instanceof SyncItem.Folder f ? "[" + f.name() + "]" : null) + .filter(n -> n != null).toList(); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakImporterTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakImporterTest.java new file mode 100644 index 0000000..ac8bcc8 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakImporterTest.java @@ -0,0 +1,130 @@ +package eu.lixko.ts3j.client.teamspeak; + +import eu.lixko.ts3j.client.config.AppDirs; +import eu.lixko.ts3j.client.config.Bookmark; +import eu.lixko.ts3j.client.config.Bookmarks; +import eu.lixko.ts3j.client.config.IdentityEntry; +import eu.lixko.ts3j.client.config.IdentityStore; +import eu.lixko.ts3j.client.config.Settings; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Path; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class TeamSpeakImporterTest { + + /** Each test starts from an empty profile; the shared test home keeps identities from earlier runs. */ + @BeforeEach + void freshProfile(@TempDir Path dir) { + AppDirs.init(dir.resolve("profile").toFile(), dir.resolve("chats")); + } + + @AfterEach + void defaultProfile() { + AppDirs.init(null, null); + } + + @Test + void importsBookmarksWithTheIdentitiesTheyUse() throws Exception { + Settings settings = new Settings(); + settings.nickname = "Fallback"; + IdentityStore identities = IdentityStore.load(settings); + Bookmarks bookmarks = new Bookmarks(); + bookmarks.add(new Bookmark("TeamSpeak Public", "VOICE.teamspeak.com", 9987, "me", "")); + + TeamSpeakImporter importer = new TeamSpeakImporter(identities, bookmarks, settings); + TeamSpeakImporter.Result result = importer.importBookmarks(SyncItemsTest.fixture()); + assertEquals(1, result.identitiesAdded()); + assertEquals(2, result.bookmarksAdded()); + assertEquals(1, result.bookmarksKnown()); + + IdentityEntry imported = identities.all().get(0); + assertEquals("Default", imported.getName()); + assertEquals(imported.getId(), settings.defaultIdentityId); + assertTrue(imported.getFile().isFile()); + + List all = bookmarks.all(); + assertEquals(3, all.size()); + Bookmark lixko = all.get(1); + assertEquals("Lixko", lixko.label); + assertEquals("Bookmark Nick", lixko.nickname); + assertEquals("hunter2", lixko.password); + assertEquals("Lobby/Games", lixko.channel); + assertEquals("chanpw", lixko.channelPassword); + assertEquals(imported.getId(), lixko.identityId); + assertTrue(lixko.connectOnStartup); + + Bookmark byId = all.get(2); + assertEquals("/42", byId.channel); + assertEquals("", byId.nickname, "takes the identity's nickname as it connects"); + assertEquals("SyncTester", imported.getNickname()); + assertEquals("", byId.identityId, "connects with whatever the default identity is"); + assertEquals("SyncTester", settings.nickname); + + // Running it again changes nothing. + result = importer.importBookmarks(SyncItemsTest.fixture()); + assertEquals(0, result.identitiesAdded()); + assertEquals(0, result.bookmarksAdded()); + assertEquals(3, bookmarks.all().size()); + assertEquals(1, identities.all().size()); + } + + @Test + void resolvesABookmarkNamingItsIdentity() throws Exception { + Settings settings = new Settings(); + IdentityStore identities = IdentityStore.load(settings); + Bookmarks bookmarks = new Bookmarks(); + SyncItem.Identity identity = TeamSpeakSettingsDb.readSyncItems(SyncItemsTest.fixture()).stream() + .filter(SyncItem.Identity.class::isInstance).map(SyncItem.Identity.class::cast).findFirst().orElseThrow(); + SyncItem.Bookmark bookmark = new SyncItem.Bookmark("b", "", "", "Server", "example.com", 9987, "", "", + identity.name(), "", "", "", 0, false); + + new TeamSpeakImporter(identities, bookmarks, settings).importAll(List.of(bookmark, identity)); + assertEquals(identities.all().get(0).getId(), bookmarks.all().get(0).identityId); + assertEquals("", bookmarks.all().get(0).nickname); + assertEquals(identity.nickname(), identities.all().get(0).getNickname()); + assertEquals(identity.phoneticNickname(), identities.all().get(0).getPhoneticNickname()); + } + + @Test + void importsTheSelectionWithTheIdentitiesItNeeds() throws Exception { + Settings settings = new Settings(); + IdentityStore identities = IdentityStore.load(settings); + Bookmarks bookmarks = new Bookmarks(); + TeamSpeakImporter importer = new TeamSpeakImporter(identities, bookmarks, settings); + List all = TeamSpeakSettingsDb.readSyncItems(SyncItemsTest.fixture()); + SyncItem.Bookmark lixko = all.stream().filter(SyncItem.Bookmark.class::isInstance) + .map(SyncItem.Bookmark.class::cast).filter(b -> b.name().equals("Lixko")).findFirst().orElseThrow(); + assertFalse(importer.isPresent(lixko)); + + TeamSpeakImporter.Result result = importer.importSelected(all, List.of(lixko)); + assertEquals(1, result.bookmarksAdded()); + assertEquals(1, result.identitiesAdded(), "the identity the bookmark connects with"); + assertEquals(identities.all().get(0).getId(), bookmarks.all().get(0).identityId); + assertTrue(importer.isPresent(lixko)); + assertTrue(all.stream().filter(SyncItem.Identity.class::isInstance).allMatch(importer::isPresent)); + } + + @Test + void identityImportRecognisesAKnownKey() throws Exception { + Settings settings = new Settings(); + IdentityStore identities = IdentityStore.load(settings); + int before = identities.all().size(); + TeamSpeakImporter importer = new TeamSpeakImporter(identities, new Bookmarks(), settings); + + TeamSpeakImporter.Result first = importer.importIdentities(SyncItemsTest.fixture()); + TeamSpeakImporter.Result second = importer.importIdentities(SyncItemsTest.fixture()); + assertEquals(1, first.identities()); + assertEquals(1, second.identitiesKnown()); + assertEquals(before + first.identitiesAdded(), identities.all().size()); + assertNotNull(identities.byId(settings.defaultIdentityId)); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakSettingsDbTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakSettingsDbTest.java new file mode 100644 index 0000000..cf319d6 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakSettingsDbTest.java @@ -0,0 +1,64 @@ +package eu.lixko.ts3j.client.teamspeak; + +import eu.lixko.ts3j.client.contacts.Contact; +import eu.lixko.ts3j.client.contacts.ContactType; +import eu.lixko.ts3j.client.contacts.NicknameDisplay; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class TeamSpeakSettingsDbTest { + + private static File fixture() { + return new File(TeamSpeakSettingsDbTest.class.getResource("/teamspeak/settings.db").getFile()); + } + + @Test + void readsEveryContactOutOfTheDatabase() throws Exception { + List contacts = TeamSpeakSettingsDb.readContacts(fixture()); + assertEquals(60, contacts.size()); + + Contact alice = byUid(contacts, "AbCdEfGh1234567890abcdefghijk="); + assertEquals("Alice", alice.nickname); + assertEquals(ContactType.FRIEND, alice.type); + assertTrue(alice.hasVolumeModifier); + assertEquals(-6.0, alice.volumeModifier); + assertEquals("Test Server", alice.lastSeenServerName); + assertEquals(2024, alice.lastSeen.getYear()); + + Contact bob = byUid(contacts, "Zyxwvutsrqponmlkjihgfedcba00="); + assertEquals(ContactType.BLOCKED, bob.type); + assertTrue(bob.automute); + assertTrue(bob.ignorePokes); + assertTrue(!bob.whisperAllowed); + assertEquals(NicknameDisplay.ONLY_CUSTOM, bob.nicknameDisplay); + } + + /** The third record spills onto overflow pages at the fixture's 512-byte page size. */ + @Test + void followsOverflowPagesAndKeepsUnicode() throws Exception { + Contact carol = byUid(TeamSpeakSettingsDb.readContacts(fixture()), "Neutral0000000000000000000000="); + assertEquals("Carol Ünïcødé", carol.nickname); + assertEquals("Karol", carol.phoneticNickname); + assertEquals("X".repeat(900), carol.lastSeenServerName); + } + + @Test + void parsesColumnNamesOutOfCreateTable() { + assertEquals(List.of("timestamp", "key", "value"), SqliteReader.columnNames( + "CREATE TABLE Contacts (timestamp INTEGER UNSIGNED NOT NULL, key VARCHAR NOT NULL UNIQUE, value VARCHAR)")); + assertEquals(List.of("a", "b"), SqliteReader.columnNames( + "CREATE TABLE \"t\"(\"a\" TEXT, [b] INT, PRIMARY KEY (a, b))")); + } + + private static Contact byUid(List contacts, String uid) { + for (Contact c : contacts) if (c.uniqueId.equals(uid)) return c; + assertNotNull(null, "no contact " + uid); + return null; + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/text/BBCodeLinksTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/text/BBCodeLinksTest.java new file mode 100644 index 0000000..a921c34 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/text/BBCodeLinksTest.java @@ -0,0 +1,48 @@ +package eu.lixko.ts3j.client.text; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The server log's renderer: it turns the client's own links into anchors and leaves + * everything else — names carrying bracket markup included — as plain text. + */ +class BBCodeLinksTest { + + @Test + void rendersClientAndChannelLinks() { + String log = TsLink.clientBBCode(7, "uid=", "Bob") + " connected to channel \"" + + TsLink.channelBBCode(3, "Lobby") + "\""; + String html = BBCode.linksToHtml(log); + assertTrue(html.contains("href=\"client://7/uid=~Bob\""), html); + assertTrue(html.contains(">Bob"), html); + assertTrue(html.contains("href=\"channel://3/Lobby\""), html); + assertTrue(html.contains(">Lobby"), html); + } + + @Test + void rendersTheOfflineMessagesLink() { + String html = BBCode.linksToHtml("You have " + TsLink.offlineMessagesBBCode("2 unread offline messages")); + assertTrue(html.contains("href=\"offline://\""), html); + assertTrue(html.contains(">2 unread offline messages"), html); + assertTrue(TsLink.isOfflineMessages("offline://")); + } + + @Test + void leavesOtherMarkupLiteral() { + assertEquals("[b]not bold[/b] & <i>", BBCode.linksToHtml("[b]not bold[/b] & ")); + } + + @Test + void keepsBracketsInsideALabelLiteral() { + String html = BBCode.linksToHtml(TsLink.channelBBCode(3, "[cspacer]---")); + assertTrue(html.contains(">[cspacer]---"), html); + } + + @Test + void rejectsHrefsThatAreNotLinks() { + assertEquals("[url=javascript:alert(1)]x[/url]", BBCode.linksToHtml("[url=javascript:alert(1)]x[/url]")); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/text/BBCodePlainTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/text/BBCodePlainTest.java new file mode 100644 index 0000000..aabafcd --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/text/BBCodePlainTest.java @@ -0,0 +1,15 @@ +package eu.lixko.ts3j.client.text; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** Messages shown where no formatting renders, such as a system notification. */ +class BBCodePlainTest { + + @Test + void dropsMarkupAndKeepsText() { + assertEquals("Hello bold & and a link", + BBCode.toPlain("Hello [b]bold[/b] & and [url=https://x.y]a link[/url]")); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/text/BBCodeTagsTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/text/BBCodeTagsTest.java new file mode 100644 index 0000000..7dfbd79 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/text/BBCodeTagsTest.java @@ -0,0 +1,67 @@ +package eu.lixko.ts3j.client.text; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +/** The block tags TeamSpeak's own client renders in descriptions. */ +class BBCodeTagsTest { + + @Test + void rulesStandAlone() { + assertEquals("a
    b", BBCode.toHtml("a[hr]b")); + assertEquals("a
    b", BBCode.toHtml("a[hr][/hr]b")); + } + + @Test + void alignsBlocks() { + assertEquals("
    x
    y
    ", + BBCode.toHtml("[right]x[/right][justify]y[/justify]")); + } + + @Test + void numbersLists() { + assertEquals("
    1. one
    2. two
    ", BBCode.toHtml("[list=1][*]one[*]two[/list]")); + assertEquals("
    1. x
    ", BBCode.toHtml("[list=a][*]x[/list]")); + } + + @Test + void buildsTablesOnlyWhereTheyNest() { + assertEquals("
    hd
    ", + BBCode.toHtml("[table][tr][th]h[/th][td]d[/td][/tr][/table]")); + assertEquals("[td]loose[/td]", BBCode.toHtml("[td]loose[/td]")); + } + + @Test + void showsPicturesOnlyWhereAsked() { + String bb = "[img]https://example.com/a.png[/img]"; + assertEquals("", BBCode.toHtml(bb, true)); + assertEquals("https://example.com/a.png", + BBCode.toHtml(bb)); + } + + @Test + void linksPicturesInsideALink() { + assertEquals("", + BBCode.toHtml("[url=https://x.org][img]http://x.org/b.gif[/img][/url]", true)); + } + + @Test + void showsNoPictureFromElsewhereThanTheWeb() { + assertEquals("[img]file:///etc/passwd[/img]", BBCode.toHtml("[img]file:///etc/passwd[/img]", true)); + assertFalse(BBCode.toHtml("[img=https://x.org/a.png]", true).contains("", BBCode.toHtml("[img]https://x.org/a.png?a=1&b=2[/img]", true)); + } + + @Test + void shortensLongAddressesToHostAndFile() { + assertEquals("https://x.org/a.png", BBCode.shortAddress("https://x.org/a.png")); + assertEquals("upload.wikimedia.org/…/250px-Example.png", BBCode.shortAddress( + "https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/Example.png/250px-Example.png")); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/text/ChatHtmlAttachmentTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/text/ChatHtmlAttachmentTest.java new file mode 100644 index 0000000..55cec72 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/text/ChatHtmlAttachmentTest.java @@ -0,0 +1,58 @@ +package eu.lixko.ts3j.client.text; + +import eu.lixko.ts3j.client.chatlog.ChatLogScope; +import eu.lixko.ts3j.client.chatlog.ChatLogStore; +import eu.lixko.ts3j.client.myts.ChatAttachment; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Path; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ChatHtmlAttachmentTest { + + private static final String ROOM = "+Tyg2JtxE8vRNZp+JiUBnmBh0MY="; + private static final ChatAttachment PICTURE = ChatAttachment.of("f1", "abc", "cat.png", 532); + private static final ChatAttachment FILE = ChatAttachment.of("f2", "abc", "notes <1>.txt", 3 << 20); + + @Test + void showsAPictureAsOne() { + String html = ChatHtml.message(5, "uid", "alice", PICTURE.toMessage(), ROOM); + assertTrue(html.contains(""), html); + assertFalse(html.contains("msg_type"), html); + } + + @Test + void showsAnyOtherFileAsALinkWithItsSize() { + String html = ChatHtml.message(5, "uid", "alice", FILE.toMessage(), ROOM); + assertTrue(html.contains("href=\"" + FILE.href(ROOM) + "\">notes <1>.txt"), html); + assertTrue(html.contains("(3.0 MB)"), html); + } + + @Test + void namesTheFileWhereItCannotBeFetched() { + String html = ChatHtml.message(5, "uid", "alice", PICTURE.toMessage()); + assertFalse(html.contains(" history = logs.channelHtmlHistory(); + String html = ChatHtml.logEntry(history.get(history.size() - 1), ROOM); + assertTrue(html.contains(""), html); + assertFalse(html.contains("msg_type"), html); + } + + @Test + void previewsAFileByItsName() { + assertEquals("cat.png", ChatHtml.plainMessage(PICTURE.toMessage())); + assertEquals("hi", ChatHtml.plainMessage("[b]hi[/b]")); + } +} diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/text/TextQueryTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/text/TextQueryTest.java new file mode 100644 index 0000000..fcba207 --- /dev/null +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/text/TextQueryTest.java @@ -0,0 +1,47 @@ +package eu.lixko.ts3j.client.text; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class TextQueryTest { + + @Test + void ignoresCaseUnlessAsked() { + assertTrue(new TextQuery("hello", false, false, false).matches("Say HELLO there")); + assertFalse(new TextQuery("hello", true, false, false).matches("Say HELLO there")); + assertTrue(new TextQuery("čau", false, false, false).matches("ČAU")); + } + + @Test + void wholeWordsStopAtLettersAndDigitsOnly() { + TextQuery q = new TextQuery("cat", false, true, false); + assertTrue(q.matches("the cat sat")); + assertTrue(q.matches("(cat)")); + assertFalse(q.matches("concatenate")); + assertFalse(q.matches("cat2")); + assertTrue(new TextQuery("@all", false, true, false).matches("hey @all!")); + } + + @Test + void literalUnlessRegex() { + assertFalse(new TextQuery("a.c", false, false, false).matches("abc")); + assertTrue(new TextQuery("a.c", false, false, true).matches("abc")); + } + + @Test + void invalidRegexMatchesNothing() { + TextQuery q = new TextQuery("(", false, false, true); + assertTrue(q.isInvalid()); + assertFalse(q.matches("(")); + } + + @Test + void plainTextOfHtml() { + assertEquals("<\"x\"> a & b", HtmlText.plain("<"x"> a & b")); + assertEquals("line\nnext", HtmlText.plain("line
    next")); + assertEquals("é", HtmlText.plain("é")); + } +} diff --git a/ts3-client/core/src/test/resources/com/ts3client/audio/processing/golden-ns0.s16 b/ts3-client/core/src/test/resources/eu/lixko/ts3j/client/audio/processing/golden-ns0.s16 similarity index 100% rename from ts3-client/core/src/test/resources/com/ts3client/audio/processing/golden-ns0.s16 rename to ts3-client/core/src/test/resources/eu/lixko/ts3j/client/audio/processing/golden-ns0.s16 diff --git a/ts3-client/core/src/test/resources/com/ts3client/audio/processing/golden-ns1-typing.s16 b/ts3-client/core/src/test/resources/eu/lixko/ts3j/client/audio/processing/golden-ns1-typing.s16 similarity index 100% rename from ts3-client/core/src/test/resources/com/ts3client/audio/processing/golden-ns1-typing.s16 rename to ts3-client/core/src/test/resources/eu/lixko/ts3j/client/audio/processing/golden-ns1-typing.s16 diff --git a/ts3-client/core/src/test/resources/com/ts3client/audio/processing/golden-ns1.s16 b/ts3-client/core/src/test/resources/eu/lixko/ts3j/client/audio/processing/golden-ns1.s16 similarity index 100% rename from ts3-client/core/src/test/resources/com/ts3client/audio/processing/golden-ns1.s16 rename to ts3-client/core/src/test/resources/eu/lixko/ts3j/client/audio/processing/golden-ns1.s16 diff --git a/ts3-client/core/src/test/resources/com/ts3client/audio/processing/golden-ns2.s16 b/ts3-client/core/src/test/resources/eu/lixko/ts3j/client/audio/processing/golden-ns2.s16 similarity index 100% rename from ts3-client/core/src/test/resources/com/ts3client/audio/processing/golden-ns2.s16 rename to ts3-client/core/src/test/resources/eu/lixko/ts3j/client/audio/processing/golden-ns2.s16 diff --git a/ts3-client/core/src/test/resources/com/ts3client/audio/processing/golden-ns3.s16 b/ts3-client/core/src/test/resources/eu/lixko/ts3j/client/audio/processing/golden-ns3.s16 similarity index 100% rename from ts3-client/core/src/test/resources/com/ts3client/audio/processing/golden-ns3.s16 rename to ts3-client/core/src/test/resources/eu/lixko/ts3j/client/audio/processing/golden-ns3.s16 diff --git a/ts3-client/desktop/pom.xml b/ts3-client/desktop/pom.xml index a4fd4a1..4254de2 100644 --- a/ts3-client/desktop/pom.xml +++ b/ts3-client/desktop/pom.xml @@ -5,18 +5,18 @@ 4.0.0 - com.ts3client + eu.lixko.ts3j.client ts3-client-parent 0.1.0 ts3-client-desktop - TS3J Client Desktop Audio + TeamSpook TS3j Desktop Audio Desktop audio backend: PipeWire/Java Sound capture/playback and native Opus via the FFM API - com.ts3client + eu.lixko.ts3j.client ts3-client-core diff --git a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/AudioDevices.java b/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/AudioDevices.java deleted file mode 100644 index 3ed2a7f..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/AudioDevices.java +++ /dev/null @@ -1,210 +0,0 @@ -package com.ts3client.audio.desktop; - -import com.ts3client.audio.AudioCapture; -import com.ts3client.audio.AudioDevice; -import com.ts3client.audio.AudioIo; -import com.ts3client.audio.AudioPlayback; -import com.ts3client.audio.VoiceFormat; -import com.ts3client.audio.desktop.pipewire.PipeWire; - -import javax.sound.sampled.AudioFormat; -import javax.sound.sampled.AudioSystem; -import javax.sound.sampled.DataLine; -import javax.sound.sampled.Line; -import javax.sound.sampled.LineUnavailableException; -import javax.sound.sampled.Mixer; -import javax.sound.sampled.SourceDataLine; -import javax.sound.sampled.TargetDataLine; -import java.util.ArrayList; -import java.util.List; - -/** - * Enumerates audio devices and opens capture/playback lines on them. - * - *

    The TS3 protocol uses 48 kHz 16-bit signed little-endian PCM for Opus, mono for - * {@code OPUS_VOICE} and stereo for {@code OPUS_MUSIC}, so the channel count is - * negotiated per line rather than fixed. - * - *

    Two backends sit behind {@link AudioCapture} / {@link AudioPlayback}: - *

      - *
    • {@link PipeWire} — used for the system default and for every {@code pw:} device - * when a PipeWire session is reachable. It sees the graph's real devices and each - * stream shows up separately in volume mixers.
    • - *
    • Java Sound — everywhere else, and for the raw ALSA devices which stay in the - * list because they still work without PipeWire and can be opened exclusively.
    • - *
    - * - *

    Java Sound enumeration deliberately asks only for "a mixer that can do - * capture/playback" instead of "a mixer that can do exactly this format": the PipeWire - * and PulseAudio ALSA plugins advertise a narrow set of formats (typically stereo only), - * so a format-specific query hides them entirely. The desired format is negotiated in - * {@link #openCapture} / {@link #openPlayback}, which fall back through the supported - * channel counts. - */ -public final class AudioDevices implements AudioIo { - - public static final AudioDevices INSTANCE = new AudioDevices(); - - /** Buffer size, in 20 ms frames, requested when opening a Java Sound line. */ - private static final int BUFFER_FRAMES = 8; - - /** Marks a device id as a PipeWire node name rather than a Java Sound mixer name. */ - private static final String PIPEWIRE_PREFIX = "pw:"; - - private AudioDevices() { - } - - /** 48 kHz signed 16-bit little-endian PCM with the given channel count. */ - public static AudioFormat format(int channels) { - return new AudioFormat(VoiceFormat.SAMPLE_RATE, 16, channels, true, false); - } - - @Override - public List inputDevices() { - return devices(TargetDataLine.class, false); - } - - @Override - public List outputDevices() { - return devices(SourceDataLine.class, true); - } - - private static List devices(Class lineClass, boolean sinks) { - List devices = new ArrayList<>(); - devices.add(AudioDevice.DEFAULT); - - for (PipeWire.Node node : PipeWire.nodes()) { - if (node.sink() == sinks) { - devices.add(new AudioDevice(PIPEWIRE_PREFIX + node.name(), node.description())); - } - } - - Line.Info anyFormat = new Line.Info(lineClass); - for (Mixer.Info mi : AudioSystem.getMixerInfo()) { - String name = mi.getName(); - if (name == null || name.isEmpty()) continue; - // The ALSA "default" PCM is what the system-default entry already opens. - if (isDefaultMixer(name)) continue; - if (!AudioSystem.getMixer(mi).isLineSupported(anyFormat)) continue; - if (devices.stream().anyMatch(d -> d.id().equals(name))) continue; - devices.add(new AudioDevice(name, "ALSA: " + name)); - } - return devices; - } - - /** - * Java Sound names its ALSA {@code default} mixer after the PCM it opened, which under - * pipewire-alsa is our own stream node (e.g. {@code alsa_playback.java [default]}), so - * only the bracketed device part is stable. - */ - private static boolean isDefaultMixer(String mixerName) { - return mixerName.endsWith("[default]"); - } - - @Override - public AudioCapture openCapture(String deviceId, int preferredChannels) - throws LineUnavailableException { - if (usePipeWire(deviceId)) { - try { - return PipeWire.openCapture("TS3J Microphone", pipeWireNode(deviceId), - VoiceFormat.SAMPLE_RATE, clampChannels(preferredChannels)); - } catch (Exception e) { - if (isPipeWireDevice(deviceId)) throw unavailable(true, deviceId, e); - // The default device: Java Sound may still reach it through ALSA. - } - } - return new JavaSoundCapture(open(TargetDataLine.class, deviceId, preferredChannels)); - } - - @Override - public AudioPlayback openPlayback(String deviceId, int preferredChannels) - throws LineUnavailableException { - if (usePipeWire(deviceId)) { - try { - return PipeWire.openPlayback("TS3J Playback", pipeWireNode(deviceId), - VoiceFormat.SAMPLE_RATE, clampChannels(preferredChannels)); - } catch (Exception e) { - if (isPipeWireDevice(deviceId)) throw unavailable(false, deviceId, e); - } - } - return new JavaSoundPlayback(open(SourceDataLine.class, deviceId, preferredChannels)); - } - - /** - * PipeWire handles its own devices and, when a session is running, the system default - * too — a Java Sound "default" would only reach the same graph through the ALSA - * compatibility plugin, with no way to pick the device. - */ - private static boolean usePipeWire(String deviceId) { - if (!isPipeWireDevice(deviceId) && !isDefault(deviceId)) return false; - return PipeWire.isAvailable(); - } - - private static boolean isDefault(String deviceId) { - return deviceId == null || deviceId.isEmpty(); - } - - private static boolean isPipeWireDevice(String deviceId) { - return deviceId != null && deviceId.startsWith(PIPEWIRE_PREFIX); - } - - /** The PipeWire node name behind a device id; empty for "let the server choose". */ - private static String pipeWireNode(String deviceId) { - return isPipeWireDevice(deviceId) ? deviceId.substring(PIPEWIRE_PREFIX.length()) : ""; - } - - /** PipeWire converts freely, so any channel count works; keep it in the range we handle. */ - private static int clampChannels(int channels) { - return Math.max(1, Math.min(VoiceFormat.MAX_CHANNELS, channels)); - } - - private static T open(Class lineClass, String deviceId, int preferredChannels) - throws LineUnavailableException { - Mixer mixer = findMixer(deviceId, lineClass); // null -> platform default - Exception failure = null; - for (int channels : channelOrder(preferredChannels)) { - AudioFormat fmt = format(channels); - DataLine.Info info = new DataLine.Info(lineClass, fmt); - try { - T line = lineClass.cast( - (mixer != null) ? mixer.getLine(info) : AudioSystem.getLine(info)); - openLine(line, fmt, VoiceFormat.FRAME_SIZE * 2 * fmt.getChannels() * BUFFER_FRAMES); - return line; - } catch (Exception e) { - failure = e; - } - } - throw unavailable(lineClass == TargetDataLine.class, deviceId, failure); - } - - private static LineUnavailableException unavailable(boolean capture, String deviceId, - Exception failure) { - LineUnavailableException e = new LineUnavailableException( - "No usable " + (capture ? "capture" : "playback") + " line for " - + (isDefault(deviceId) ? "the system default" : deviceId)); - if (failure != null) e.initCause(failure); - return e; - } - - /** {@code open(format, bufferSize)} lives on the two line interfaces, not on {@code DataLine}. */ - private static void openLine(DataLine line, AudioFormat fmt, int bufferSize) - throws LineUnavailableException { - if (line instanceof TargetDataLine target) target.open(fmt, bufferSize); - else ((SourceDataLine) line).open(fmt, bufferSize); - } - - private static int[] channelOrder(int preferred) { - return preferred >= 2 ? new int[]{2, 1} : new int[]{1, 2}; - } - - private static Mixer findMixer(String deviceId, Class lineClass) { - if (isDefault(deviceId) || isPipeWireDevice(deviceId)) return null; - Line.Info anyFormat = new Line.Info(lineClass); - for (Mixer.Info mi : AudioSystem.getMixerInfo()) { - if (!deviceId.equals(mi.getName())) continue; - Mixer mixer = AudioSystem.getMixer(mi); - if (mixer.isLineSupported(anyFormat)) return mixer; - } - return null; // device went away: fall back to the system default - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/DesktopAudioBackend.java b/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/DesktopAudioBackend.java deleted file mode 100644 index 94c123b..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/DesktopAudioBackend.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.ts3client.audio.desktop; - -import com.ts3client.audio.AudioBackend; -import com.ts3client.audio.AudioIo; -import com.ts3client.audio.StreamingVoiceOutput; -import com.ts3client.audio.desktop.pipewire.PipeWire; -import com.ts3client.audio.opus.OpusCodec; - -/** - * Desktop audio backend: PipeWire for capture/playback where it is running, Java Sound - * everywhere else, and native Opus (via the FFM API) for the codec. - */ -public final class DesktopAudioBackend implements AudioBackend { - - private final OpusCodec opus = new NativeOpusCodec(); - - @Override - public AudioIo io() { - return AudioDevices.INSTANCE; - } - - @Override - public OpusCodec opus() { - return opus; - } - - /** Every speaker gets a line of their own, so each shows up in the desktop's mixer. */ - @Override - public StreamingVoiceOutput.Lines outputLines() { - return StreamingVoiceOutput.Lines.PER_SPEAKER; - } - - @Override - public String description() { - return codec() + ", " + audioSystem(); - } - - private String codec() { - try { - return "Opus " + opus.version(); - } catch (Throwable t) { - return "Opus (native library unavailable)"; - } - } - - private static String audioSystem() { - String pipeWire = PipeWire.version(); - return pipeWire != null ? "PipeWire " + pipeWire : "Java Sound"; - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/EncodeSoundPacks.java b/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/EncodeSoundPacks.java deleted file mode 100644 index 536ff29..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/EncodeSoundPacks.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.ts3client.audio.desktop; - -import com.ts3client.sound.SoundPackConverter; - -import java.io.File; -import java.io.IOException; - -/** - * Converts a folder of sound packs to Opus with the bundled libopus — the Android build - * ships TeamSpeak's packs this way. - * - *

    Usage: {@code EncodeSoundPacks } - */ -public final class EncodeSoundPacks { - - private EncodeSoundPacks() { - } - - public static void main(String[] args) throws IOException { - if (args.length != 2) { - System.err.println("Usage: EncodeSoundPacks "); - System.exit(2); - } - SoundPackConverter.convert(new File(args[0]), new File(args[1]), new NativeOpusCodec()); - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/JavaSoundCapture.java b/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/JavaSoundCapture.java deleted file mode 100644 index 0f733d7..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/JavaSoundCapture.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.ts3client.audio.desktop; - -import com.ts3client.audio.AudioCapture; - -import javax.sound.sampled.TargetDataLine; - -/** {@link AudioCapture} backed by a Java Sound {@link TargetDataLine}. */ -final class JavaSoundCapture implements AudioCapture { - - private final TargetDataLine line; - - JavaSoundCapture(TargetDataLine line) { - this.line = line; - } - - @Override - public int channels() { - return line.getFormat().getChannels(); - } - - @Override - public void start() { - line.start(); - } - - /** {@code TargetDataLine.read} may return early, so it is repeated until satisfied. */ - @Override - public int read(byte[] buffer, int offset, int length) { - int read = 0; - while (read < length) { - int n; - try { - n = line.read(buffer, offset + read, length - read); - } catch (Exception e) { - break; - } - if (n <= 0) break; - read += n; - } - return read; - } - - @Override - public void close() { - try { - line.stop(); - line.close(); - } catch (Exception ignored) { - } - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/JavaSoundPlayback.java b/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/JavaSoundPlayback.java deleted file mode 100644 index aa25649..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/JavaSoundPlayback.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.ts3client.audio.desktop; - -import com.ts3client.audio.AudioPlayback; - -import javax.sound.sampled.SourceDataLine; - -/** {@link AudioPlayback} backed by a Java Sound {@link SourceDataLine}. */ -final class JavaSoundPlayback implements AudioPlayback { - - private final SourceDataLine line; - - JavaSoundPlayback(SourceDataLine line) { - this.line = line; - } - - @Override - public int channels() { - return line.getFormat().getChannels(); - } - - @Override - public void start() { - line.start(); - } - - @Override - public void write(byte[] buffer, int offset, int length) { - int written; - try { - written = line.write(buffer, offset, length); - } catch (RuntimeException e) { - throw new IllegalStateException("The playback line failed", e); - } - if (written < length && !line.isOpen()) throw new IllegalStateException("The playback line closed"); - } - - @Override - public void drain() { - try { - line.drain(); - } catch (Exception ignored) { - } - } - - @Override - public void close() { - try { - line.stop(); - line.close(); - } catch (Exception ignored) { - } - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/NativeOpusCodec.java b/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/NativeOpusCodec.java deleted file mode 100644 index 4bf2674..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/NativeOpusCodec.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.ts3client.audio.desktop; - -import com.ts3client.audio.opus.LibOpus; -import com.ts3client.audio.opus.OpusCodec; -import com.ts3client.audio.opus.OpusDecoder; -import com.ts3client.audio.opus.OpusEncoder; - -/** The system's (or the bundled) libopus, reached through the FFM API. */ -public final class NativeOpusCodec implements OpusCodec { - - @Override - public OpusEncoder createEncoder(int sampleRate, int frameSize, int channels, Application application) { - return new NativeOpusEncoder(sampleRate, frameSize, channels, LibOpus.application(application)); - } - - @Override - public OpusDecoder createDecoder(int sampleRate, int maxFrameSize, int channels) { - return new NativeOpusDecoder(sampleRate, maxFrameSize, channels); - } - - @Override - public String version() { - return Opus.getVersionString(); - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/NativeOpusDecoder.java b/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/NativeOpusDecoder.java deleted file mode 100644 index c1c5615..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/NativeOpusDecoder.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.ts3client.audio.desktop; - -import com.ts3client.audio.opus.LibOpus; -import com.ts3client.audio.opus.OpusDecoder; - -import java.lang.foreign.Arena; -import java.lang.foreign.MemorySegment; -import java.lang.foreign.ValueLayout; - -/** - * Thin wrapper around a native Opus decoder. - * - *

    Fixed at 48 kHz. The channel count should match the stream being decoded - * (mono for {@code OPUS_VOICE}, stereo for {@code OPUS_MUSIC}); Opus will up-/down-mix - * a mismatched stream, which costs the stereo image. - */ -final class NativeOpusDecoder implements OpusDecoder { - - private static final int MAX_PACKET_BYTES = 4096; - - private final Arena arena = Arena.ofShared(); - private final MemorySegment handle; - private final MemorySegment packetBuffer; - private final MemorySegment pcmBuffer; - private final int frameSize; - private final int channels; - private boolean closed; - - NativeOpusDecoder(int sampleRate, int frameSize, int channels) { - this.frameSize = frameSize; - this.channels = channels; - - MemorySegment error = arena.allocate(ValueLayout.JAVA_INT); - MemorySegment created = Opus.decoderCreate(sampleRate, channels, error); - int errorCode = error.get(ValueLayout.JAVA_INT, 0); - if (created.address() == 0 || errorCode != 0) { - arena.close(); - throw new IllegalStateException("opus_decoder_create failed: " + Opus.strerror(errorCode)); - } - - this.handle = created; - this.packetBuffer = arena.allocate(MAX_PACKET_BYTES); - this.pcmBuffer = arena.allocate(ValueLayout.JAVA_FLOAT, (long) frameSize * channels); - } - - /** - * @param packet an Opus packet, at most {@value #MAX_PACKET_BYTES} bytes - * @param out output buffer, at least {@code frameSize * channels} long - * @return number of samples decoded per channel - */ - @Override - public int decode(byte[] packet, float[] out) { - if (packet.length > MAX_PACKET_BYTES) { - throw new IllegalArgumentException("packet too large: " + packet.length); - } - MemorySegment.copy(packet, 0, packetBuffer, ValueLayout.JAVA_BYTE, 0, packet.length); - return decode(packetBuffer, packet.length, out, frameSize, 0); - } - - @Override - public int conceal(float[] out, int frameSize) { - return decode(MemorySegment.NULL, 0, out, Math.min(frameSize, this.frameSize), 0); - } - - @Override - public int recover(byte[] next, float[] out, int frameSize) { - if (next.length > MAX_PACKET_BYTES) { - throw new IllegalArgumentException("packet too large: " + next.length); - } - MemorySegment.copy(next, 0, packetBuffer, ValueLayout.JAVA_BYTE, 0, next.length); - return decode(packetBuffer, next.length, out, Math.min(frameSize, this.frameSize), 1); - } - - private int decode(MemorySegment data, int len, float[] out, int maxSamples, int fec) { - if (closed) throw new IllegalStateException("decoder closed"); - int samples = Opus.decodeFloat(handle, data, len, pcmBuffer, maxSamples, fec); - if (samples < 0) { - throw new IllegalStateException("opus_decode_float failed: " + Opus.strerror(samples)); - } - MemorySegment.copy(pcmBuffer, ValueLayout.JAVA_FLOAT, 0, out, 0, samples * channels); - return samples; - } - - @Override - public void reset() { - if (closed) return; - Opus.decoderCtl(handle, LibOpus.RESET_STATE, 0); - } - - @Override - public void close() { - if (closed) return; - closed = true; - Opus.decoderDestroy(handle); - arena.close(); - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/NativeOpusEncoder.java b/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/NativeOpusEncoder.java deleted file mode 100644 index 959f62a..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/NativeOpusEncoder.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.ts3client.audio.desktop; - -import com.ts3client.audio.opus.CtlOpusEncoder; - -import java.lang.foreign.Arena; -import java.lang.foreign.MemorySegment; -import java.lang.foreign.ValueLayout; - -/** - * Thin wrapper around a native Opus encoder configured for TeamSpeak voice. - * - *

    Fixed at 48 kHz. Frames are 20 ms (960 samples per channel), which - * is the frame size the TS3 client uses. - * - *

    The native scratch buffers live in a shared arena owned by this instance and - * are freed by {@link #close()}; access is serialised by the instance lock, so the - * encoder may be driven from any thread. - */ -final class NativeOpusEncoder extends CtlOpusEncoder { - - private static final int MAX_PACKET_BYTES = 4096; - - private final Arena arena = Arena.ofShared(); - private final MemorySegment handle; - private final MemorySegment pcmBuffer; - private final MemorySegment packetBuffer; - private final int frameSize; - private final int channels; - private final Object lock = new Object(); - private boolean closed; - - NativeOpusEncoder(int sampleRate, int frameSize, int channels, int application) { - this.frameSize = frameSize; - this.channels = channels; - - MemorySegment error = arena.allocate(ValueLayout.JAVA_INT); - MemorySegment created = Opus.encoderCreate(sampleRate, channels, application, error); - int errorCode = error.get(ValueLayout.JAVA_INT, 0); - if (created.address() == 0 || errorCode != 0) { - arena.close(); - throw new IllegalStateException("opus_encoder_create failed: " + Opus.strerror(errorCode)); - } - - this.handle = created; - this.pcmBuffer = arena.allocate(ValueLayout.JAVA_FLOAT, (long) frameSize * channels); - this.packetBuffer = arena.allocate(MAX_PACKET_BYTES); - } - - @Override - protected void ctl(int request, int value) { - synchronized (lock) { - if (closed) return; - int r = Opus.encoderCtl(handle, request, value); - if (r < 0) { - throw new IllegalStateException("opus_encoder_ctl(" + request + ") failed: " - + Opus.strerror(r)); - } - } - } - - /** - * Encodes one frame of interleaved float PCM ({@code frameSize * channels} samples) - * into an Opus packet. - * - * @return a newly allocated byte array holding the encoded packet - */ - @Override - public byte[] encode(float[] pcm) { - int expected = frameSize * channels; - if (pcm.length != expected) { - throw new IllegalArgumentException("expected " + expected + " samples, got " + pcm.length); - } - synchronized (lock) { - if (closed) throw new IllegalStateException("encoder closed"); - MemorySegment.copy(pcm, 0, pcmBuffer, ValueLayout.JAVA_FLOAT, 0, expected); - int len = Opus.encodeFloat(handle, pcmBuffer, frameSize, packetBuffer, MAX_PACKET_BYTES); - if (len < 0) { - throw new IllegalStateException("opus_encode_float failed: " + Opus.strerror(len)); - } - byte[] packet = new byte[len]; - MemorySegment.copy(packetBuffer, ValueLayout.JAVA_BYTE, 0, packet, 0, len); - return packet; - } - } - - @Override - public void close() { - synchronized (lock) { - if (closed) return; - closed = true; - Opus.encoderDestroy(handle); - arena.close(); - } - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/Opus.java b/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/Opus.java deleted file mode 100644 index 4dfb692..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/Opus.java +++ /dev/null @@ -1,264 +0,0 @@ -package com.ts3client.audio.desktop; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.foreign.Arena; -import java.lang.foreign.FunctionDescriptor; -import java.lang.foreign.Linker; -import java.lang.foreign.MemorySegment; -import java.lang.foreign.SymbolLookup; -import java.lang.foreign.ValueLayout; -import java.lang.invoke.MethodHandle; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardCopyOption; -import java.util.List; - -/** - * Binding to the native Opus codec library (libopus) via the Foreign Function & - * Memory API (project Panama). - * - *

    The library is resolved by first trying the system-installed {@code libopus} - * under its usual SONAMEs; failing that, the copy we bundle on the classpath for - * the running platform (e.g. {@code linux-x86-64/libopus.so}, {@code win32-x86-64/opus.dll}) - * is extracted to a temporary file and loaded, so the client runs from the single - * JAR with no external Opus install. Opus always operates internally at 48 kHz - * which matches what the TeamSpeak 3 protocol uses on the wire. - */ -public final class Opus { - - private Opus() { - } - - private static final ValueLayout.OfInt INT = ValueLayout.JAVA_INT; - private static final java.lang.foreign.AddressLayout PTR = ValueLayout.ADDRESS; - - private static final Linker LINKER = Linker.nativeLinker(); - private static final SymbolLookup LOOKUP = NativeLibraries.loadOpus(); - - // OpusEncoder *opus_encoder_create(opus_int32 fs, int channels, int application, int *error) - private static final MethodHandle ENCODER_CREATE = - downcall("opus_encoder_create", FunctionDescriptor.of(PTR, INT, INT, INT, PTR)); - // opus_int32 opus_encode_float(OpusEncoder *st, const float *pcm, int frame_size, - // unsigned char *data, opus_int32 max_data_bytes) - private static final MethodHandle ENCODE_FLOAT = - downcall("opus_encode_float", FunctionDescriptor.of(INT, PTR, PTR, INT, PTR, INT)); - private static final MethodHandle ENCODER_DESTROY = - downcall("opus_encoder_destroy", FunctionDescriptor.ofVoid(PTR)); - - // OpusDecoder *opus_decoder_create(opus_int32 fs, int channels, int *error) - private static final MethodHandle DECODER_CREATE = - downcall("opus_decoder_create", FunctionDescriptor.of(PTR, INT, INT, PTR)); - // int opus_decode_float(OpusDecoder *st, const unsigned char *data, opus_int32 len, - // float *pcm, int frame_size, int decode_fec) - private static final MethodHandle DECODE_FLOAT = - downcall("opus_decode_float", FunctionDescriptor.of(INT, PTR, PTR, INT, PTR, INT, INT)); - private static final MethodHandle DECODER_DESTROY = - downcall("opus_decoder_destroy", FunctionDescriptor.ofVoid(PTR)); - - private static final MethodHandle STRERROR = - downcall("opus_strerror", FunctionDescriptor.of(PTR, INT)); - private static final MethodHandle GET_VERSION_STRING = - downcall("opus_get_version_string", FunctionDescriptor.of(PTR)); - - // int opus_encoder_ctl(OpusEncoder *st, int request, ...) — the value argument is - // variadic, so the linker must be told where the variadic part starts (index 2). - private static final MethodHandle ENCODER_CTL_SET = variadicCtl("opus_encoder_ctl"); - private static final MethodHandle DECODER_CTL_SET = variadicCtl("opus_decoder_ctl"); - - private static MethodHandle downcall(String symbol, FunctionDescriptor descriptor) { - return LINKER.downcallHandle(find(symbol), descriptor); - } - - private static MethodHandle variadicCtl(String symbol) { - return LINKER.downcallHandle( - find(symbol), - FunctionDescriptor.of(INT, PTR, INT, INT), - Linker.Option.firstVariadicArg(2)); - } - - private static MemorySegment find(String symbol) { - return LOOKUP.find(symbol) - .orElseThrow(() -> new UnsatisfiedLinkError("libopus: unresolved symbol " + symbol)); - } - - static MemorySegment encoderCreate(int sampleRate, int channels, int application, MemorySegment error) { - try { - return (MemorySegment) ENCODER_CREATE.invokeExact(sampleRate, channels, application, error); - } catch (Throwable t) { - throw wrap(t); - } - } - - static int encodeFloat(MemorySegment st, MemorySegment pcm, int frameSize, - MemorySegment data, int maxDataBytes) { - try { - return (int) ENCODE_FLOAT.invokeExact(st, pcm, frameSize, data, maxDataBytes); - } catch (Throwable t) { - throw wrap(t); - } - } - - static void encoderDestroy(MemorySegment st) { - try { - ENCODER_DESTROY.invokeExact(st); - } catch (Throwable t) { - throw wrap(t); - } - } - - static int encoderCtl(MemorySegment st, int request, int value) { - try { - return (int) ENCODER_CTL_SET.invokeExact(st, request, value); - } catch (Throwable t) { - throw wrap(t); - } - } - - static MemorySegment decoderCreate(int sampleRate, int channels, MemorySegment error) { - try { - return (MemorySegment) DECODER_CREATE.invokeExact(sampleRate, channels, error); - } catch (Throwable t) { - throw wrap(t); - } - } - - static int decodeFloat(MemorySegment st, MemorySegment data, int len, - MemorySegment pcm, int frameSize, int decodeFec) { - try { - return (int) DECODE_FLOAT.invokeExact(st, data, len, pcm, frameSize, decodeFec); - } catch (Throwable t) { - throw wrap(t); - } - } - - static void decoderDestroy(MemorySegment st) { - try { - DECODER_DESTROY.invokeExact(st); - } catch (Throwable t) { - throw wrap(t); - } - } - - static int decoderCtl(MemorySegment st, int request, int value) { - try { - return (int) DECODER_CTL_SET.invokeExact(st, request, value); - } catch (Throwable t) { - throw wrap(t); - } - } - - /** Human-readable message for an Opus error code. */ - public static String strerror(int error) { - try { - MemorySegment message = (MemorySegment) STRERROR.invokeExact(error); - return cString(message); - } catch (Throwable t) { - throw wrap(t); - } - } - - /** Version string of the loaded libopus, e.g. {@code libopus 1.4}. */ - public static String getVersionString() { - try { - MemorySegment version = (MemorySegment) GET_VERSION_STRING.invokeExact(); - return cString(version); - } catch (Throwable t) { - throw wrap(t); - } - } - - /** Reads a NUL-terminated C string from a zero-length (unbounded) return segment. */ - private static String cString(MemorySegment segment) { - if (segment.address() == 0) { - return null; - } - return segment.reinterpret(Long.MAX_VALUE).getString(0); - } - - private static RuntimeException wrap(Throwable t) { - if (t instanceof RuntimeException re) { - return re; - } - if (t instanceof Error e) { - throw e; - } - return new IllegalStateException("libopus call failed", t); - } - - /** - * Resolves libopus: system install first, bundled classpath copy second. - */ - private static final class NativeLibraries { - - static SymbolLookup loadOpus() { - Arena arena = Arena.global(); - for (String name : candidateNames()) { - try { - return SymbolLookup.libraryLookup(name, arena); - } catch (IllegalArgumentException ignored) { - // not present under this name; try the next one - } - } - return SymbolLookup.libraryLookup(extractBundled(), arena); - } - - /** SONAMEs/filenames a system-installed libopus may carry, in preference order. */ - private static List candidateNames() { - String os = System.getProperty("os.name", "").toLowerCase(); - if (os.contains("win")) { - return List.of("opus.dll", "libopus-0.dll", "libopus.dll"); - } - if (os.contains("mac") || os.contains("darwin")) { - return List.of("libopus.dylib", "libopus.0.dylib"); - } - return List.of("libopus.so.0", "libopus.so"); - } - - private static Path extractBundled() { - String libraryName = System.mapLibraryName("opus"); - for (String directory : platformDirectories()) { - String resource = directory + "/" + libraryName; - try (InputStream in = Opus.class.getClassLoader().getResourceAsStream(resource)) { - if (in == null) { - continue; - } - Path dir = Files.createTempDirectory("ts3-client-opus"); - dir.toFile().deleteOnExit(); - Path file = dir.resolve(libraryName); - Files.copy(in, file, StandardCopyOption.REPLACE_EXISTING); - file.toFile().deleteOnExit(); - return file; - } catch (IOException e) { - throw new UnsatisfiedLinkError("failed to extract bundled libopus: " + e); - } - } - throw new UnsatisfiedLinkError("libopus not found on this system and no bundled copy for " - + platformDirectories()); - } - - /** - * Classpath directories that may hold the bundled native (JNA's platform layout), - * most specific first — macOS also ships an architecture-agnostic {@code darwin/}. - */ - private static List platformDirectories() { - String os = System.getProperty("os.name", "").toLowerCase(); - String arch = System.getProperty("os.arch", "").toLowerCase(); - - String normalizedArch = switch (arch) { - case "amd64", "x86_64" -> "x86-64"; - case "i386", "i486", "i586", "i686", "x86" -> "x86"; - case "aarch64", "arm64" -> "aarch64"; - default -> arch.startsWith("arm") ? "arm" : arch; - }; - - if (os.contains("win")) { - return List.of("win32-" + normalizedArch); - } - if (os.contains("mac") || os.contains("darwin")) { - return List.of("darwin-" + normalizedArch, "darwin"); - } - return List.of("linux-" + normalizedArch); - } - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PcmRing.java b/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PcmRing.java deleted file mode 100644 index ff48d85..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PcmRing.java +++ /dev/null @@ -1,141 +0,0 @@ -package com.ts3client.audio.desktop.pipewire; - -import java.lang.foreign.MemorySegment; - -/** - * Byte ring buffer between the application threads and PipeWire's loop thread. - * - *

    The stream callbacks must never block — a late buffer is a glitch for the whole - * graph — so the loop side ({@link #put}/{@link #take}) always returns immediately and - * absorbs the mismatch: a capture overrun drops the oldest audio, a playback underrun is - * reported as a short read and padded with silence by the caller. The application side - * ({@link #write}/{@link #read}) blocks instead, which is what {@code SourceDataLine} and - * {@code TargetDataLine} do and what the voice pipeline expects. - */ -final class PcmRing { - - private final byte[] data; - private final MemorySegment view; - private int start; // index of the oldest byte - private int count; // bytes currently held - private boolean closed; - - PcmRing(int capacity) { - this.data = new byte[capacity]; - this.view = MemorySegment.ofArray(data); - } - - int capacity() { - return data.length; - } - - synchronized int available() { - return count; - } - - synchronized void clear() { - start = 0; - count = 0; - notifyAll(); - } - - /** Unblocks every waiter; subsequent reads report end-of-stream and writes are dropped. */ - synchronized void close() { - closed = true; - notifyAll(); - } - - synchronized boolean isClosed() { - return closed; - } - - // ---- loop-thread side (never blocks) ---- - - /** Appends up to {@code length} bytes, dropping the oldest audio if that overruns. */ - synchronized void put(MemorySegment source, long offset, int length) { - if (closed) return; - int overflow = count + length - data.length; - if (overflow > 0) skip(overflow); - int copied = Math.min(length, data.length); - long from = offset + (length - copied); - int end = (start + count) % data.length; - int firstChunk = Math.min(copied, data.length - end); - MemorySegment.copy(source, from, view, end, firstChunk); - MemorySegment.copy(source, from + firstChunk, view, 0, copied - firstChunk); - count += copied; - notifyAll(); - } - - /** Removes up to {@code length} bytes into {@code destination}; returns how many. */ - synchronized int take(MemorySegment destination, long offset, int length) { - int copied = Math.min(length, count); - int firstChunk = Math.min(copied, data.length - start); - MemorySegment.copy(view, start, destination, offset, firstChunk); - MemorySegment.copy(view, 0, destination, offset + firstChunk, copied - firstChunk); - skip(copied); - notifyAll(); - return copied; - } - - // ---- application side (blocks) ---- - - /** - * Blocks until {@code length} bytes have been read, the ring is closed, or the calling - * thread is interrupted. Returns the number of bytes actually read. - */ - synchronized int read(byte[] destination, int offset, int length) { - MemorySegment target = MemorySegment.ofArray(destination); - int read = 0; - while (read < length) { - if (count == 0) { - if (closed || !await()) break; - continue; - } - read += take(target, offset + read, length - read); - } - return read; - } - - /** - * Blocks until {@code length} bytes have been queued, the ring is closed, or the - * calling thread is interrupted. Returns the number of bytes actually written. - */ - synchronized int write(byte[] source, int offset, int length) { - MemorySegment target = MemorySegment.ofArray(source); - int written = 0; - while (written < length && !closed) { - int free = data.length - count; - if (free == 0) { - if (!await()) break; - continue; - } - int chunk = Math.min(free, length - written); - put(target, offset + written, chunk); - written += chunk; - } - return written; - } - - /** Blocks until the ring has drained (or was closed / the wait was interrupted). */ - synchronized void drain() { - while (count > 0 && !closed) { - if (!await()) return; - } - } - - /** Waits for a state change; {@code false} when interrupted. */ - private boolean await() { - try { - wait(100); - return true; - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return false; - } - } - - private void skip(int bytes) { - start = (start + bytes) % data.length; - count -= bytes; - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWire.java b/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWire.java deleted file mode 100644 index 3210361..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWire.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.ts3client.audio.desktop.pipewire; - -import com.ts3client.audio.AudioCapture; -import com.ts3client.audio.AudioPlayback; - -import java.util.List; - -/** - * PipeWire audio backend. - * - *

    On a PipeWire desktop this replaces Java Sound entirely: devices are enumerated - * from the graph — with their real names, including Bluetooth and virtual devices, - * which Java Sound's ALSA-only provider never sees — and capture and playback run as - * ordinary {@code pw_stream}s that appear individually in volume mixers. - * - *

    Everything here is a no-op on a machine without PipeWire: {@link #isAvailable()} - * reports {@code false} and {@link com.ts3client.audio.desktop.AudioDevices} falls back - * to Java Sound. - */ -public final class PipeWire { - - /** A selectable PipeWire device. {@code name} is the node name used to target it. */ - public record Node(String name, String description, boolean sink) { - } - - private PipeWire() { - } - - /** {@code true} when libpipewire loaded and a session is reachable. */ - public static boolean isAvailable() { - return PipeWireSession.get() != null; - } - - /** The version of the loaded libpipewire, or {@code null} when it is not available. */ - public static String version() { - if (!isAvailable()) return null; - try { - return PipeWireLibrary.libraryVersion(); - } catch (Throwable t) { - return null; - } - } - - /** The audio sinks and sources currently in the graph; empty without PipeWire. */ - public static List nodes() { - PipeWireSession session = PipeWireSession.get(); - if (session == null) return List.of(); - return session.nodes().stream() - .map(node -> new Node(node.name(), node.description(), node.sink())) - .toList(); - } - - /** - * Opens a capture stream on {@code targetNode} (empty or {@code null} for the default - * source). - * - * @throws IllegalStateException if PipeWire is unavailable or the stream is refused - */ - public static AudioCapture openCapture(String name, String targetNode, int rate, int channels) { - return new PipeWireCapture(session(), name, targetNode, rate, channels); - } - - /** - * Opens a playback stream on {@code targetNode} (empty or {@code null} for the default - * sink). - * - * @throws IllegalStateException if PipeWire is unavailable or the stream is refused - */ - public static AudioPlayback openPlayback(String name, String targetNode, int rate, int channels) { - return new PipeWirePlayback(session(), name, targetNode, rate, channels); - } - - private static PipeWireSession session() { - PipeWireSession session = PipeWireSession.get(); - if (session == null) throw new IllegalStateException("PipeWire is not available"); - return session; - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWireCapture.java b/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWireCapture.java deleted file mode 100644 index f79352d..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWireCapture.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.ts3client.audio.desktop.pipewire; - -import com.ts3client.audio.AudioCapture; - -import java.lang.foreign.MemorySegment; - -import static com.ts3client.audio.desktop.pipewire.PipeWireLibrary.INT; - -/** A PipeWire capture stream ({@code PW_DIRECTION_INPUT}). */ -final class PipeWireCapture extends PipeWireStream implements AudioCapture { - - PipeWireCapture(PipeWireSession session, String name, String targetNode, int rate, int channels) { - super(session, name, targetNode, rate, channels, true); - } - - /** Copies the valid part of the buffer — which need not start at zero — into the ring. */ - @Override - void process(MemorySegment header, MemorySegment audio, MemorySegment chunk, int maxSize) { - int offset = Math.min(chunk.get(INT, PipeWireLibrary.SPA_CHUNK_OFFSET), maxSize); - int size = Math.min(chunk.get(INT, PipeWireLibrary.SPA_CHUNK_SIZE), maxSize - offset); - if (size > 0) ring.put(audio, offset, size); - } - - @Override - public int read(byte[] buffer, int offset, int length) { - return ring.read(buffer, offset, length); - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWireLibrary.java b/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWireLibrary.java deleted file mode 100644 index 4cad3a3..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWireLibrary.java +++ /dev/null @@ -1,409 +0,0 @@ -package com.ts3client.audio.desktop.pipewire; - -import java.lang.foreign.AddressLayout; -import java.lang.foreign.Arena; -import java.lang.foreign.FunctionDescriptor; -import java.lang.foreign.Linker; -import java.lang.foreign.MemorySegment; -import java.lang.foreign.SymbolLookup; -import java.lang.foreign.ValueLayout; -import java.lang.invoke.MethodHandle; - -/** - * Raw binding to {@code libpipewire-0.3} through the Foreign Function & Memory API. - * - *

    This class is the only place that knows about the C ABI: the exported entry points, - * the SPA/PipeWire constants, and the offsets of the few structures that are read or - * written directly. Everything above it works with Java types. - * - *

    Loading is lazy and failure is expected: on a machine without PipeWire (or without - * a session running) {@link #isAvailable()} returns {@code false} and the caller falls - * back to Java Sound. The class initialiser is what fails, so both the first - * {@link ExceptionInInitializerError} and the later {@link NoClassDefFoundError} are - * caught. - * - *

    Interface methods

    - * The registry API ({@code pw_core_get_registry}, {@code pw_registry_add_listener}, - * {@code pw_core_sync}, ...) is declared {@code static inline} in the headers. PipeWire - * only began exporting compiled copies of those helpers in 1.1; to work on older - * versions too they are instead called the way the inline code does, through the - * object's {@code spa_interface} method table — see {@link #interfaceMethod}. - * - *

    Constants and structure offsets below were taken from the pipewire 1.4 headers and - * are part of the frozen 0.3 ABI. - */ -final class PipeWireLibrary { - - private PipeWireLibrary() { - } - - static final AddressLayout PTR = ValueLayout.ADDRESS; - static final ValueLayout.OfInt INT = ValueLayout.JAVA_INT; - static final ValueLayout.OfLong LONG = ValueLayout.JAVA_LONG; - static final ValueLayout.OfBoolean BOOL = ValueLayout.JAVA_BOOLEAN; - - // ---- enum pw_direction ---- - static final int PW_DIRECTION_INPUT = 0; - static final int PW_DIRECTION_OUTPUT = 1; - - // ---- well-known object ids ---- - static final int PW_ID_CORE = 0; - static final int PW_ID_ANY = 0xFFFFFFFF; - - // ---- interface versions we ask for / implement ---- - static final int PW_VERSION_REGISTRY = 3; - static final int PW_VERSION_CORE_EVENTS = 1; - static final int PW_VERSION_REGISTRY_EVENTS = 0; - static final int PW_VERSION_STREAM_EVENTS = 2; - - // ---- enum pw_stream_flags ---- - static final int PW_STREAM_FLAG_AUTOCONNECT = 1 << 0; - static final int PW_STREAM_FLAG_INACTIVE = 1 << 1; - static final int PW_STREAM_FLAG_MAP_BUFFERS = 1 << 2; - - // ---- enum pw_stream_state ---- - static final int PW_STREAM_STATE_ERROR = -1; - static final int PW_STREAM_STATE_UNCONNECTED = 0; - static final int PW_STREAM_STATE_CONNECTING = 1; - static final int PW_STREAM_STATE_PAUSED = 2; - static final int PW_STREAM_STATE_STREAMING = 3; - - // ---- property keys (pipewire/keys.h) ---- - static final String KEY_APP_NAME = "application.name"; - static final String KEY_MEDIA_TYPE = "media.type"; - static final String KEY_MEDIA_CATEGORY = "media.category"; - static final String KEY_MEDIA_ROLE = "media.role"; - static final String KEY_MEDIA_CLASS = "media.class"; - static final String KEY_NODE_NAME = "node.name"; - static final String KEY_NODE_DESCRIPTION = "node.description"; - static final String KEY_NODE_NICK = "node.nick"; - static final String KEY_NODE_LATENCY = "node.latency"; - static final String KEY_NODE_RATE = "node.rate"; - static final String KEY_TARGET_OBJECT = "target.object"; - - static final String TYPE_INTERFACE_NODE = "PipeWire:Interface:Node"; - - // ---- struct offsets (x86-64/aarch64 LP64; all fields are naturally aligned) ---- - - /** {@code struct spa_interface { const char *type; uint32_t version; struct spa_callbacks cb; }} */ - private static final long SPA_INTERFACE_SIZE = 32; - private static final long SPA_INTERFACE_CB_FUNCS = 16; - private static final long SPA_INTERFACE_CB_DATA = 24; - - /** {@code struct spa_dict { uint32_t flags, n_items; const struct spa_dict_item *items; }} */ - static final long SPA_DICT_SIZE = 16; - static final long SPA_DICT_N_ITEMS = 4; - static final long SPA_DICT_ITEMS = 8; - - /** {@code struct spa_dict_item { const char *key, *value; }} */ - static final long SPA_DICT_ITEM_SIZE = 16; - static final long SPA_DICT_ITEM_VALUE = 8; - - /** {@code struct pw_buffer { struct spa_buffer *buffer; void *user_data; uint64_t size, requested, time; }} */ - static final long PW_BUFFER_BUFFER = 0; - static final long PW_BUFFER_SIZE = 16; - static final long PW_BUFFER_REQUESTED = 24; - static final long PW_BUFFER_SIZEOF = 40; - - /** {@code struct spa_buffer { uint32_t n_metas, n_datas; struct spa_meta *metas; struct spa_data *datas; }} */ - static final long SPA_BUFFER_N_DATAS = 4; - static final long SPA_BUFFER_DATAS = 16; - static final long SPA_BUFFER_SIZEOF = 24; - - /** - * {@code struct spa_data { uint32_t type, flags; int64_t fd; uint32_t mapoffset, maxsize; - * void *data; struct spa_chunk *chunk; }} - */ - static final long SPA_DATA_MAXSIZE = 20; - static final long SPA_DATA_DATA = 24; - static final long SPA_DATA_CHUNK = 32; - static final long SPA_DATA_SIZEOF = 40; - - /** {@code struct spa_chunk { uint32_t offset, size; int32_t stride, flags; }} */ - static final long SPA_CHUNK_OFFSET = 0; - static final long SPA_CHUNK_SIZE = 4; - static final long SPA_CHUNK_STRIDE = 8; - static final long SPA_CHUNK_SIZEOF = 16; - - /** Slot (pointer index) of a method inside {@code struct pw_core_methods}. */ - static final int CORE_METHOD_ADD_LISTENER = 1; - static final int CORE_METHOD_SYNC = 3; - static final int CORE_METHOD_GET_REGISTRY = 6; - - /** Slot of a method inside {@code struct pw_registry_methods}. */ - static final int REGISTRY_METHOD_ADD_LISTENER = 1; - - /** Field offsets in {@code struct pw_core_events} (version at 0, then one pointer each). */ - static final long CORE_EVENTS_SIZEOF = 80; - static final long CORE_EVENTS_DONE = 16; - - /** Field offsets in {@code struct pw_registry_events}. */ - static final long REGISTRY_EVENTS_SIZEOF = 24; - static final long REGISTRY_EVENTS_GLOBAL = 8; - static final long REGISTRY_EVENTS_GLOBAL_REMOVE = 16; - - /** Field offsets in {@code struct pw_stream_events}. */ - static final long STREAM_EVENTS_SIZEOF = 96; - static final long STREAM_EVENTS_STATE_CHANGED = 16; - static final long STREAM_EVENTS_PROCESS = 64; - - /** {@code struct spa_hook}; over-allocated so a future growth cannot corrupt anything. */ - static final long SPA_HOOK_SIZEOF = 128; - - static final Linker LINKER = Linker.nativeLinker(); - - /** SONAMEs to try, newest packaging first. */ - private static final String[] LIBRARY_NAMES = {"libpipewire-0.3.so.0", "libpipewire-0.3.so"}; - - private static final class Handles { - static final SymbolLookup LOOKUP = load(); - - static final MethodHandle PW_INIT = - downcall("pw_init", FunctionDescriptor.ofVoid(PTR, PTR)); - static final MethodHandle PW_GET_LIBRARY_VERSION = - downcall("pw_get_library_version", FunctionDescriptor.of(PTR)); - - static final MethodHandle PW_THREAD_LOOP_NEW = - downcall("pw_thread_loop_new", FunctionDescriptor.of(PTR, PTR, PTR)); - static final MethodHandle PW_THREAD_LOOP_DESTROY = - downcall("pw_thread_loop_destroy", FunctionDescriptor.ofVoid(PTR)); - static final MethodHandle PW_THREAD_LOOP_GET_LOOP = - downcall("pw_thread_loop_get_loop", FunctionDescriptor.of(PTR, PTR)); - static final MethodHandle PW_THREAD_LOOP_START = - downcall("pw_thread_loop_start", FunctionDescriptor.of(INT, PTR)); - static final MethodHandle PW_THREAD_LOOP_STOP = - downcall("pw_thread_loop_stop", FunctionDescriptor.ofVoid(PTR)); - static final MethodHandle PW_THREAD_LOOP_LOCK = - downcall("pw_thread_loop_lock", FunctionDescriptor.ofVoid(PTR)); - static final MethodHandle PW_THREAD_LOOP_UNLOCK = - downcall("pw_thread_loop_unlock", FunctionDescriptor.ofVoid(PTR)); - static final MethodHandle PW_THREAD_LOOP_SIGNAL = - downcall("pw_thread_loop_signal", FunctionDescriptor.ofVoid(PTR, BOOL)); - static final MethodHandle PW_THREAD_LOOP_TIMED_WAIT = - downcall("pw_thread_loop_timed_wait", FunctionDescriptor.of(INT, PTR, INT)); - - static final MethodHandle PW_CONTEXT_NEW = - downcall("pw_context_new", FunctionDescriptor.of(PTR, PTR, PTR, LONG)); - static final MethodHandle PW_CONTEXT_CONNECT = - downcall("pw_context_connect", FunctionDescriptor.of(PTR, PTR, PTR, LONG)); - static final MethodHandle PW_CONTEXT_DESTROY = - downcall("pw_context_destroy", FunctionDescriptor.ofVoid(PTR)); - static final MethodHandle PW_CORE_DISCONNECT = - downcall("pw_core_disconnect", FunctionDescriptor.of(INT, PTR)); - static final MethodHandle PW_PROXY_DESTROY = - downcall("pw_proxy_destroy", FunctionDescriptor.ofVoid(PTR)); - - static final MethodHandle PW_PROPERTIES_NEW_DICT = - downcall("pw_properties_new_dict", FunctionDescriptor.of(PTR, PTR)); - - static final MethodHandle PW_STREAM_NEW_SIMPLE = - downcall("pw_stream_new_simple", FunctionDescriptor.of(PTR, PTR, PTR, PTR, PTR, PTR)); - static final MethodHandle PW_STREAM_CONNECT = - downcall("pw_stream_connect", FunctionDescriptor.of(INT, PTR, INT, INT, INT, PTR, INT)); - static final MethodHandle PW_STREAM_DISCONNECT = - downcall("pw_stream_disconnect", FunctionDescriptor.of(INT, PTR)); - static final MethodHandle PW_STREAM_DESTROY = - downcall("pw_stream_destroy", FunctionDescriptor.ofVoid(PTR)); - static final MethodHandle PW_STREAM_SET_ACTIVE = - downcall("pw_stream_set_active", FunctionDescriptor.of(INT, PTR, BOOL)); - static final MethodHandle PW_STREAM_FLUSH = - downcall("pw_stream_flush", FunctionDescriptor.of(INT, PTR, BOOL)); - static final MethodHandle PW_STREAM_DEQUEUE_BUFFER = - downcall("pw_stream_dequeue_buffer", FunctionDescriptor.of(PTR, PTR)); - static final MethodHandle PW_STREAM_QUEUE_BUFFER = - downcall("pw_stream_queue_buffer", FunctionDescriptor.of(INT, PTR, PTR)); - - private static SymbolLookup load() { - IllegalArgumentException last = null; - for (String name : LIBRARY_NAMES) { - try { - return SymbolLookup.libraryLookup(name, Arena.global()); - } catch (IllegalArgumentException e) { - last = e; - } - } - throw (last != null) ? last : new IllegalArgumentException("libpipewire not found"); - } - - private static MethodHandle downcall(String symbol, FunctionDescriptor descriptor) { - return LINKER.downcallHandle( - LOOKUP.find(symbol).orElseThrow(() -> - new UnsatisfiedLinkError("libpipewire: unresolved symbol " + symbol)), - descriptor); - } - } - - /** {@code true} when libpipewire could be loaded and every symbol we need resolved. */ - static boolean isAvailable() { - try { - return Handles.LOOKUP != null; - } catch (Throwable t) { - return false; - } - } - - // ---- library ---- - - static void init() { - invokeVoid(Handles.PW_INIT, MemorySegment.NULL, MemorySegment.NULL); - } - - static String libraryVersion() { - MemorySegment version = (MemorySegment) invoke(Handles.PW_GET_LIBRARY_VERSION); - return cString(version); - } - - // ---- thread loop ---- - - static MemorySegment threadLoopNew(MemorySegment name) { - return (MemorySegment) invoke(Handles.PW_THREAD_LOOP_NEW, name, MemorySegment.NULL); - } - - static void threadLoopDestroy(MemorySegment loop) { - invokeVoid(Handles.PW_THREAD_LOOP_DESTROY, loop); - } - - static MemorySegment threadLoopGetLoop(MemorySegment loop) { - return (MemorySegment) invoke(Handles.PW_THREAD_LOOP_GET_LOOP, loop); - } - - static int threadLoopStart(MemorySegment loop) { - return (int) invoke(Handles.PW_THREAD_LOOP_START, loop); - } - - static void threadLoopStop(MemorySegment loop) { - invokeVoid(Handles.PW_THREAD_LOOP_STOP, loop); - } - - static void threadLoopLock(MemorySegment loop) { - invokeVoid(Handles.PW_THREAD_LOOP_LOCK, loop); - } - - static void threadLoopUnlock(MemorySegment loop) { - invokeVoid(Handles.PW_THREAD_LOOP_UNLOCK, loop); - } - - static void threadLoopSignal(MemorySegment loop, boolean waitForAccept) { - invokeVoid(Handles.PW_THREAD_LOOP_SIGNAL, loop, waitForAccept); - } - - /** Waits for a {@code signal}, returning {@code -ETIMEDOUT} when {@code seconds} elapse. */ - static int threadLoopTimedWait(MemorySegment loop, int seconds) { - return (int) invoke(Handles.PW_THREAD_LOOP_TIMED_WAIT, loop, seconds); - } - - // ---- context / core ---- - - static MemorySegment contextNew(MemorySegment loop, MemorySegment properties) { - return (MemorySegment) invoke(Handles.PW_CONTEXT_NEW, loop, properties, 0L); - } - - static MemorySegment contextConnect(MemorySegment context, MemorySegment properties) { - return (MemorySegment) invoke(Handles.PW_CONTEXT_CONNECT, context, properties, 0L); - } - - static void contextDestroy(MemorySegment context) { - invokeVoid(Handles.PW_CONTEXT_DESTROY, context); - } - - static int coreDisconnect(MemorySegment core) { - return (int) invoke(Handles.PW_CORE_DISCONNECT, core); - } - - static void proxyDestroy(MemorySegment proxy) { - invokeVoid(Handles.PW_PROXY_DESTROY, proxy); - } - - static MemorySegment propertiesNewDict(MemorySegment dict) { - return (MemorySegment) invoke(Handles.PW_PROPERTIES_NEW_DICT, dict); - } - - // ---- stream ---- - - static MemorySegment streamNewSimple(MemorySegment loop, MemorySegment name, - MemorySegment properties, MemorySegment events, - MemorySegment data) { - return (MemorySegment) invoke(Handles.PW_STREAM_NEW_SIMPLE, loop, name, properties, events, data); - } - - static int streamConnect(MemorySegment stream, int direction, int targetId, int flags, - MemorySegment params, int paramCount) { - return (int) invoke(Handles.PW_STREAM_CONNECT, stream, direction, targetId, flags, params, paramCount); - } - - static int streamDisconnect(MemorySegment stream) { - return (int) invoke(Handles.PW_STREAM_DISCONNECT, stream); - } - - static void streamDestroy(MemorySegment stream) { - invokeVoid(Handles.PW_STREAM_DESTROY, stream); - } - - static int streamSetActive(MemorySegment stream, boolean active) { - return (int) invoke(Handles.PW_STREAM_SET_ACTIVE, stream, active); - } - - static int streamFlush(MemorySegment stream, boolean drain) { - return (int) invoke(Handles.PW_STREAM_FLUSH, stream, drain); - } - - static MemorySegment streamDequeueBuffer(MemorySegment stream) { - return (MemorySegment) invoke(Handles.PW_STREAM_DEQUEUE_BUFFER, stream); - } - - static int streamQueueBuffer(MemorySegment stream, MemorySegment buffer) { - return (int) invoke(Handles.PW_STREAM_QUEUE_BUFFER, stream, buffer); - } - - // ---- spa_interface method dispatch ---- - - /** The {@code cb.data} pointer an interface's methods expect as their first argument. */ - static MemorySegment interfaceSelf(MemorySegment iface) { - return iface.reinterpret(SPA_INTERFACE_SIZE).get(PTR, SPA_INTERFACE_CB_DATA); - } - - /** - * Binds slot {@code slot} of an interface's method table as a downcall. The table is - * a {@code uint32_t version} followed by one function pointer per method, so the slot - * is the pointer index (1 for the first method). - */ - static MethodHandle interfaceMethod(MemorySegment iface, int slot, FunctionDescriptor descriptor) { - MemorySegment methods = iface.reinterpret(SPA_INTERFACE_SIZE).get(PTR, SPA_INTERFACE_CB_FUNCS); - MemorySegment function = methods.reinterpret(8L * (slot + 1)).get(PTR, 8L * slot); - if (function.address() == 0) { - throw new UnsatisfiedLinkError("libpipewire: interface method slot " + slot + " is null"); - } - return LINKER.downcallHandle(function, descriptor); - } - - // ---- helpers ---- - - /** Reads a NUL-terminated C string from an unbounded pointer; {@code null} for NULL. */ - static String cString(MemorySegment pointer) { - if (pointer == null || pointer.address() == 0) return null; - return pointer.reinterpret(Long.MAX_VALUE).getString(0); - } - - /** Gives a pointer returned by C a known extent so its fields can be read. */ - static MemorySegment at(MemorySegment pointer, long size) { - return pointer.reinterpret(size); - } - - static Object invoke(MethodHandle handle, Object... arguments) { - try { - return handle.invokeWithArguments(arguments); - } catch (Throwable t) { - throw wrap(t); - } - } - - static void invokeVoid(MethodHandle handle, Object... arguments) { - invoke(handle, arguments); - } - - private static RuntimeException wrap(Throwable t) { - if (t instanceof RuntimeException re) return re; - if (t instanceof Error e) throw e; - return new IllegalStateException("libpipewire call failed", t); - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWirePlayback.java b/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWirePlayback.java deleted file mode 100644 index 98c858f..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWirePlayback.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.ts3client.audio.desktop.pipewire; - -import com.ts3client.audio.AudioPlayback; - -import java.lang.foreign.MemorySegment; - -import static com.ts3client.audio.desktop.pipewire.PipeWireLibrary.INT; -import static com.ts3client.audio.desktop.pipewire.PipeWireLibrary.LONG; - -/** A PipeWire playback stream ({@code PW_DIRECTION_OUTPUT}). */ -final class PipeWirePlayback extends PipeWireStream implements AudioPlayback { - - PipeWirePlayback(PipeWireSession session, String name, String targetNode, int rate, int channels) { - super(session, name, targetNode, rate, channels, false); - } - - /** - * Fills the buffer with as much queued audio as there is, padding with silence on an - * underrun so the graph always gets a full quantum. - */ - @Override - void process(MemorySegment header, MemorySegment audio, MemorySegment chunk, int maxSize) { - int stride = stride(); - long requested = header.get(LONG, PipeWireLibrary.PW_BUFFER_REQUESTED); - int bytes = maxSize; - if (requested > 0) bytes = (int) Math.min(bytes, requested * stride); - bytes -= bytes % stride; - - int filled = ring.take(audio, 0, bytes); - if (filled < bytes) audio.asSlice(filled, bytes - filled).fill((byte) 0); - - chunk.set(INT, PipeWireLibrary.SPA_CHUNK_OFFSET, 0); - chunk.set(INT, PipeWireLibrary.SPA_CHUNK_STRIDE, stride); - chunk.set(INT, PipeWireLibrary.SPA_CHUNK_SIZE, bytes); - header.set(LONG, PipeWireLibrary.PW_BUFFER_SIZE, bytes / stride); - } - - @Override - public void write(byte[] buffer, int offset, int length) { - if (ring.write(buffer, offset, length) < length && ring.isClosed()) { - throw new IllegalStateException("The PipeWire stream ended"); - } - } - - @Override - public void drain() { - ring.drain(); - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWireSession.java b/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWireSession.java deleted file mode 100644 index 057afaa..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWireSession.java +++ /dev/null @@ -1,287 +0,0 @@ -package com.ts3client.audio.desktop.pipewire; - -import java.lang.foreign.Arena; -import java.lang.foreign.FunctionDescriptor; -import java.lang.foreign.MemorySegment; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.invoke.MethodType; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import static com.ts3client.audio.desktop.pipewire.PipeWireLibrary.INT; -import static com.ts3client.audio.desktop.pipewire.PipeWireLibrary.PTR; - -/** - * The process-wide connection to the PipeWire daemon. - * - *

    Owns the thread loop that every stream runs on, and keeps a live view of the - * graph's audio nodes by listening to the registry — so the device list is always - * current without polling. The session is created on first use and then kept: the - * loop is a native thread that does not hold the JVM open, and re-connecting per - * device query would cost a round trip each time. - * - *

    Every libpipewire call from outside the loop thread must hold the loop lock; the - * {@code lock}/{@code unlock} pairs below are that lock, not a Java monitor. - */ -final class PipeWireSession { - - /** An audio sink (playback device) or source (capture device) in the graph. */ - record Node(String name, String description, boolean sink) { - } - - private static final int ROUNDTRIP_TIMEOUT_SECONDS = 2; - - private static volatile PipeWireSession instance; - private static volatile boolean failed; - - private final Arena arena = Arena.ofShared(); - private final MemorySegment threadLoop; - private final MemorySegment loop; - private final MemorySegment context; - private final MemorySegment core; - private final MemorySegment registry; - - private final MethodHandle coreSync; - - /** Nodes by global id, in the order the registry announced them. Guarded by itself. */ - private final Map nodes = new LinkedHashMap<>(); - - // Written on the caller's thread, read on the loop thread; the native loop mutex - // that orders them is invisible to the Java memory model. - private volatile int pendingSync; - private volatile boolean syncDone; - - /** - * Returns the shared session, or {@code null} when PipeWire is not usable here — - * no library, no daemon, or a connection that was refused. The first failure is - * remembered so an unavailable system is not retried on every device query. - */ - static PipeWireSession get() { - PipeWireSession existing = instance; - if (existing != null || failed) return existing; - synchronized (PipeWireSession.class) { - if (instance == null && !failed) { - try { - instance = new PipeWireSession(); - } catch (Throwable t) { - failed = true; - } - } - return instance; - } - } - - private PipeWireSession() { - if (!PipeWireLibrary.isAvailable()) { - throw new UnsupportedOperationException("libpipewire is not available"); - } - PipeWireLibrary.init(); - - threadLoop = nonNull(PipeWireLibrary.threadLoopNew(arena.allocateFrom("ts3-client")), - "pw_thread_loop_new"); - loop = PipeWireLibrary.threadLoopGetLoop(threadLoop); - context = nonNull(PipeWireLibrary.contextNew(loop, MemorySegment.NULL), "pw_context_new"); - - if (PipeWireLibrary.threadLoopStart(threadLoop) < 0) { - throw new IllegalStateException("pw_thread_loop_start failed"); - } - - PipeWireLibrary.threadLoopLock(threadLoop); - try { - core = nonNull(PipeWireLibrary.contextConnect(context, MemorySegment.NULL), - "pw_context_connect"); - coreSync = PipeWireLibrary.interfaceMethod(core, PipeWireLibrary.CORE_METHOD_SYNC, - FunctionDescriptor.of(INT, PTR, INT, INT)); - addCoreListener(); - registry = nonNull(getRegistry(), "pw_core_get_registry"); - addRegistryListener(); - roundtrip(); - } catch (Throwable t) { - PipeWireLibrary.threadLoopUnlock(threadLoop); - close(); - throw t; - } - PipeWireLibrary.threadLoopUnlock(threadLoop); - } - - // ---- registry / core wiring ---- - - private MemorySegment getRegistry() { - MethodHandle getRegistry = PipeWireLibrary.interfaceMethod(core, - PipeWireLibrary.CORE_METHOD_GET_REGISTRY, - FunctionDescriptor.of(PTR, PTR, INT, PipeWireLibrary.LONG)); - return (MemorySegment) PipeWireLibrary.invoke(getRegistry, - PipeWireLibrary.interfaceSelf(core), PipeWireLibrary.PW_VERSION_REGISTRY, 0L); - } - - private void addCoreListener() { - // Arena allocations are zero-filled, so every callback we do not set stays NULL. - MemorySegment events = arena.allocate(PipeWireLibrary.CORE_EVENTS_SIZEOF, 8); - events.set(INT, 0, PipeWireLibrary.PW_VERSION_CORE_EVENTS); - events.set(PTR, PipeWireLibrary.CORE_EVENTS_DONE, - upcall("onDone", MethodType.methodType(void.class, MemorySegment.class, int.class, int.class), - FunctionDescriptor.ofVoid(PTR, INT, INT))); - - MethodHandle addListener = PipeWireLibrary.interfaceMethod(core, - PipeWireLibrary.CORE_METHOD_ADD_LISTENER, - FunctionDescriptor.of(INT, PTR, PTR, PTR, PTR)); - PipeWireLibrary.invoke(addListener, PipeWireLibrary.interfaceSelf(core), - hook(), events, MemorySegment.NULL); - } - - private void addRegistryListener() { - MemorySegment events = arena.allocate(PipeWireLibrary.REGISTRY_EVENTS_SIZEOF, 8); - events.set(INT, 0, PipeWireLibrary.PW_VERSION_REGISTRY_EVENTS); - events.set(PTR, PipeWireLibrary.REGISTRY_EVENTS_GLOBAL, - upcall("onGlobal", MethodType.methodType(void.class, MemorySegment.class, int.class, - int.class, MemorySegment.class, int.class, MemorySegment.class), - FunctionDescriptor.ofVoid(PTR, INT, INT, PTR, INT, PTR))); - events.set(PTR, PipeWireLibrary.REGISTRY_EVENTS_GLOBAL_REMOVE, - upcall("onGlobalRemove", MethodType.methodType(void.class, MemorySegment.class, int.class), - FunctionDescriptor.ofVoid(PTR, INT))); - - MethodHandle addListener = PipeWireLibrary.interfaceMethod(registry, - PipeWireLibrary.REGISTRY_METHOD_ADD_LISTENER, - FunctionDescriptor.of(INT, PTR, PTR, PTR, PTR)); - PipeWireLibrary.invoke(addListener, PipeWireLibrary.interfaceSelf(registry), - hook(), events, MemorySegment.NULL); - } - - /** A zeroed {@code struct spa_hook} for a listener; it must outlive the object it hooks. */ - private MemorySegment hook() { - return arena.allocate(PipeWireLibrary.SPA_HOOK_SIZEOF, 8); - } - - private MemorySegment upcall(String method, MethodType type, FunctionDescriptor descriptor) { - try { - MethodHandle handle = MethodHandles.lookup() - .bind(this, method, type) - .asType(descriptor.toMethodType()); - return PipeWireLibrary.LINKER.upcallStub(handle, descriptor, arena); - } catch (ReflectiveOperationException e) { - throw new IllegalStateException("cannot bind PipeWire callback " + method, e); - } - } - - // ---- callbacks, all invoked on the loop thread ---- - - @SuppressWarnings("unused") // bound as an upcall - private void onDone(MemorySegment data, int id, int seq) { - if (id != PipeWireLibrary.PW_ID_CORE || seq != pendingSync) return; - syncDone = true; - PipeWireLibrary.threadLoopSignal(threadLoop, false); - } - - @SuppressWarnings("unused") // bound as an upcall - private void onGlobal(MemorySegment data, int id, int permissions, MemorySegment type, - int version, MemorySegment props) { - try { - if (!PipeWireLibrary.TYPE_INTERFACE_NODE.equals(PipeWireLibrary.cString(type))) return; - if (props.address() == 0) return; - - Map properties = readDict(props); - String mediaClass = properties.get(PipeWireLibrary.KEY_MEDIA_CLASS); - boolean sink = "Audio/Sink".equals(mediaClass); - if (!sink && !"Audio/Source".equals(mediaClass)) return; - - String name = properties.get(PipeWireLibrary.KEY_NODE_NAME); - if (name == null || name.isBlank()) return; - - String description = firstNonBlank( - properties.get(PipeWireLibrary.KEY_NODE_DESCRIPTION), - properties.get(PipeWireLibrary.KEY_NODE_NICK), - name); - synchronized (nodes) { - nodes.put(id, new Node(name, description, sink)); - } - } catch (Throwable ignored) { - // An upcall must not throw: a node we cannot read is simply not listed. - } - } - - @SuppressWarnings("unused") // bound as an upcall - private void onGlobalRemove(MemorySegment data, int id) { - synchronized (nodes) { - nodes.remove(id); - } - } - - /** Copies a {@code struct spa_dict} into a Java map. */ - private static Map readDict(MemorySegment dict) { - MemorySegment header = PipeWireLibrary.at(dict, PipeWireLibrary.SPA_DICT_SIZE); - int itemCount = header.get(INT, PipeWireLibrary.SPA_DICT_N_ITEMS); - MemorySegment items = header.get(PTR, PipeWireLibrary.SPA_DICT_ITEMS); - Map properties = new LinkedHashMap<>(); - if (items.address() == 0 || itemCount <= 0) return properties; - - MemorySegment array = PipeWireLibrary.at(items, PipeWireLibrary.SPA_DICT_ITEM_SIZE * itemCount); - for (int i = 0; i < itemCount; i++) { - long offset = PipeWireLibrary.SPA_DICT_ITEM_SIZE * i; - String key = PipeWireLibrary.cString(array.get(PTR, offset)); - String value = PipeWireLibrary.cString( - array.get(PTR, offset + PipeWireLibrary.SPA_DICT_ITEM_VALUE)); - if (key != null) properties.put(key, value); - } - return properties; - } - - private static String firstNonBlank(String... candidates) { - for (String candidate : candidates) { - if (candidate != null && !candidate.isBlank()) return candidate; - } - return null; - } - - // ---- public surface ---- - - /** The audio sinks and sources currently in the graph. */ - List nodes() { - synchronized (nodes) { - return new ArrayList<>(nodes.values()); - } - } - - /** The loop streams are created on; only touch it under {@link #lock()}. */ - MemorySegment loop() { - return loop; - } - - void lock() { - PipeWireLibrary.threadLoopLock(threadLoop); - } - - void unlock() { - PipeWireLibrary.threadLoopUnlock(threadLoop); - } - - /** - * Waits until the server has processed everything sent so far, so that the initial - * burst of registry events has been delivered. Call with the loop lock held. - */ - private void roundtrip() { - pendingSync = (int) PipeWireLibrary.invoke(coreSync, - PipeWireLibrary.interfaceSelf(core), PipeWireLibrary.PW_ID_CORE, pendingSync + 1); - syncDone = false; - while (!syncDone) { - if (PipeWireLibrary.threadLoopTimedWait(threadLoop, ROUNDTRIP_TIMEOUT_SECONDS) != 0) break; - } - } - - private void close() { - if (threadLoop != null) PipeWireLibrary.threadLoopStop(threadLoop); - if (registry != null) PipeWireLibrary.proxyDestroy(registry); - if (core != null) PipeWireLibrary.coreDisconnect(core); - if (context != null) PipeWireLibrary.contextDestroy(context); - if (threadLoop != null) PipeWireLibrary.threadLoopDestroy(threadLoop); - } - - private static MemorySegment nonNull(MemorySegment pointer, String what) { - if (pointer == null || pointer.address() == 0) { - throw new IllegalStateException(what + " failed"); - } - return pointer; - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWireStream.java b/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWireStream.java deleted file mode 100644 index 50f5601..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/PipeWireStream.java +++ /dev/null @@ -1,222 +0,0 @@ -package com.ts3client.audio.desktop.pipewire; - -import java.lang.foreign.Arena; -import java.lang.foreign.FunctionDescriptor; -import java.lang.foreign.MemorySegment; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.invoke.MethodType; -import java.util.LinkedHashMap; -import java.util.Map; - -import static com.ts3client.audio.desktop.pipewire.PipeWireLibrary.INT; -import static com.ts3client.audio.desktop.pipewire.PipeWireLibrary.PTR; - -/** - * One {@code pw_stream} plus the ring buffer that decouples it from the application. - * - *

    PipeWire is pull-based: it calls {@code process} on the loop thread whenever a - * buffer can be filled (playback) or has arrived (capture). The voice pipeline, on the - * other hand, wants to block on a line. {@link PcmRing} bridges the two — see there for - * what happens when the two sides drift apart. - * - *

    {@code PW_STREAM_FLAG_RT_PROCESS} is deliberately not used: it would run the - * callback on a real-time thread, where a garbage collection pause would be an xrun. - * Without it PipeWire schedules the callback on the loop thread instead, which is a - * normal thread and can safely run Java code. - */ -abstract class PipeWireStream { - - /** Ring capacity, as a multiple of the 20 ms frame the pipeline works in. */ - private static final int RING_FRAMES = 20; - - private static final int QUANTUM = 960; // 20 ms at 48 kHz - - private final PipeWireSession session; - private final Arena arena = Arena.ofShared(); - private final int channels; - private final int rate; - private final int stride; - protected final PcmRing ring; - - private volatile MemorySegment stream; - private volatile boolean started; - private volatile boolean closed; - - PipeWireStream(PipeWireSession session, String name, String targetNode, - int rate, int channels, boolean capture) { - this.session = session; - this.rate = rate; - this.channels = channels; - this.stride = channels * 2; // S16, interleaved - this.ring = new PcmRing(QUANTUM * stride * RING_FRAMES); - - session.lock(); - try { - stream = PipeWireLibrary.streamNewSimple(session.loop(), arena.allocateFrom(name), - properties(name, targetNode, capture), events(), MemorySegment.NULL); - if (stream.address() == 0) { - throw new IllegalStateException("pw_stream_new_simple failed"); - } - MemorySegment params = arena.allocate(PTR, 1); - params.set(PTR, 0, SpaPod.audioFormat(arena, rate, channels)); - - int flags = PipeWireLibrary.PW_STREAM_FLAG_AUTOCONNECT - | PipeWireLibrary.PW_STREAM_FLAG_MAP_BUFFERS - | PipeWireLibrary.PW_STREAM_FLAG_INACTIVE; - int result = PipeWireLibrary.streamConnect(stream, - capture ? PipeWireLibrary.PW_DIRECTION_INPUT : PipeWireLibrary.PW_DIRECTION_OUTPUT, - PipeWireLibrary.PW_ID_ANY, flags, params, 1); - if (result < 0) { - throw new IllegalStateException("pw_stream_connect failed: " + result); - } - } catch (Throwable t) { - session.unlock(); - close(); - throw t; - } - session.unlock(); - } - - /** - * Properties the server uses to place and label the stream: the target device, the - * name shown in volume mixers, and the quantum we would like to be called with. - */ - private MemorySegment properties(String name, String targetNode, boolean capture) { - Map properties = new LinkedHashMap<>(); - properties.put(PipeWireLibrary.KEY_MEDIA_TYPE, "Audio"); - properties.put(PipeWireLibrary.KEY_MEDIA_CATEGORY, capture ? "Capture" : "Playback"); - properties.put(PipeWireLibrary.KEY_MEDIA_ROLE, "Communication"); - properties.put(PipeWireLibrary.KEY_APP_NAME, "TS3J"); - properties.put(PipeWireLibrary.KEY_NODE_NAME, name); - properties.put(PipeWireLibrary.KEY_NODE_LATENCY, QUANTUM + "/" + rate); - properties.put(PipeWireLibrary.KEY_NODE_RATE, "1/" + rate); - if (targetNode != null && !targetNode.isEmpty()) { - properties.put(PipeWireLibrary.KEY_TARGET_OBJECT, targetNode); - } - return PipeWireLibrary.propertiesNewDict(dict(properties)); - } - - /** Builds a temporary {@code struct spa_dict}; {@code pw_properties_new_dict} copies it. */ - private MemorySegment dict(Map properties) { - MemorySegment items = arena.allocate( - PipeWireLibrary.SPA_DICT_ITEM_SIZE * properties.size(), 8); - int index = 0; - for (Map.Entry entry : properties.entrySet()) { - long offset = PipeWireLibrary.SPA_DICT_ITEM_SIZE * index++; - items.set(PTR, offset, arena.allocateFrom(entry.getKey())); - items.set(PTR, offset + PipeWireLibrary.SPA_DICT_ITEM_VALUE, - arena.allocateFrom(entry.getValue())); - } - MemorySegment dict = arena.allocate(PipeWireLibrary.SPA_DICT_SIZE, 8); - dict.set(INT, PipeWireLibrary.SPA_DICT_N_ITEMS, properties.size()); - dict.set(PTR, PipeWireLibrary.SPA_DICT_ITEMS, items); - return dict; - } - - private MemorySegment events() { - MemorySegment events = arena.allocate(PipeWireLibrary.STREAM_EVENTS_SIZEOF, 8); - events.set(INT, 0, PipeWireLibrary.PW_VERSION_STREAM_EVENTS); - events.set(PTR, PipeWireLibrary.STREAM_EVENTS_PROCESS, - upcall("onProcess", MethodType.methodType(void.class, MemorySegment.class), - FunctionDescriptor.ofVoid(PTR))); - events.set(PTR, PipeWireLibrary.STREAM_EVENTS_STATE_CHANGED, - upcall("onStateChanged", MethodType.methodType(void.class, MemorySegment.class, - int.class, int.class, MemorySegment.class), - FunctionDescriptor.ofVoid(PTR, INT, INT, PTR))); - return events; - } - - private MemorySegment upcall(String method, MethodType type, FunctionDescriptor descriptor) { - try { - MethodHandle handle = MethodHandles.lookup().bind(this, method, type); - return PipeWireLibrary.LINKER.upcallStub(handle, descriptor, arena); - } catch (ReflectiveOperationException e) { - throw new IllegalStateException("cannot bind PipeWire callback " + method, e); - } - } - - // ---- callbacks, invoked on the loop thread with the loop lock held ---- - - @SuppressWarnings("unused") // bound as an upcall - private void onStateChanged(MemorySegment data, int previous, int current, MemorySegment message) { - // A stream that errored will never be scheduled again, so unblock the pipeline - // instead of letting it wait for audio that cannot arrive. - if (current == PipeWireLibrary.PW_STREAM_STATE_ERROR) ring.close(); - } - - @SuppressWarnings("unused") // bound as an upcall - private void onProcess(MemorySegment data) { - try { - MemorySegment pwBuffer = PipeWireLibrary.streamDequeueBuffer(stream); - if (pwBuffer.address() == 0) return; // out of buffers; skip a cycle - try { - MemorySegment header = PipeWireLibrary.at(pwBuffer, PipeWireLibrary.PW_BUFFER_SIZEOF); - MemorySegment spaBuffer = PipeWireLibrary.at( - header.get(PTR, PipeWireLibrary.PW_BUFFER_BUFFER), PipeWireLibrary.SPA_BUFFER_SIZEOF); - if (spaBuffer.get(INT, PipeWireLibrary.SPA_BUFFER_N_DATAS) < 1) return; - - MemorySegment datum = PipeWireLibrary.at( - spaBuffer.get(PTR, PipeWireLibrary.SPA_BUFFER_DATAS), PipeWireLibrary.SPA_DATA_SIZEOF); - MemorySegment audio = datum.get(PTR, PipeWireLibrary.SPA_DATA_DATA); - if (audio.address() == 0) return; // not mapped (e.g. a DmaBuf) - - int maxSize = datum.get(INT, PipeWireLibrary.SPA_DATA_MAXSIZE); - MemorySegment chunk = PipeWireLibrary.at( - datum.get(PTR, PipeWireLibrary.SPA_DATA_CHUNK), PipeWireLibrary.SPA_CHUNK_SIZEOF); - process(header, PipeWireLibrary.at(audio, maxSize), chunk, maxSize); - } finally { - PipeWireLibrary.streamQueueBuffer(stream, pwBuffer); - } - } catch (Throwable ignored) { - // An upcall must not throw: drop the cycle rather than take the JVM down. - } - } - - /** - * Moves one buffer between {@code audio} and the ring. - * - * @param header the {@code struct pw_buffer}, for {@code requested} and {@code size} - * @param audio the mapped payload, {@code maxSize} bytes long - * @param chunk the {@code struct spa_chunk} describing the valid part of {@code audio} - */ - abstract void process(MemorySegment header, MemorySegment audio, MemorySegment chunk, int maxSize); - - // ---- lifecycle ---- - - public int channels() { - return channels; - } - - final int stride() { - return stride; - } - - public synchronized void start() { - if (started || closed) return; - started = true; - session.lock(); - try { - PipeWireLibrary.streamSetActive(stream, true); - } finally { - session.unlock(); - } - } - - public synchronized void close() { - if (closed) return; - closed = true; - ring.close(); - if (stream != null && stream.address() != 0) { - session.lock(); - try { - PipeWireLibrary.streamDestroy(stream); // disconnects and drops the listeners - } finally { - session.unlock(); - } - stream = null; - } - // Only safe once the loop can no longer reach the upcall stubs, i.e. after destroy. - arena.close(); - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/SpaPod.java b/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/SpaPod.java deleted file mode 100644 index f6e870e..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/audio/desktop/pipewire/SpaPod.java +++ /dev/null @@ -1,161 +0,0 @@ -package com.ts3client.audio.desktop.pipewire; - -import java.lang.foreign.MemorySegment; -import java.lang.foreign.SegmentAllocator; -import java.lang.foreign.ValueLayout; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; - -/** - * Builder for the SPA "plain old data" objects PipeWire uses to describe formats. - * - *

    A POD is a length-prefixed tree: every value is an 8-byte header - * ({@code uint32_t size; uint32_t type;}) followed by {@code size} bytes of body, padded - * out to a multiple of 8. An object adds {@code uint32_t type; uint32_t id;} in front of - * its properties, and each property is {@code uint32_t key; uint32_t flags;} followed by - * one value POD. - * - *

    libpipewire only offers {@code spa_pod_builder} as inline C, so the bytes are - * assembled here instead. {@code SpaPodTest} pins the output against the bytes the real - * {@code spa_format_audio_raw_build()} produces. - */ -final class SpaPod { - - // ---- enum spa_type ---- - private static final int SPA_TYPE_ID = 3; - private static final int SPA_TYPE_INT = 4; - private static final int SPA_TYPE_ARRAY = 13; - private static final int SPA_TYPE_OBJECT = 15; - private static final int SPA_TYPE_OBJECT_FORMAT = 0x0004_0003; - - // ---- enum spa_param_type ---- - static final int SPA_PARAM_ENUM_FORMAT = 3; - - // ---- enum spa_format (object property keys) ---- - private static final int SPA_FORMAT_MEDIA_TYPE = 1; - private static final int SPA_FORMAT_MEDIA_SUBTYPE = 2; - private static final int SPA_FORMAT_AUDIO_FORMAT = 0x0001_0001; - private static final int SPA_FORMAT_AUDIO_RATE = 0x0001_0003; - private static final int SPA_FORMAT_AUDIO_CHANNELS = 0x0001_0004; - private static final int SPA_FORMAT_AUDIO_POSITION = 0x0001_0005; - - private static final int SPA_MEDIA_TYPE_AUDIO = 1; - private static final int SPA_MEDIA_SUBTYPE_RAW = 1; - - /** {@code SPA_AUDIO_FORMAT_S16_LE} — interleaved signed 16-bit, what our pipeline uses. */ - static final int SPA_AUDIO_FORMAT_S16_LE = 0x103; - - // ---- enum spa_audio_channel ---- - private static final int SPA_AUDIO_CHANNEL_UNKNOWN = 0; - private static final int SPA_AUDIO_CHANNEL_MONO = 2; - private static final int SPA_AUDIO_CHANNEL_FL = 3; - private static final int SPA_AUDIO_CHANNEL_FR = 4; - - private final ByteBuffer buffer; - - private SpaPod(int capacity) { - this.buffer = ByteBuffer.allocate(capacity).order(ByteOrder.LITTLE_ENDIAN); - } - - /** - * Builds the single {@code EnumFormat} parameter a stream offers when connecting: - * interleaved S16 audio at one fixed rate and channel count. Offering exactly one - * format lets the server put its own converter in front of us, so the negotiated - * format is always the one asked for here. - */ - static MemorySegment audioFormat(SegmentAllocator allocator, int rate, int channels) { - SpaPod pod = new SpaPod(256); - pod.beginObject(SPA_TYPE_OBJECT_FORMAT, SPA_PARAM_ENUM_FORMAT); - pod.id(SPA_FORMAT_MEDIA_TYPE, SPA_MEDIA_TYPE_AUDIO); - pod.id(SPA_FORMAT_MEDIA_SUBTYPE, SPA_MEDIA_SUBTYPE_RAW); - pod.id(SPA_FORMAT_AUDIO_FORMAT, SPA_AUDIO_FORMAT_S16_LE); - pod.integer(SPA_FORMAT_AUDIO_RATE, rate); - pod.integer(SPA_FORMAT_AUDIO_CHANNELS, channels); - pod.idArray(SPA_FORMAT_AUDIO_POSITION, positions(channels)); - pod.endObject(); - return pod.toSegment(allocator); - } - - /** Channel map for the layouts we use; anything wider is left for the server to assign. */ - private static int[] positions(int channels) { - return switch (channels) { - case 1 -> new int[]{SPA_AUDIO_CHANNEL_MONO}; - case 2 -> new int[]{SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR}; - default -> { - int[] unknown = new int[channels]; - java.util.Arrays.fill(unknown, SPA_AUDIO_CHANNEL_UNKNOWN); - yield unknown; - } - }; - } - - // ---- writing ---- - - /** Offset of the size field of the object being built, patched by {@link #endObject}. */ - private int objectSizeOffset = -1; - - private void beginObject(int type, int id) { - objectSizeOffset = buffer.position(); - buffer.putInt(0); // size, patched in endObject - buffer.putInt(SPA_TYPE_OBJECT); - buffer.putInt(type); - buffer.putInt(id); - } - - private void endObject() { - int bodyStart = objectSizeOffset + 8; - buffer.putInt(objectSizeOffset, buffer.position() - bodyStart); - } - - private void id(int key, int value) { - property(key, SPA_TYPE_ID, 4); - buffer.putInt(value); - pad(); - } - - private void integer(int key, int value) { - property(key, SPA_TYPE_INT, 4); - buffer.putInt(value); - pad(); - } - - /** An array POD: a child header describing one element, then the elements. */ - private void idArray(int key, int[] values) { - property(key, SPA_TYPE_ARRAY, 8 + 4 * values.length); - buffer.putInt(4); - buffer.putInt(SPA_TYPE_ID); - for (int value : values) { - buffer.putInt(value); - } - pad(); - } - - /** Writes {@code key/flags} plus the value header; the caller writes the body. */ - private void property(int key, int type, int size) { - buffer.putInt(key); - buffer.putInt(0); // flags - buffer.putInt(size); - buffer.putInt(type); - } - - /** Bodies are padded to 8 bytes; the padding is not counted in the declared size. */ - private void pad() { - while ((buffer.position() & 7) != 0) { - buffer.put((byte) 0); - } - } - - private MemorySegment toSegment(SegmentAllocator allocator) { - MemorySegment segment = allocator.allocate(buffer.position(), 8); - MemorySegment.copy(MemorySegment.ofBuffer(buffer.flip()), 0, segment, 0, segment.byteSize()); - return segment; - } - - /** The bytes this builder produced, for tests. */ - static byte[] audioFormatBytes(int rate, int channels) { - try (java.lang.foreign.Arena arena = java.lang.foreign.Arena.ofConfined()) { - MemorySegment pod = audioFormat(arena, rate, channels); - return pod.toArray(ValueLayout.JAVA_BYTE); - } - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/DesktopInputHooks.java b/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/DesktopInputHooks.java deleted file mode 100644 index 9a42a88..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/DesktopInputHooks.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.ts3client.hotkey.desktop; - -import com.ts3client.hotkey.GlobalInputHook; -import com.ts3client.hotkey.HotkeyKey; - -import java.util.ArrayList; -import java.util.List; - -/** - * Picks the global input hook that suits the running session and starts it. - * - *

    Windows has one answer, raw input. On X11 it is XInput2, with RECORD behind it for - * servers that lack it: neither needs privileges or devices to open. On Wayland the X - * server sees only what the compositor forwards, so reading evdev is the surest way to - * catch every key — and when that is not permitted either, the returned hook is simply - * not running and says why. - */ -public final class DesktopInputHooks { - - private DesktopInputHooks() { - } - - /** @return a hook, started when it could be; check {@link GlobalInputHook#isRunning()} */ - public static GlobalInputHook start(GlobalInputHook.Listener listener) { - List reasons = new ArrayList<>(); - for (GlobalInputHook hook : candidates()) { - hook.start(listener); - if (hook.isRunning()) return hook; - reasons.add(hook.getClass().getSimpleName() + ": " + hook.unavailableReason()); - hook.close(); - } - return new Unavailable(reasons.isEmpty() - ? "no global input backend for this session" - : String.join("; ", reasons)); - } - - private static List candidates() { - List hooks = new ArrayList<>(); - if (Win32.isWindows()) { - if (WindowsInputHook.isSupported()) hooks.add(new WindowsInputHook()); - return hooks; - } - if (isWayland()) { - // Evdev first: it is the only backend guaranteed to see keys aimed at native - // Wayland windows. Failing that, Xwayland still covers every X11 app, and on - // compositors that forward the rest — KWin, with legacy X11 app support on — - // it covers those too. - if (EvdevInputHook.isSupported()) hooks.add(new EvdevInputHook()); - addX11Hooks(hooks); - } else { - addX11Hooks(hooks); - if (EvdevInputHook.isSupported()) hooks.add(new EvdevInputHook()); - } - return hooks; - } - - /** - * RECORD before XInput2: on at least some driver stacks, XInput2's raw - * {@code XI_RawButtonRelease} never reaches a client that hasn't grabbed the pointer — - * see {@link XInput2InputHook} — which makes a bound mouse button look stuck down. - * RECORD taps the same core events {@code xev} sees and is not affected. XInput2 stays - * as the fallback for servers where RECORD is disabled or missing. - */ - private static void addX11Hooks(List hooks) { - if (XRecordInputHook.isSupported()) hooks.add(new XRecordInputHook()); - if (XInput2InputHook.isSupported()) hooks.add(new XInput2InputHook()); - } - - private static boolean isWayland() { - return System.getenv("WAYLAND_DISPLAY") != null - || "wayland".equalsIgnoreCase(System.getenv("XDG_SESSION_TYPE")); - } - - /** Stands in when no backend could start, so callers need no null checks. */ - private record Unavailable(String reason) implements GlobalInputHook { - - @Override - public void start(Listener listener) { - } - - @Override - public boolean isRunning() { - return false; - } - - @Override - public String unavailableReason() { - return reason; - } - - @Override - public String keyName(HotkeyKey key) { - // Bindings recorded earlier still deserve their real names in the dialog, - // even with no hook running to have produced them. - return Win32.isWindows() ? WindowsKeyNamer.name(key) : X11KeyNamer.name(key); - } - - @Override - public void close() { - } - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/EvdevInputHook.java b/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/EvdevInputHook.java deleted file mode 100644 index b3f4e8a..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/EvdevInputHook.java +++ /dev/null @@ -1,151 +0,0 @@ -package com.ts3client.hotkey.desktop; - -import com.ts3client.hotkey.GlobalInputHook; -import com.ts3client.hotkey.HotkeyKey; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.ArrayList; -import java.util.List; - -/** - * System-wide input hook that reads the kernel's evdev devices directly, for sessions - * where {@link XRecordInputHook} cannot see everything — Wayland above all, where the X - * server is only told about events aimed at X clients. - * - *

    It needs read access to {@code /dev/input/event*}, which normally means membership - * of the {@code input} group; without it the hook reports itself unavailable and the - * client carries on without global hotkeys. - * - *

    Key codes are reported as X keycodes (the kernel code plus 8) and buttons as X - * button numbers, so bindings mean the same thing whichever backend recorded them. - */ -public final class EvdevInputHook implements GlobalInputHook { - - private static final File INPUT_DIR = new File("/dev/input"); - /** {@code struct input_event} on 64-bit Linux: two 8-byte time fields, then type/code/value. */ - private static final int EVENT_SIZE = 24; - private static final int EV_KEY = 1; - /** Kernel key codes below this are keyboard keys; from here up they are BTN_* buttons. */ - private static final int BTN_MISC = 0x100; - private static final int BTN_LEFT = 0x110; - - private final List streams = new ArrayList<>(); - private final List threads = new ArrayList<>(); - private volatile Listener listener; - private volatile boolean running; - private volatile String unavailable = "not started"; - - public static boolean isSupported() { - File[] devices = INPUT_DIR.listFiles((dir, name) -> name.startsWith("event")); - if (devices == null) return false; - for (File device : devices) { - if (device.canRead()) return true; - } - return false; - } - - @Override - public void start(Listener listener) { - this.listener = listener; - File[] devices = INPUT_DIR.listFiles((dir, name) -> name.startsWith("event")); - if (devices == null || devices.length == 0) { - unavailable = "no /dev/input devices"; - return; - } - for (File device : devices) { - try { - InputStream in = new FileInputStream(device); - streams.add(in); - Thread t = new Thread(() -> read(in), "ts3j-hotkeys-evdev-" + device.getName()); - t.setDaemon(true); - threads.add(t); - } catch (Exception ignored) { - // Devices we may not read are simply skipped. - } - } - if (streams.isEmpty()) { - unavailable = "no readable /dev/input device — add your user to the \"input\" group"; - return; - } - running = true; - unavailable = ""; - for (Thread t : threads) t.start(); - } - - private void read(InputStream in) { - byte[] buffer = new byte[EVENT_SIZE * 16]; - ByteBuffer view = ByteBuffer.wrap(buffer).order(ByteOrder.nativeOrder()); - while (running) { - try { - int read = in.read(buffer); - if (read < 0) return; - for (int offset = 0; offset + EVENT_SIZE <= read; offset += EVENT_SIZE) { - int type = view.getShort(offset + 16) & 0xffff; - int code = view.getShort(offset + 18) & 0xffff; - int value = view.getInt(offset + 20); - // 2 is auto-repeat, which must not look like a fresh press. - if (type == EV_KEY && value != 2) dispatch(code, value == 1); - } - } catch (Exception e) { - return; - } - } - } - - private void dispatch(int code, boolean pressed) { - Listener l = listener; - if (l == null) return; - HotkeyKey key = code < BTN_MISC ? HotkeyKey.keyboard(code + 8) : mouse(code); - if (key != null) l.onInput(key, pressed); - } - - /** Maps the kernel's BTN_* codes onto the X button numbering. */ - private static HotkeyKey mouse(int code) { - return switch (code) { - case BTN_LEFT -> HotkeyKey.mouse(1); - case BTN_LEFT + 1 -> HotkeyKey.mouse(3); // BTN_RIGHT - case BTN_LEFT + 2 -> HotkeyKey.mouse(2); // BTN_MIDDLE - case BTN_LEFT + 3 -> HotkeyKey.mouse(8); // BTN_SIDE, "mouse 4" - case BTN_LEFT + 4 -> HotkeyKey.mouse(9); // BTN_EXTRA, "mouse 5" - case BTN_LEFT + 5 -> HotkeyKey.mouse(10); // BTN_FORWARD - case BTN_LEFT + 6 -> HotkeyKey.mouse(11); // BTN_BACK - case BTN_LEFT + 7 -> HotkeyKey.mouse(12); // BTN_TASK - default -> null; // joysticks, lid switches, … - }; - } - - @Override - public boolean isRunning() { - return running; - } - - @Override - public String unavailableReason() { - return running ? "" : unavailable; - } - - @Override - public String keyName(HotkeyKey key) { - // The kernel knows scancodes, not layouts; let X name the key when it can. - return X11KeyNamer.name(key); - } - - @Override - public void close() { - running = false; - listener = null; - // Closing the descriptor is what breaks the readers out of their blocking read. - for (InputStream in : streams) { - try { - in.close(); - } catch (Exception ignored) { - } - } - streams.clear(); - threads.clear(); - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/KeyNames.java b/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/KeyNames.java deleted file mode 100644 index 77b2921..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/KeyNames.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.ts3client.hotkey.desktop; - -import java.util.Map; - -/** Turns X keysym names into the labels users expect on a hotkey button. */ -final class KeyNames { - - private KeyNames() { - } - - private static final Map SPECIAL = Map.ofEntries( - Map.entry("Control_L", "Left Ctrl"), - Map.entry("Control_R", "Right Ctrl"), - Map.entry("Shift_L", "Left Shift"), - Map.entry("Shift_R", "Right Shift"), - Map.entry("Alt_L", "Left Alt"), - Map.entry("Alt_R", "Right Alt"), - Map.entry("ISO_Level3_Shift", "AltGr"), - Map.entry("Super_L", "Left Super"), - Map.entry("Super_R", "Right Super"), - Map.entry("Meta_L", "Left Meta"), - Map.entry("Meta_R", "Right Meta"), - Map.entry("Prior", "Page Up"), - Map.entry("Next", "Page Down"), - Map.entry("Return", "Enter"), - Map.entry("space", "Space"), - Map.entry("BackSpace", "Backspace"), - Map.entry("Escape", "Esc"), - Map.entry("Caps_Lock", "Caps Lock"), - Map.entry("Num_Lock", "Num Lock"), - Map.entry("Scroll_Lock", "Scroll Lock"), - Map.entry("Menu", "Menu"), - Map.entry("Print", "Print Screen")); - - /** - * @param keysym the X name of the keysym, e.g. {@code a}, {@code Control_L}, {@code KP_Add} - * @return a display name, or {@code null} when there is nothing sensible to show - */ - static String pretty(String keysym) { - if (keysym == null || keysym.isBlank()) return null; - String special = SPECIAL.get(keysym); - if (special != null) return special; - if (keysym.startsWith("KP_")) return "Numpad " + pretty(keysym.substring(3)); - if (keysym.length() == 1) return keysym.toUpperCase(); - return keysym.replace('_', ' '); - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/RawInput.java b/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/RawInput.java deleted file mode 100644 index 69ca9a8..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/RawInput.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.ts3client.hotkey.desktop; - -import com.ts3client.hotkey.HotkeyKey; - -import java.util.ArrayList; -import java.util.List; - -/** - * Layout of a {@code RAWINPUT} structure and the reading of the two kinds we ask for, - * split out from {@link WindowsInputHook} so the decoding can be tested anywhere. - * - *

    Keyboards report a set-1 scan code, which is what a binding stores: it names the - * physical key, so it survives a layout change exactly as an X keycode does on Linux. - * Mice are renumbered to the X button numbering the rest of the client already speaks, - * so {@link HotkeyKey#fallbackName()} and the saved bindings mean the same thing on - * both platforms. - */ -final class RawInput { - - private RawInput() { - } - - /** {@code RAWINPUTHEADER.dwType}. */ - static final int TYPE_MOUSE = 0; - static final int TYPE_KEYBOARD = 1; - - /** Field offsets in {@code RAWINPUT} under x64, past the 24-byte header. */ - static final long HEADER_TYPE = 0; - static final long HEADER_SIZE = 24; - static final long KEYBOARD_MAKE_CODE = 24; - static final long KEYBOARD_FLAGS = 26; - static final long KEYBOARD_VKEY = 30; - static final long MOUSE_BUTTON_FLAGS = 28; - - /** Both event kinds fit comfortably; the larger, {@code RAWMOUSE}, needs 48 bytes. */ - static final long BUFFER_SIZE = 64; - - /** {@code RAWKEYBOARD.Flags}. */ - static final int RI_KEY_BREAK = 0x01; - static final int RI_KEY_E0 = 0x02; - static final int RI_KEY_E1 = 0x04; - - /** {@code VK_NO_VKEY}: the filler half of an escaped sequence, carrying no key. */ - private static final int VKEY_NONE = 0xFF; - - /** {@code RAWMOUSE.usButtonFlags}, in down/up pairs. */ - private static final int[] BUTTON_FLAGS = { - 0x0001, 0x0002, 1, // left - 0x0010, 0x0020, 2, // middle - 0x0004, 0x0008, 3, // right - 0x0040, 0x0080, 8, // X1, "Mouse 4" - 0x0100, 0x0200, 9, // X2, "Mouse 5" - }; - - private static final int RI_MOUSE_WHEEL = 0x0400; - private static final int RI_MOUSE_HWHEEL = 0x0800; - - /** - * The scan code identifying a key, with the escape prefix folded into the high byte - * so that e.g. right Ctrl ({@code E0 1D}) stays distinct from left ({@code 1D}). - * - * @return the code, or -1 when the event names no key of its own - */ - static int scanCode(int makeCode, int flags, int vkey) { - if (vkey == VKEY_NONE) return -1; - int code = makeCode & 0xFF; - if (code == 0) return -1; - if ((flags & RI_KEY_E0) != 0) code |= 0xE000; - else if ((flags & RI_KEY_E1) != 0) code |= 0xE100; - return code; - } - - static boolean isRelease(int flags) { - return (flags & RI_KEY_BREAK) != 0; - } - - /** One button transition, in the order the flags word packs them. */ - record ButtonEvent(HotkeyKey key, boolean pressed) { - } - - /** - * Unpacks a mouse event, which may carry several transitions at once. - * - * @param buttonFlags {@code usButtonFlags} - * @param wheelDelta {@code usButtonData}, read as a signed delta when a wheel bit is set - */ - static List buttons(int buttonFlags, short wheelDelta) { - List events = new ArrayList<>(); - for (int i = 0; i < BUTTON_FLAGS.length; i += 3) { - HotkeyKey key = HotkeyKey.mouse(BUTTON_FLAGS[i + 2]); - if ((buttonFlags & BUTTON_FLAGS[i]) != 0) events.add(new ButtonEvent(key, true)); - if ((buttonFlags & BUTTON_FLAGS[i + 1]) != 0) events.add(new ButtonEvent(key, false)); - } - // A wheel notch has no release of its own; X reports it as a button tap, and the - // hotkey engine expects the same shape, so synthesise both edges. - if ((buttonFlags & RI_MOUSE_WHEEL) != 0 && wheelDelta != 0) { - tap(events, wheelDelta > 0 ? 4 : 5); - } - if ((buttonFlags & RI_MOUSE_HWHEEL) != 0 && wheelDelta != 0) { - tap(events, wheelDelta > 0 ? 7 : 6); - } - return events; - } - - private static void tap(List events, int button) { - events.add(new ButtonEvent(HotkeyKey.mouse(button), true)); - events.add(new ButtonEvent(HotkeyKey.mouse(button), false)); - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/Win32.java b/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/Win32.java deleted file mode 100644 index 03d2c87..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/Win32.java +++ /dev/null @@ -1,210 +0,0 @@ -package com.ts3client.hotkey.desktop; - -import java.lang.foreign.Arena; -import java.lang.foreign.FunctionDescriptor; -import java.lang.foreign.Linker; -import java.lang.foreign.MemorySegment; -import java.lang.foreign.SymbolLookup; -import java.lang.foreign.ValueLayout; -import java.lang.invoke.MethodHandle; -import java.nio.charset.StandardCharsets; - -/** - * Raw binding to {@code user32} and {@code kernel32}, with just the calls - * {@link WindowsInputHook} needs to own a message-only window and read raw input from it. - * - *

    Raw input is the polite way to watch the whole machine on Windows: registering with - * {@code RIDEV_INPUTSINK} delivers every key and button even while another application is - * in the foreground, and — unlike a {@code WH_KEYBOARD_LL} hook — it observes rather than - * intercepts, so nothing can be swallowed and nothing serialises the system input queue. - * - *

    Loading is lazy and failure is expected off Windows, where {@link #isAvailable()} - * returns {@code false} and the caller falls back to another backend. - */ -final class Win32 { - - private Win32() { - } - - private static final ValueLayout.OfInt INT = ValueLayout.JAVA_INT; - private static final ValueLayout.OfLong LONG = ValueLayout.JAVA_LONG; - private static final java.lang.foreign.AddressLayout PTR = ValueLayout.ADDRESS; - - /** Window messages we care about. */ - static final int WM_DESTROY = 0x0002; - static final int WM_CLOSE = 0x0010; - static final int WM_INPUT = 0x00FF; - - /** {@code HWND_MESSAGE}: parent for a window that only ever receives messages. */ - static final long HWND_MESSAGE = -3L; - - /** {@code RIDEV_INPUTSINK}: deliver input even when the window is not in front. */ - static final int RIDEV_INPUTSINK = 0x00000100; - - /** HID usages for the two devices we register (usage page 1, "generic desktop"). */ - static final int USAGE_PAGE_GENERIC = 0x01; - static final int USAGE_MOUSE = 0x02; - static final int USAGE_KEYBOARD = 0x06; - - /** {@code RID_INPUT}: ask {@code GetRawInputData} for the payload, not the header. */ - static final int RID_INPUT = 0x10000003; - - /** {@code WNDCLASSEXW} size and the field offsets we fill, under x64. */ - static final long WNDCLASS_SIZE = 80; - static final long WNDCLASS_CBSIZE = 0; - static final long WNDCLASS_WNDPROC = 8; - static final long WNDCLASS_HINSTANCE = 24; - static final long WNDCLASS_CLASSNAME = 64; - - /** {@code RAWINPUTDEVICE}: usage page, usage, flags, target window. */ - static final long RAWINPUTDEVICE_SIZE = 16; - static final long RAWINPUTDEVICE_USAGE_PAGE = 0; - static final long RAWINPUTDEVICE_USAGE = 2; - static final long RAWINPUTDEVICE_FLAGS = 4; - static final long RAWINPUTDEVICE_TARGET = 8; - - /** {@code MSG} is 48 bytes under x64. */ - static final long MSG_SIZE = 48; - - /** The C signature of a {@code WNDPROC}. */ - static final FunctionDescriptor WND_PROC = - FunctionDescriptor.of(LONG, PTR, INT, LONG, LONG); - - private static final Linker LINKER = Linker.nativeLinker(); - - private static final class Libs { - static final SymbolLookup USER32 = SymbolLookup.libraryLookup("user32.dll", Arena.global()); - static final SymbolLookup KERNEL32 = SymbolLookup.libraryLookup("kernel32.dll", Arena.global()); - - static final MethodHandle GET_MODULE_HANDLE = - downcall(KERNEL32, "GetModuleHandleW", FunctionDescriptor.of(PTR, PTR)); - static final MethodHandle REGISTER_CLASS = - downcall(USER32, "RegisterClassExW", FunctionDescriptor.of(INT, PTR)); - static final MethodHandle UNREGISTER_CLASS = - downcall(USER32, "UnregisterClassW", FunctionDescriptor.of(INT, PTR, PTR)); - static final MethodHandle CREATE_WINDOW = - downcall(USER32, "CreateWindowExW", FunctionDescriptor.of(PTR, - INT, PTR, PTR, INT, INT, INT, INT, INT, PTR, PTR, PTR, PTR)); - static final MethodHandle DESTROY_WINDOW = - downcall(USER32, "DestroyWindow", FunctionDescriptor.of(INT, PTR)); - static final MethodHandle DEF_WINDOW_PROC = - downcall(USER32, "DefWindowProcW", FunctionDescriptor.of(LONG, PTR, INT, LONG, LONG)); - static final MethodHandle GET_MESSAGE = - downcall(USER32, "GetMessageW", FunctionDescriptor.of(INT, PTR, PTR, INT, INT)); - static final MethodHandle DISPATCH_MESSAGE = - downcall(USER32, "DispatchMessageW", FunctionDescriptor.of(LONG, PTR)); - static final MethodHandle POST_MESSAGE = - downcall(USER32, "PostMessageW", FunctionDescriptor.of(INT, PTR, INT, LONG, LONG)); - static final MethodHandle POST_QUIT_MESSAGE = - downcall(USER32, "PostQuitMessage", FunctionDescriptor.ofVoid(INT)); - static final MethodHandle REGISTER_RAW_INPUT = - downcall(USER32, "RegisterRawInputDevices", FunctionDescriptor.of(INT, PTR, INT, INT)); - static final MethodHandle GET_RAW_INPUT_DATA = - downcall(USER32, "GetRawInputData", - FunctionDescriptor.of(INT, PTR, INT, PTR, PTR, INT)); - static final MethodHandle GET_KEY_NAME_TEXT = - downcall(USER32, "GetKeyNameTextW", FunctionDescriptor.of(INT, INT, PTR, INT)); - } - - private static MethodHandle downcall(SymbolLookup lookup, String symbol, - FunctionDescriptor descriptor) { - return LINKER.downcallHandle( - lookup.find(symbol).orElseThrow(() -> - new UnsatisfiedLinkError("unresolved symbol " + symbol)), - descriptor); - } - - static boolean isWindows() { - return System.getProperty("os.name", "").toLowerCase().startsWith("windows"); - } - - static boolean isAvailable() { - if (!isWindows()) return false; - try { - return Libs.USER32 != null && Libs.KERNEL32 != null; - } catch (Throwable t) { - return false; - } - } - - /** Allocates a null-terminated UTF-16 string, as every {@code ...W} entry point wants. */ - static MemorySegment wide(Arena arena, String text) { - return arena.allocateFrom(text, StandardCharsets.UTF_16LE); - } - - static MemorySegment moduleHandle() { - return (MemorySegment) call(Libs.GET_MODULE_HANDLE, MemorySegment.NULL); - } - - /** @return the class atom, or 0 when registration failed */ - static int registerClass(MemorySegment wndClass) { - return (int) call(Libs.REGISTER_CLASS, wndClass); - } - - static void unregisterClass(MemorySegment className, MemorySegment instance) { - call(Libs.UNREGISTER_CLASS, className, instance); - } - - /** Creates a message-only window: no pixels, but it has a queue and can be a target. */ - static MemorySegment createMessageWindow(MemorySegment className, MemorySegment instance) { - return (MemorySegment) call(Libs.CREATE_WINDOW, 0, className, MemorySegment.NULL, 0, - 0, 0, 0, 0, MemorySegment.ofAddress(HWND_MESSAGE), - MemorySegment.NULL, instance, MemorySegment.NULL); - } - - static void destroyWindow(MemorySegment window) { - call(Libs.DESTROY_WINDOW, window); - } - - static long defWindowProc(MemorySegment window, int message, long wParam, long lParam) { - return (long) call(Libs.DEF_WINDOW_PROC, window, message, wParam, lParam); - } - - /** @return 1 for a message, 0 for {@code WM_QUIT}, -1 on error */ - static int getMessage(MemorySegment message) { - return (int) call(Libs.GET_MESSAGE, message, MemorySegment.NULL, 0, 0); - } - - static void dispatchMessage(MemorySegment message) { - call(Libs.DISPATCH_MESSAGE, message); - } - - static void postMessage(MemorySegment window, int message, long wParam, long lParam) { - call(Libs.POST_MESSAGE, window, message, wParam, lParam); - } - - static void postQuitMessage(int exitCode) { - call(Libs.POST_QUIT_MESSAGE, exitCode); - } - - /** @return whether the devices were registered for background delivery */ - static boolean registerRawInputDevices(MemorySegment devices, int count) { - return (int) call(Libs.REGISTER_RAW_INPUT, devices, count, (int) RAWINPUTDEVICE_SIZE) != 0; - } - - /** @return bytes written into {@code buffer}, or -1 on failure */ - static int getRawInputData(MemorySegment handle, MemorySegment buffer, MemorySegment size) { - return (int) call(Libs.GET_RAW_INPUT_DATA, handle, RID_INPUT, buffer, size, - (int) RawInput.HEADER_SIZE); - } - - /** - * The layout's name for a key. - * - * @param lParam scan code in bits 16..23, the extended flag in bit 24, as the API wants - */ - static String keyName(int lParam, Arena arena) { - MemorySegment buffer = arena.allocate(128); - int length = (int) call(Libs.GET_KEY_NAME_TEXT, lParam, buffer, 64); - if (length <= 0) return null; - return buffer.getString(0, StandardCharsets.UTF_16LE); - } - - private static Object call(MethodHandle handle, Object... args) { - try { - return handle.invokeWithArguments(args); - } catch (Throwable t) { - throw new IllegalStateException("Win32 call failed", t); - } - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/WindowsInputHook.java b/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/WindowsInputHook.java deleted file mode 100644 index 90a75f4..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/WindowsInputHook.java +++ /dev/null @@ -1,234 +0,0 @@ -package com.ts3client.hotkey.desktop; - -import com.ts3client.hotkey.GlobalInputHook; -import com.ts3client.hotkey.HotkeyKey; - -import java.lang.foreign.Arena; -import java.lang.foreign.MemorySegment; -import java.lang.foreign.ValueLayout; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.invoke.MethodType; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -/** - * System-wide input hook for Windows, built on raw input: a message-only window - * registers the keyboard and mouse with {@code RIDEV_INPUTSINK}, so every key and button - * on the machine arrives as {@code WM_INPUT} whether or not this application is in front, - * and the event still reaches the foreground window untouched. - * - *

    Chosen over a {@code WH_KEYBOARD_LL} hook because raw input only observes: it cannot - * swallow a keystroke, it does not put this process in the path of the system input queue - * — where a slow callback stalls typing everywhere — and it reports the side buttons and - * both edges of every key, which push-to-talk needs. - * - *

    A window's messages belong to the thread that created it, so the window is created - * on the pump thread and {@link #start} waits to hear whether that succeeded. - */ -public final class WindowsInputHook implements GlobalInputHook { - - private static final String WINDOW_CLASS = "Ts3jHotkeyInputSink"; - - /** How long to wait for the pump thread to stand its window up before giving up. */ - private static final long STARTUP_TIMEOUT_SECONDS = 5; - - private static final MethodHandle WND_PROC; - - static { - try { - WND_PROC = MethodHandles.lookup().findStatic(WindowsInputHook.class, "onMessage", - MethodType.methodType(long.class, MemorySegment.class, int.class, - long.class, long.class)); - } catch (ReflectiveOperationException e) { - throw new ExceptionInInitializerError(e); - } - } - - /** The running hook, for the static window procedure to find its way back. */ - private static volatile WindowsInputHook current; - - private volatile MemorySegment window = MemorySegment.NULL; - private Thread thread; - private volatile Listener listener; - private volatile boolean running; - private volatile String unavailable = "not started"; - - public static boolean isSupported() { - return Win32.isAvailable(); - } - - @Override - public void start(Listener listener) { - this.listener = listener; - CountDownLatch ready = new CountDownLatch(1); - thread = new Thread(() -> pump(ready), "ts3j-hotkeys-rawinput"); - thread.setDaemon(true); - thread.start(); - try { - if (!ready.await(STARTUP_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { - unavailable = "the raw input window did not come up"; - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - unavailable = "interrupted while starting"; - } - } - - /** Owns the window for its whole life: creates it, pumps it, tears it down. */ - private void pump(CountDownLatch ready) { - boolean signalled = false; - try (Arena arena = Arena.ofConfined()) { - MemorySegment className = Win32.wide(arena, WINDOW_CLASS); - MemorySegment instance = Win32.moduleHandle(); - MemorySegment stub = java.lang.foreign.Linker.nativeLinker() - .upcallStub(WND_PROC, Win32.WND_PROC, arena); - - MemorySegment wndClass = arena.allocate(Win32.WNDCLASS_SIZE); - wndClass.set(ValueLayout.JAVA_INT, Win32.WNDCLASS_CBSIZE, (int) Win32.WNDCLASS_SIZE); - wndClass.set(ValueLayout.ADDRESS, Win32.WNDCLASS_WNDPROC, stub); - wndClass.set(ValueLayout.ADDRESS, Win32.WNDCLASS_HINSTANCE, instance); - wndClass.set(ValueLayout.ADDRESS, Win32.WNDCLASS_CLASSNAME, className); - // A leftover registration from an earlier run in this process is harmless: - // CreateWindowEx only needs the class to exist. - Win32.registerClass(wndClass); - - MemorySegment hwnd = Win32.createMessageWindow(className, instance); - if (hwnd.equals(MemorySegment.NULL)) { - unavailable = "cannot create the raw input window"; - return; - } - window = hwnd; - - if (!Win32.registerRawInputDevices(rawInputDevices(arena, hwnd), 2)) { - unavailable = "RegisterRawInputDevices failed"; - Win32.destroyWindow(hwnd); - window = MemorySegment.NULL; - return; - } - - current = this; - running = true; - unavailable = ""; - ready.countDown(); - signalled = true; - - MemorySegment message = arena.allocate(Win32.MSG_SIZE); - while (running) { - int result = Win32.getMessage(message); - // 0 is WM_QUIT, -1 an error; either way the window is finished. - if (result <= 0) break; - Win32.dispatchMessage(message); - } - } catch (Throwable t) { - unavailable = describe(t); - } finally { - running = false; - window = MemorySegment.NULL; - if (current == this) current = null; - if (!signalled) ready.countDown(); - } - } - - /** The keyboard and the mouse, both asked for in the background. */ - private static MemorySegment rawInputDevices(Arena arena, MemorySegment hwnd) { - MemorySegment devices = arena.allocate(Win32.RAWINPUTDEVICE_SIZE * 2); - int[] usages = {Win32.USAGE_KEYBOARD, Win32.USAGE_MOUSE}; - for (int i = 0; i < usages.length; i++) { - long base = i * Win32.RAWINPUTDEVICE_SIZE; - devices.set(ValueLayout.JAVA_SHORT, base + Win32.RAWINPUTDEVICE_USAGE_PAGE, - (short) Win32.USAGE_PAGE_GENERIC); - devices.set(ValueLayout.JAVA_SHORT, base + Win32.RAWINPUTDEVICE_USAGE, - (short) usages[i]); - devices.set(ValueLayout.JAVA_INT, base + Win32.RAWINPUTDEVICE_FLAGS, - Win32.RIDEV_INPUTSINK); - devices.set(ValueLayout.ADDRESS, base + Win32.RAWINPUTDEVICE_TARGET, hwnd); - } - return devices; - } - - /** Upcall target: the window procedure. */ - @SuppressWarnings("unused") - private static long onMessage(MemorySegment hwnd, int message, long wParam, long lParam) { - WindowsInputHook hook = current; - try { - if (message == Win32.WM_INPUT && hook != null) { - hook.readInput(lParam); - } else if (message == Win32.WM_DESTROY) { - Win32.postQuitMessage(0); - return 0; - } - } catch (Throwable ignored) { - } - // WM_INPUT must reach DefWindowProc too, so the system can release the event. - return Win32.defWindowProc(hwnd, message, wParam, lParam); - } - - /** Copies one {@code RAWINPUT} out of the system and turns it into hotkey events. */ - private void readInput(long handle) { - Listener l = listener; - if (l == null) return; - try (Arena arena = Arena.ofConfined()) { - MemorySegment buffer = arena.allocate(RawInput.BUFFER_SIZE); - MemorySegment size = arena.allocate(ValueLayout.JAVA_INT); - size.set(ValueLayout.JAVA_INT, 0, (int) RawInput.BUFFER_SIZE); - if (Win32.getRawInputData(MemorySegment.ofAddress(handle), buffer, size) <= 0) return; - - switch (buffer.get(ValueLayout.JAVA_INT, RawInput.HEADER_TYPE)) { - case RawInput.TYPE_KEYBOARD -> { - int makeCode = buffer.get(ValueLayout.JAVA_SHORT, RawInput.KEYBOARD_MAKE_CODE) & 0xFFFF; - int flags = buffer.get(ValueLayout.JAVA_SHORT, RawInput.KEYBOARD_FLAGS) & 0xFFFF; - int vkey = buffer.get(ValueLayout.JAVA_SHORT, RawInput.KEYBOARD_VKEY) & 0xFFFF; - int code = RawInput.scanCode(makeCode, flags, vkey); - if (code >= 0) l.onInput(HotkeyKey.keyboard(code), !RawInput.isRelease(flags)); - } - case RawInput.TYPE_MOUSE -> { - int flags = buffer.get(ValueLayout.JAVA_SHORT, RawInput.MOUSE_BUTTON_FLAGS) & 0xFFFF; - short data = buffer.get(ValueLayout.JAVA_SHORT, RawInput.MOUSE_BUTTON_FLAGS + 2); - for (RawInput.ButtonEvent e : RawInput.buttons(flags, data)) { - l.onInput(e.key(), e.pressed()); - } - } - default -> { - } - } - } catch (Throwable ignored) { - } - } - - @Override - public boolean isRunning() { - return running; - } - - @Override - public String unavailableReason() { - return running ? "" : unavailable; - } - - @Override - public String keyName(HotkeyKey key) { - return WindowsKeyNamer.name(key); - } - - @Override - public void close() { - listener = null; - running = false; - MemorySegment hwnd = window; - try { - // Closing has to happen on the pump thread; ask it to, then let it unwind. - if (!hwnd.equals(MemorySegment.NULL)) Win32.postMessage(hwnd, Win32.WM_CLOSE, 0, 0); - if (thread != null) thread.join(2000); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } catch (Throwable ignored) { - } - thread = null; - } - - private static String describe(Throwable t) { - String message = t.getMessage(); - return (message == null || message.isBlank()) ? t.getClass().getSimpleName() : message; - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/WindowsKeyNamer.java b/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/WindowsKeyNamer.java deleted file mode 100644 index ad59f66..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/WindowsKeyNamer.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.ts3client.hotkey.desktop; - -import com.ts3client.hotkey.HotkeyKey; - -import java.lang.foreign.Arena; -import java.util.HashMap; -import java.util.Map; - -/** - * Names scan codes through the active Windows layout, so a hotkey button shows "A" - * rather than "Key 30" — the counterpart to {@link X11KeyNamer}. - * - *

    {@code GetKeyNameTextW} wants the scan code where a {@code WM_KEYDOWN} would carry - * it: bits 16..23, with bit 24 marking the {@code E0} escape. - */ -final class WindowsKeyNamer { - - private WindowsKeyNamer() { - } - - private static final Map CACHE = new HashMap<>(); - - static synchronized String name(HotkeyKey key) { - if (key.device() != HotkeyKey.Device.KEYBOARD) return null; - if (!Win32.isAvailable()) return null; - return CACHE.computeIfAbsent(key.code(), code -> { - try (Arena arena = Arena.ofConfined()) { - int lParam = (code & 0xFF) << 16; - if ((code & 0xE000) == 0xE000) lParam |= 1 << 24; - String name = Win32.keyName(lParam, arena); - return (name == null || name.isBlank()) ? null : name; - } catch (Throwable t) { - return null; - } - }); - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/X11KeyNamer.java b/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/X11KeyNamer.java deleted file mode 100644 index 7ff49d3..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/X11KeyNamer.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.ts3client.hotkey.desktop; - -import com.ts3client.hotkey.HotkeyKey; - -import java.lang.foreign.MemorySegment; -import java.util.HashMap; -import java.util.Map; - -/** - * Names keycodes using the X keyboard layout, so a hotkey button shows "A" rather than - * "Key 38". Bindings themselves stay layout-independent; only the label comes from here. - * - *

    Keeps one long-lived display connection of its own, opened on first use, so it can - * be asked from any thread without racing the input hooks' own connections. - */ -final class X11KeyNamer { - - private X11KeyNamer() { - } - - private static final Map CACHE = new HashMap<>(); - private static MemorySegment display; - private static boolean tried; - - static synchronized String name(HotkeyKey key) { - if (key.device() != HotkeyKey.Device.KEYBOARD) return null; - if (!tried) { - tried = true; - try { - if (Xlib.isCoreAvailable() && System.getenv("DISPLAY") != null) { - display = Xlib.openDisplay(); - } - } catch (Throwable ignored) { - display = null; - } - } - if (display == null || display.equals(MemorySegment.NULL)) return null; - return CACHE.computeIfAbsent(key.code(), code -> { - try { - long sym = Xlib.keysym(display, code); - return sym == 0 ? null : KeyNames.pretty(Xlib.keysymName(sym)); - } catch (Throwable t) { - return null; - } - }); - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/XInput2InputHook.java b/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/XInput2InputHook.java deleted file mode 100644 index 6b5ae8c..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/XInput2InputHook.java +++ /dev/null @@ -1,206 +0,0 @@ -package com.ts3client.hotkey.desktop; - -import com.ts3client.hotkey.GlobalInputHook; -import com.ts3client.hotkey.HotkeyKey; - -import java.lang.foreign.Arena; -import java.lang.foreign.MemorySegment; -import java.lang.foreign.ValueLayout; - -/** - * System-wide input hook built on XInput2 raw events, the way TeamSpeak's own Linux - * client does it: {@code XI_RawKeyPress} and friends are selected on the root window, so - * every key and button on the machine arrives here regardless of which window has focus, - * and the event still reaches that window untouched. - * - *

    Raw events report the device's own view of the key, before focus routing and before - * any layout mapping, which is precisely what a hotkey wants — the detail field is the - * keycode, matching how {@link HotkeyKey} identifies keys. - * - *

    On at least some driver stacks, {@code XI_RawButtonRelease} is never delivered here - * at all: the X server hands the initiating {@code XI_RawButtonPress} to every raw - * listener, but the matching release only reaches whichever client holds the pointer's - * implicit per-click grab, which is never us. An active {@code XIGrabDevice} grab makes - * this hook that owner and does fix delivery, but even with {@code owner_events} set it - * stopped clicks from reaching other windows at all — worse than the bug it fixes — so it - * is not used here. {@link XRecordInputHook} is unaffected and takes over first on X11 as - * a result; this hook stays as its fallback for servers without RECORD. - * - *

    Under Wayland this hook lives inside Xwayland and therefore sees what Xwayland is - * given: every X11 client, plus — on compositors that allow it, KWin's "legacy X11 app - * support" among them — keys aimed at native Wayland windows too. Where the compositor - * forwards nothing, {@link EvdevInputHook} is the way out. - */ -public final class XInput2InputHook implements GlobalInputHook { - - /** How long the event loop sleeps on the socket before rechecking {@link #running}. */ - private static final int POLL_TIMEOUT_MILLIS = 200; - - private Arena arena; - private MemorySegment display = MemorySegment.NULL; - private int opcode = -1; - private Thread thread; - private volatile Listener listener; - private volatile boolean running; - private volatile String unavailable = "not started"; - - public static boolean isSupported() { - return Xlib.isInputAvailable() && System.getenv("DISPLAY") != null; - } - - @Override - public void start(Listener listener) { - this.listener = listener; - try { - open(); - } catch (Throwable t) { - unavailable = describe(t); - closeQuietly(); - } - } - - private void open() { - arena = Arena.ofShared(); - display = Xlib.openDisplay(); - if (display.equals(MemorySegment.NULL)) { - throw new IllegalStateException("cannot open the X display"); - } - opcode = Xlib.queryExtension(display, "XInputExtension", arena); - if (opcode < 0) throw new IllegalStateException("the X server has no XInput extension"); - if (!Xlib.queryInputVersion(display, arena)) { - throw new IllegalStateException("the X server does not speak XInput 2"); - } - - long root = Xlib.defaultRootWindow(display); - int maskLen = maskLen(); - MemorySegment bits = rawMaskBits(maskLen); - int[] masters = Xlib.queryMasterDeviceIds(display, arena); - Xlib.selectInputEvents(display, root, masters, bits, maskLen, arena); - Xlib.sync(display); - - running = true; - unavailable = ""; - thread = new Thread(this::pump, "ts3j-hotkeys-xinput2"); - thread.setDaemon(true); - thread.start(); - } - - private static int maskLen() { - // XIMaskLen(event): the byte length of a mask covering event types up to this one. - return (Xlib.XI_RAW_BUTTON_RELEASE >> 3) + 1; - } - - /** The four raw event types, as a byte mask in {@code XISetMask} order. */ - private MemorySegment rawMaskBits(int maskLen) { - MemorySegment bits = arena.allocate(maskLen); - for (int type : new int[]{Xlib.XI_RAW_KEY_PRESS, Xlib.XI_RAW_KEY_RELEASE, - Xlib.XI_RAW_BUTTON_PRESS, Xlib.XI_RAW_BUTTON_RELEASE}) { - long index = type / 8; - byte bit = (byte) (1 << (type % 8)); - bits.set(ValueLayout.JAVA_BYTE, index, - (byte) (bits.get(ValueLayout.JAVA_BYTE, index) | bit)); - } - return bits; - } - - private void pump() { - try (Arena loop = Arena.ofConfined()) { - MemorySegment event = loop.allocate(Xlib.EVENT_SIZE); - MemorySegment pollFd = Xlib.pollFd(display, loop); - while (running) { - if (Xlib.pending(display) <= 0) { - Xlib.awaitEvent(pollFd, POLL_TIMEOUT_MILLIS); - continue; - } - Xlib.nextEvent(display, event); - handle(event); - } - } catch (Throwable t) { - unavailable = describe(t); - } finally { - running = false; - } - } - - /** Unpacks one event, which is ours only when it is a generic event from XInput2. */ - private void handle(MemorySegment event) { - if (event.get(ValueLayout.JAVA_INT, Xlib.COOKIE_TYPE) != Xlib.GENERIC_EVENT) return; - if (event.get(ValueLayout.JAVA_INT, Xlib.COOKIE_EXTENSION) != opcode) return; - if (!Xlib.getEventData(display, event)) return; - try { - int evtype = event.get(ValueLayout.JAVA_INT, Xlib.COOKIE_EVTYPE); - MemorySegment raw = event.get(ValueLayout.ADDRESS, Xlib.COOKIE_DATA); - if (raw.equals(MemorySegment.NULL)) return; - int detail = raw.reinterpret(Xlib.RAW_EVENT_SIZE) - .get(ValueLayout.JAVA_INT, Xlib.RAW_EVENT_DETAIL); - dispatch(evtype, detail); - } finally { - Xlib.freeEventData(display, event); - } - } - - private void dispatch(int evtype, int detail) { - Listener l = listener; - if (l == null) return; - switch (evtype) { - case Xlib.XI_RAW_KEY_PRESS -> l.onInput(HotkeyKey.keyboard(detail), true); - case Xlib.XI_RAW_KEY_RELEASE -> l.onInput(HotkeyKey.keyboard(detail), false); - case Xlib.XI_RAW_BUTTON_PRESS -> l.onInput(HotkeyKey.mouse(detail), true); - case Xlib.XI_RAW_BUTTON_RELEASE -> l.onInput(HotkeyKey.mouse(detail), false); - default -> { - } - } - } - - @Override - public boolean isRunning() { - return running; - } - - @Override - public String unavailableReason() { - return running ? "" : unavailable; - } - - @Override - public String keyName(HotkeyKey key) { - return X11KeyNamer.name(key); - } - - @Override - public void close() { - listener = null; - running = false; - try { - if (thread != null) thread.join(POLL_TIMEOUT_MILLIS * 5L); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - closeQuietly(); - } - - private synchronized void closeQuietly() { - // The pump owns the display connection; closing it underneath would crash Xlib. - boolean pumpDone = thread == null || !thread.isAlive(); - if (pumpDone) { - try { - if (!display.equals(MemorySegment.NULL)) Xlib.closeDisplay(display); - } catch (Throwable ignored) { - } - display = MemorySegment.NULL; - if (arena != null) { - try { - arena.close(); - } catch (Throwable ignored) { - } - arena = null; - } - thread = null; - } - } - - private static String describe(Throwable t) { - String message = t.getMessage(); - return (message == null || message.isBlank()) ? t.getClass().getSimpleName() : message; - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/XRecordInputHook.java b/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/XRecordInputHook.java deleted file mode 100644 index 44b527a..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/XRecordInputHook.java +++ /dev/null @@ -1,212 +0,0 @@ -package com.ts3client.hotkey.desktop; - -import com.ts3client.hotkey.GlobalInputHook; -import com.ts3client.hotkey.HotkeyKey; - -import java.lang.foreign.Arena; -import java.lang.foreign.MemorySegment; -import java.lang.foreign.ValueLayout; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.invoke.MethodType; - -/** - * System-wide input hook built on X11's RECORD extension: it taps the core key and - * button events the server delivers to every client, so hotkeys work no matter which - * window has focus, and the keystroke still reaches that window untouched. - * - *

    Two connections are needed, as RECORD demands: a control one that creates and - * later tears the context down, and a data one that blocks inside - * {@code XRecordEnableContext} handing us events. - * - *

    Under Wayland the X server only ever sees events aimed at X clients, so this hook - * is not truly global there; {@link EvdevInputHook} is the way out. - */ -public final class XRecordInputHook implements GlobalInputHook { - - private static final MethodHandle CALLBACK; - - static { - try { - CALLBACK = MethodHandles.lookup().findStatic(XRecordInputHook.class, "onRecorded", - MethodType.methodType(void.class, MemorySegment.class, MemorySegment.class)); - } catch (ReflectiveOperationException e) { - throw new ExceptionInInitializerError(e); - } - } - - /** The running hook, for the static upcall to find its way back. */ - private static volatile XRecordInputHook current; - - private Arena arena; - private MemorySegment control = MemorySegment.NULL; - private MemorySegment data = MemorySegment.NULL; - private long context; - private Thread thread; - private volatile Listener listener; - private volatile boolean running; - private volatile String unavailable = "not started"; - - public static boolean isSupported() { - return Xlib.isAvailable() && System.getenv("DISPLAY") != null; - } - - @Override - public void start(Listener listener) { - this.listener = listener; - try { - open(); - } catch (Throwable t) { - unavailable = describe(t); - closeQuietly(); - } - } - - private void open() { - arena = Arena.ofShared(); - control = Xlib.openDisplay(); - if (control.equals(MemorySegment.NULL)) { - throw new IllegalStateException("cannot open the X display"); - } - if (!Xlib.queryRecordVersion(control, arena)) { - throw new IllegalStateException("the X server has no RECORD extension"); - } - - MemorySegment range = Xlib.allocRange(); - if (range.equals(MemorySegment.NULL)) throw new IllegalStateException("XRecordAllocRange failed"); - MemorySegment r = range.reinterpret(64); - r.set(ValueLayout.JAVA_BYTE, Xlib.RANGE_DEVICE_EVENTS_FIRST, (byte) Xlib.KEY_PRESS); - r.set(ValueLayout.JAVA_BYTE, Xlib.RANGE_DEVICE_EVENTS_LAST, (byte) Xlib.BUTTON_RELEASE); - - MemorySegment clients = arena.allocate(ValueLayout.JAVA_LONG); - clients.set(ValueLayout.JAVA_LONG, 0, Xlib.ALL_CLIENTS); - MemorySegment ranges = arena.allocate(ValueLayout.ADDRESS); - ranges.set(ValueLayout.ADDRESS, 0, range); - - context = Xlib.createContext(control, clients, 1, ranges, 1); - if (context == 0) throw new IllegalStateException("XRecordCreateContext failed"); - // The context id is allocated client-side and the request is not a round trip: - // without this the second connection can enable a context the server has yet to - // create, which it answers with BadContext. - Xlib.sync(control); - - data = Xlib.openDisplay(); - if (data.equals(MemorySegment.NULL)) { - throw new IllegalStateException("cannot open the second X display connection"); - } - - MemorySegment stub = java.lang.foreign.Linker.nativeLinker() - .upcallStub(CALLBACK, Xlib.INTERCEPT_PROC, arena); - - current = this; - running = true; - unavailable = ""; - thread = new Thread(() -> { - try { - // Blocks until close() disables the context from the control connection. - Xlib.enableContext(data, context, stub); - } catch (Throwable ignored) { - } finally { - running = false; - } - }, "ts3j-hotkeys-xrecord"); - thread.setDaemon(true); - thread.start(); - } - - /** Upcall target: one recorded protocol datum. */ - @SuppressWarnings("unused") - private static void onRecorded(MemorySegment closure, MemorySegment recorded) { - XRecordInputHook hook = current; - MemorySegment d = recorded.reinterpret(48); - try { - if (hook == null || d.get(ValueLayout.JAVA_INT, Xlib.INTERCEPT_CATEGORY) != Xlib.FROM_SERVER) { - return; - } - long length = d.get(ValueLayout.JAVA_LONG, Xlib.INTERCEPT_DATA_LEN); - MemorySegment event = d.get(ValueLayout.ADDRESS, Xlib.INTERCEPT_DATA); - // data_len counts 4-byte units; a core event is always 32 bytes. - if (event.equals(MemorySegment.NULL) || length < 2) return; - event = event.reinterpret(32); - hook.dispatch(event.get(ValueLayout.JAVA_BYTE, 0) & 0x7f, - event.get(ValueLayout.JAVA_BYTE, 1) & 0xff); - } catch (Throwable ignored) { - } finally { - Xlib.freeData(recorded); - } - } - - private void dispatch(int type, int detail) { - Listener l = listener; - if (l == null) return; - switch (type) { - case Xlib.KEY_PRESS -> l.onInput(HotkeyKey.keyboard(detail), true); - case Xlib.KEY_RELEASE -> l.onInput(HotkeyKey.keyboard(detail), false); - case Xlib.BUTTON_PRESS -> l.onInput(HotkeyKey.mouse(detail), true); - case Xlib.BUTTON_RELEASE -> l.onInput(HotkeyKey.mouse(detail), false); - default -> { - } - } - } - - @Override - public boolean isRunning() { - return running; - } - - @Override - public String unavailableReason() { - return running ? "" : unavailable; - } - - @Override - public String keyName(HotkeyKey key) { - return X11KeyNamer.name(key); - } - - @Override - public void close() { - listener = null; - running = false; - try { - if (!control.equals(MemorySegment.NULL) && context != 0) { - Xlib.disableContext(control, context); - Xlib.flush(control); - } - if (thread != null) thread.join(1000); - } catch (Throwable ignored) { - } - closeQuietly(); - } - - private synchronized void closeQuietly() { - if (current == this) current = null; - try { - if (!control.equals(MemorySegment.NULL) && context != 0) Xlib.freeContext(control, context); - } catch (Throwable ignored) { - } - context = 0; - for (MemorySegment display : new MemorySegment[]{data, control}) { - try { - if (!display.equals(MemorySegment.NULL)) Xlib.closeDisplay(display); - } catch (Throwable ignored) { - } - } - data = control = MemorySegment.NULL; - // The arena owns the upcall stub: freeing it while the recording thread could - // still call into it would take the JVM down, so a stuck thread keeps it alive. - if (arena != null && (thread == null || !thread.isAlive())) { - try { - arena.close(); - } catch (Throwable ignored) { - } - arena = null; - } - thread = null; - } - - private static String describe(Throwable t) { - String message = t.getMessage(); - return (message == null || message.isBlank()) ? t.getClass().getSimpleName() : message; - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/Xlib.java b/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/Xlib.java deleted file mode 100644 index 5137a13..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/hotkey/desktop/Xlib.java +++ /dev/null @@ -1,400 +0,0 @@ -package com.ts3client.hotkey.desktop; - -import java.lang.foreign.Arena; -import java.lang.foreign.FunctionDescriptor; -import java.lang.foreign.Linker; -import java.lang.foreign.MemorySegment; -import java.lang.foreign.SymbolLookup; -import java.lang.foreign.ValueLayout; -import java.lang.invoke.MethodHandle; -import java.nio.charset.StandardCharsets; - -/** - * Raw binding to {@code libX11}, the XInput2 extension in {@code libXi} and the RECORD - * extension in {@code libXtst}, with just the calls the X11 hooks need. - * - *

    Both extensions let a client watch input the server delivers to everyone else - * without intercepting it, which is exactly what a global hotkey needs: the keystroke - * still reaches the focused application. See {@link DesktopInputHooks#addX11Hooks} for - * which one is preferred and why. - * - *

    Each library loads lazily and failure is expected — with no X11 around, the - * {@code is*Available()} probes return {@code false} and the caller falls back to - * another backend. - */ -final class Xlib { - - private Xlib() { - } - - static final ValueLayout.OfInt INT = ValueLayout.JAVA_INT; - static final ValueLayout.OfLong LONG = ValueLayout.JAVA_LONG; - private static final java.lang.foreign.AddressLayout PTR = ValueLayout.ADDRESS; - - /** Core event types (X.h) as they appear in the recorded protocol data. */ - static final int KEY_PRESS = 2; - static final int KEY_RELEASE = 3; - static final int BUTTON_PRESS = 4; - static final int BUTTON_RELEASE = 5; - - /** {@code XRecordAllClients}: record every client, present and future. */ - static final long ALL_CLIENTS = 3L; - - /** {@code XRecordInterceptData.category} values we care about. */ - static final int FROM_SERVER = 0; - - /** - * {@code XRecordRange}: only {@code device_events} is filled in. Its two bytes sit - * after the request/reply and delivered-event ranges, at a fixed LP64 offset. - */ - static final long RANGE_DEVICE_EVENTS_FIRST = 18; - static final long RANGE_DEVICE_EVENTS_LAST = 19; - - /** {@code XRecordInterceptData}: the protocol bytes and the reason we were called. */ - static final long INTERCEPT_CATEGORY = 24; - static final long INTERCEPT_DATA = 32; - static final long INTERCEPT_DATA_LEN = 40; - - /** {@code GenericEvent}, the envelope every extension event arrives in. */ - static final int GENERIC_EVENT = 35; - - /** XInput2 raw event types (XI2.h): the device's own view, before any focus routing. */ - static final int XI_RAW_KEY_PRESS = 13; - static final int XI_RAW_KEY_RELEASE = 14; - static final int XI_RAW_BUTTON_PRESS = 15; - static final int XI_RAW_BUTTON_RELEASE = 16; - - /** {@code XIAllMasterDevices}: raw events reach us through the master devices. */ - static final int XI_ALL_MASTER_DEVICES = 1; - - /** An {@code XEvent} is a union of 24 longs; a cookie is the widest member we read. */ - static final long EVENT_SIZE = 192; - - /** {@code XGenericEventCookie} field offsets under LP64. */ - static final long COOKIE_TYPE = 0; - static final long COOKIE_EXTENSION = 32; - static final long COOKIE_EVTYPE = 36; - static final long COOKIE_DATA = 48; - - /** - * {@code XIRawEvent.detail} — the keycode or button number — past the generic header, - * {@code time}, {@code deviceid} and {@code sourceid}. - */ - static final long RAW_EVENT_DETAIL = 56; - static final long RAW_EVENT_SIZE = 152; - - /** {@code XIEventMask}: {@code deviceid}, {@code mask_len}, then the mask pointer. */ - static final long EVENT_MASK_SIZE = 16; - static final long EVENT_MASK_DEVICEID = 0; - static final long EVENT_MASK_LEN = 4; - static final long EVENT_MASK_MASK = 8; - - /** {@code XIDeviceInfo.deviceid} — the only field {@link #queryMasterDeviceIds} needs. */ - static final long DEVICE_INFO_SIZE = 40; - static final long DEVICE_INFO_DEVICEID = 0; - - private static final Linker LINKER = Linker.nativeLinker(); - private static final String[] X11_NAMES = {"libX11.so.6", "libX11.so"}; - private static final String[] XI_NAMES = {"libXi.so.6", "libXi.so"}; - private static final String[] XTST_NAMES = {"libXtst.so.6", "libXtst.so"}; - - /** libX11 alone: enough to open a display and name keys. */ - private static final class Core { - static final SymbolLookup LIB = load(X11_NAMES, "libX11"); - - static final MethodHandle X_OPEN_DISPLAY = - downcall(LIB, "XOpenDisplay", FunctionDescriptor.of(PTR, PTR)); - static final MethodHandle X_CLOSE_DISPLAY = - downcall(LIB, "XCloseDisplay", FunctionDescriptor.of(INT, PTR)); - static final MethodHandle X_FLUSH = - downcall(LIB, "XFlush", FunctionDescriptor.of(INT, PTR)); - static final MethodHandle X_SYNC = - downcall(LIB, "XSync", FunctionDescriptor.of(INT, PTR, INT)); - static final MethodHandle XKB_KEYCODE_TO_KEYSYM = - downcall(LIB, "XkbKeycodeToKeysym", FunctionDescriptor.of(LONG, PTR, INT, INT, INT)); - static final MethodHandle X_KEYSYM_TO_STRING = - downcall(LIB, "XKeysymToString", FunctionDescriptor.of(PTR, LONG)); - static final MethodHandle X_QUERY_EXTENSION = - downcall(LIB, "XQueryExtension", FunctionDescriptor.of(INT, PTR, PTR, PTR, PTR, PTR)); - static final MethodHandle X_DEFAULT_ROOT_WINDOW = - downcall(LIB, "XDefaultRootWindow", FunctionDescriptor.of(LONG, PTR)); - static final MethodHandle X_CONNECTION_NUMBER = - downcall(LIB, "XConnectionNumber", FunctionDescriptor.of(INT, PTR)); - static final MethodHandle X_PENDING = - downcall(LIB, "XPending", FunctionDescriptor.of(INT, PTR)); - static final MethodHandle X_NEXT_EVENT = - downcall(LIB, "XNextEvent", FunctionDescriptor.of(INT, PTR, PTR)); - static final MethodHandle X_GET_EVENT_DATA = - downcall(LIB, "XGetEventData", FunctionDescriptor.of(INT, PTR, PTR)); - static final MethodHandle X_FREE_EVENT_DATA = - downcall(LIB, "XFreeEventData", FunctionDescriptor.ofVoid(PTR, PTR)); - } - - /** XInput2, which ships separately in libXi. */ - private static final class Input { - static final SymbolLookup LIB = load(XI_NAMES, "libXi"); - - static final MethodHandle XI_QUERY_VERSION = - downcall(LIB, "XIQueryVersion", FunctionDescriptor.of(INT, PTR, PTR, PTR)); - static final MethodHandle XI_SELECT_EVENTS = - downcall(LIB, "XISelectEvents", FunctionDescriptor.of(INT, PTR, LONG, PTR, INT)); - static final MethodHandle XI_QUERY_DEVICE = - downcall(LIB, "XIQueryDevice", FunctionDescriptor.of(PTR, PTR, INT, PTR)); - static final MethodHandle XI_FREE_DEVICE_INFO = - downcall(LIB, "XIFreeDeviceInfo", FunctionDescriptor.ofVoid(PTR)); - } - - /** {@code poll(2)}, so the event loop can wait on the X socket and still be woken. */ - private static final class Poll { - static final MethodHandle POLL = LINKER.downcallHandle( - LINKER.defaultLookup().find("poll").orElseThrow(() -> - new UnsatisfiedLinkError("unresolved symbol poll")), - FunctionDescriptor.of(INT, PTR, LONG, INT)); - } - - /** {@code struct pollfd} is an int and two shorts, and {@code POLLIN} is bit 0. */ - private static final long POLLFD_SIZE = 8; - private static final long POLLFD_EVENTS = 4; - private static final short POLLIN = 1; - - /** The RECORD extension, which ships separately in libXtst. */ - private static final class Record { - static final SymbolLookup LIB = load(XTST_NAMES, "libXtst"); - - static final MethodHandle QUERY_VERSION = - downcall(LIB, "XRecordQueryVersion", FunctionDescriptor.of(INT, PTR, PTR, PTR)); - static final MethodHandle ALLOC_RANGE = - downcall(LIB, "XRecordAllocRange", FunctionDescriptor.of(PTR)); - static final MethodHandle CREATE_CONTEXT = - downcall(LIB, "XRecordCreateContext", - FunctionDescriptor.of(LONG, PTR, INT, PTR, INT, PTR, INT)); - static final MethodHandle ENABLE_CONTEXT = - downcall(LIB, "XRecordEnableContext", FunctionDescriptor.of(INT, PTR, LONG, PTR, PTR)); - static final MethodHandle DISABLE_CONTEXT = - downcall(LIB, "XRecordDisableContext", FunctionDescriptor.of(INT, PTR, LONG)); - static final MethodHandle FREE_CONTEXT = - downcall(LIB, "XRecordFreeContext", FunctionDescriptor.of(INT, PTR, LONG)); - static final MethodHandle FREE_DATA = - downcall(LIB, "XRecordFreeData", FunctionDescriptor.ofVoid(PTR)); - } - - private static SymbolLookup load(String[] names, String what) { - IllegalArgumentException last = null; - for (String name : names) { - try { - return SymbolLookup.libraryLookup(name, Arena.global()); - } catch (IllegalArgumentException e) { - last = e; - } - } - throw (last != null) ? last : new IllegalArgumentException(what + " not found"); - } - - private static MethodHandle downcall(SymbolLookup lookup, String symbol, - FunctionDescriptor descriptor) { - return LINKER.downcallHandle( - lookup.find(symbol).orElseThrow(() -> - new UnsatisfiedLinkError("unresolved symbol " + symbol)), - descriptor); - } - - /** The C signature of {@code XRecordInterceptProc}. */ - static final FunctionDescriptor INTERCEPT_PROC = FunctionDescriptor.ofVoid(PTR, PTR); - - /** Whether libX11 loaded, which is all that naming keys needs. */ - static boolean isCoreAvailable() { - try { - return Core.LIB != null; - } catch (Throwable t) { - return false; - } - } - - static boolean isAvailable() { - try { - return Core.LIB != null && Record.LIB != null; - } catch (Throwable t) { - return false; - } - } - - /** Whether libX11 and libXi both loaded, which is what the XInput2 hook needs. */ - static boolean isInputAvailable() { - try { - return Core.LIB != null && Input.LIB != null && Poll.POLL != null; - } catch (Throwable t) { - return false; - } - } - - static MemorySegment openDisplay() { - return (MemorySegment) call(Core.X_OPEN_DISPLAY, MemorySegment.NULL); - } - - static void closeDisplay(MemorySegment display) { - call(Core.X_CLOSE_DISPLAY, display); - } - - static void flush(MemorySegment display) { - call(Core.X_FLUSH, display); - } - - /** Flushes and waits for the server to have processed everything sent so far. */ - static void sync(MemorySegment display) { - call(Core.X_SYNC, display, 0); - } - - /** @return whether the server has the RECORD extension */ - static boolean queryRecordVersion(MemorySegment display, Arena arena) { - MemorySegment major = arena.allocate(INT); - MemorySegment minor = arena.allocate(INT); - return (int) call(Record.QUERY_VERSION, display, major, minor) != 0; - } - - static MemorySegment allocRange() { - return (MemorySegment) call(Record.ALLOC_RANGE); - } - - static long createContext(MemorySegment display, MemorySegment clients, int clientCount, - MemorySegment ranges, int rangeCount) { - return (long) call(Record.CREATE_CONTEXT, display, 0, clients, clientCount, ranges, rangeCount); - } - - static int enableContext(MemorySegment display, long context, MemorySegment callback) { - return (int) call(Record.ENABLE_CONTEXT, display, context, callback, MemorySegment.NULL); - } - - static void disableContext(MemorySegment display, long context) { - call(Record.DISABLE_CONTEXT, display, context); - } - - static void freeContext(MemorySegment display, long context) { - call(Record.FREE_CONTEXT, display, context); - } - - static void freeData(MemorySegment data) { - call(Record.FREE_DATA, data); - } - - /** @return the extension's major opcode, or -1 when the server does not have it */ - static int queryExtension(MemorySegment display, String name, Arena arena) { - MemorySegment opcode = arena.allocate(INT); - MemorySegment event = arena.allocate(INT); - MemorySegment error = arena.allocate(INT); - int found = (int) call(Core.X_QUERY_EXTENSION, display, arena.allocateFrom(name), - opcode, event, error); - return found != 0 ? opcode.get(INT, 0) : -1; - } - - /** @return whether the server speaks at least XInput 2.0 */ - static boolean queryInputVersion(MemorySegment display, Arena arena) { - MemorySegment major = arena.allocate(INT); - MemorySegment minor = arena.allocate(INT); - major.set(INT, 0, 2); - minor.set(INT, 0, 0); - // Success is 0; anything else means the server would not agree on 2.x. - return (int) call(Input.XI_QUERY_VERSION, display, major, minor) == 0; - } - - static long defaultRootWindow(MemorySegment display) { - return (long) call(Core.X_DEFAULT_ROOT_WINDOW, display); - } - - /** - * Asks for the events set in {@code bits} on {@code window}, once per device in - * {@code deviceIds}: selecting against {@code XIAllMasterDevices} itself does not - * reliably deliver every raw event type, so callers resolve it to real device ids first - * with {@link #queryMasterDeviceIds}. - */ - static void selectInputEvents(MemorySegment display, long window, int[] deviceIds, - MemorySegment bits, int maskLen, Arena arena) { - MemorySegment masks = arena.allocate(EVENT_MASK_SIZE * deviceIds.length); - for (int i = 0; i < deviceIds.length; i++) { - long base = i * EVENT_MASK_SIZE; - masks.set(INT, base + EVENT_MASK_DEVICEID, deviceIds[i]); - masks.set(INT, base + EVENT_MASK_LEN, maskLen); - masks.set(PTR, base + EVENT_MASK_MASK, bits); - } - call(Input.XI_SELECT_EVENTS, display, window, masks, deviceIds.length); - } - - /** - * The real device ids behind the {@code XIAllMasterDevices} pseudo-device — selecting - * raw events against each one individually, rather than the pseudo-device itself, is - * the more correct form (some drivers reportedly need it), even though it alone does - * not fix the {@code XI_RawButtonRelease} gap {@link XInput2InputHook} documents. - */ - static int[] queryMasterDeviceIds(MemorySegment display, Arena arena) { - MemorySegment count = arena.allocate(INT); - MemorySegment infos = (MemorySegment) call(Input.XI_QUERY_DEVICE, display, - XI_ALL_MASTER_DEVICES, count); - int n = count.get(INT, 0); - if (infos.equals(MemorySegment.NULL) || n <= 0) return new int[0]; - try { - MemorySegment array = infos.reinterpret(DEVICE_INFO_SIZE * n); - int[] ids = new int[n]; - for (int i = 0; i < n; i++) { - ids[i] = array.get(INT, i * DEVICE_INFO_SIZE + DEVICE_INFO_DEVICEID); - } - return ids; - } finally { - call(Input.XI_FREE_DEVICE_INFO, infos); - } - } - - static int pending(MemorySegment display) { - return (int) call(Core.X_PENDING, display); - } - - static void nextEvent(MemorySegment display, MemorySegment event) { - call(Core.X_NEXT_EVENT, display, event); - } - - /** Fetches a generic event's payload; the caller must free it when this succeeds. */ - static boolean getEventData(MemorySegment display, MemorySegment cookie) { - return (int) call(Core.X_GET_EVENT_DATA, display, cookie) != 0; - } - - static void freeEventData(MemorySegment display, MemorySegment cookie) { - call(Core.X_FREE_EVENT_DATA, display, cookie); - } - - /** - * A {@code struct pollfd} watching the display connection, to be allocated once and - * handed to {@link #awaitEvent} for the life of an event loop. - */ - static MemorySegment pollFd(MemorySegment display, Arena arena) { - MemorySegment fds = arena.allocate(POLLFD_SIZE); - fds.set(INT, 0, (int) call(Core.X_CONNECTION_NUMBER, display)); - fds.set(ValueLayout.JAVA_SHORT, POLLFD_EVENTS, POLLIN); - return fds; - } - - /** - * Waits until the connection has something to read or the timeout runs out, so an - * event loop can stay asleep yet still notice it has been asked to stop. - */ - static void awaitEvent(MemorySegment pollFd, int timeoutMillis) { - call(Poll.POLL, pollFd, 1L, timeoutMillis); - } - - /** The unshifted keysym of a keycode in the first group, or 0 when unbound. */ - static long keysym(MemorySegment display, int keycode) { - return (long) call(Core.XKB_KEYCODE_TO_KEYSYM, display, keycode, 0, 0); - } - - /** The keysym's X name ("a", "Control_L", "F5"), or {@code null}. */ - static String keysymName(long keysym) { - MemorySegment name = (MemorySegment) call(Core.X_KEYSYM_TO_STRING, keysym); - if (name == null || name.equals(MemorySegment.NULL)) return null; - return name.reinterpret(Long.MAX_VALUE).getString(0, StandardCharsets.US_ASCII); - } - - private static Object call(MethodHandle handle, Object... args) { - try { - return handle.invokeWithArguments(args); - } catch (Throwable t) { - throw new IllegalStateException("X11 call failed", t); - } - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/notify/desktop/DBusConnection.java b/ts3-client/desktop/src/main/java/com/ts3client/notify/desktop/DBusConnection.java deleted file mode 100644 index 408a569..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/notify/desktop/DBusConnection.java +++ /dev/null @@ -1,215 +0,0 @@ -package com.ts3client.notify.desktop; - -import java.io.EOFException; -import java.io.IOException; -import java.net.StandardProtocolFamily; -import java.net.UnixDomainSocketAddress; -import java.nio.ByteBuffer; -import java.nio.channels.SocketChannel; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.HexFormat; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicLong; - -/** - * A connection to the user's D-Bus session bus, spoken directly over its Unix socket: - * method calls and the signals a match rule lets through, which is all a client of a - * desktop service needs. Signals and replies are read on a thread of its own. - */ -final class DBusConnection implements AutoCloseable { - - private static final String BUS = "org.freedesktop.DBus"; - private static final long CALL_TIMEOUT_MS = 3_000; - - /** A signal from the bus. */ - interface SignalHandler { - void signal(String iface, String member, List args); - } - - private final SocketChannel channel; - private final AtomicLong serials = new AtomicLong(); - private final Map>> pending = new ConcurrentHashMap<>(); - private volatile SignalHandler signals = (iface, member, args) -> { }; - private volatile boolean closed; - - private DBusConnection(SocketChannel channel) { - this.channel = channel; - } - - /** Connects to the session bus named by {@code DBUS_SESSION_BUS_ADDRESS}, or the usual socket. */ - static DBusConnection session() throws IOException { - Path socket = sessionSocket(); - if (socket == null) throw new IOException("No D-Bus session bus socket"); - SocketChannel channel = SocketChannel.open(StandardProtocolFamily.UNIX); - try { - channel.connect(UnixDomainSocketAddress.of(socket)); - authenticate(channel); - DBusConnection bus = new DBusConnection(channel); - Thread reader = new Thread(bus::readLoop, "dbus-reader"); - reader.setDaemon(true); - reader.start(); - bus.call(BUS, "/org/freedesktop/DBus", BUS, "Hello", ""); - return bus; - } catch (IOException | RuntimeException e) { - channel.close(); - throw e; - } - } - - private static Path sessionSocket() { - String address = System.getenv("DBUS_SESSION_BUS_ADDRESS"); - if (address != null) { - for (String entry : address.split(";")) { - if (!entry.startsWith("unix:")) continue; - for (String pair : entry.substring(5).split(",")) { - // An abstract socket (unix:abstract=) is out of reach of Java's Unix sockets. - if (pair.startsWith("path=")) return Path.of(unescape(pair.substring(5))); - } - } - } - String runtime = System.getenv("XDG_RUNTIME_DIR"); - if (runtime == null) return null; - Path socket = Path.of(runtime, "bus"); - return Files.exists(socket) ? socket : null; - } - - /** Undoes the %xx escaping of D-Bus addresses. */ - private static String unescape(String value) { - StringBuilder out = new StringBuilder(); - for (int i = 0; i < value.length(); i++) { - char c = value.charAt(i); - if (c == '%' && i + 2 < value.length()) { - out.append((char) Integer.parseInt(value.substring(i + 1, i + 3), 16)); - i += 2; - } else { - out.append(c); - } - } - return out.toString(); - } - - /** The EXTERNAL mechanism: the bus checks the socket's peer credentials against our uid. */ - private static void authenticate(SocketChannel channel) throws IOException { - Object uid = Files.getAttribute(Path.of("/proc/self"), "unix:uid"); - String hexUid = HexFormat.of().formatHex(uid.toString().getBytes(StandardCharsets.US_ASCII)); - write(channel, "\0AUTH EXTERNAL " + hexUid + "\r\n"); - String reply = readLine(channel); - if (!reply.startsWith("OK ")) throw new IOException("D-Bus refused authentication: " + reply); - write(channel, "BEGIN\r\n"); - } - - private static void write(SocketChannel channel, String line) throws IOException { - ByteBuffer b = ByteBuffer.wrap(line.getBytes(StandardCharsets.US_ASCII)); - while (b.hasRemaining()) channel.write(b); - } - - private static String readLine(SocketChannel channel) throws IOException { - StringBuilder line = new StringBuilder(); - ByteBuffer one = ByteBuffer.allocate(1); - while (!line.toString().endsWith("\r\n")) { - one.clear(); - if (channel.read(one) < 0) throw new EOFException("D-Bus closed during authentication"); - line.append((char) one.get(0)); - } - return line.substring(0, line.length() - 2); - } - - void onSignal(SignalHandler handler) { - this.signals = handler; - } - - /** Lets the bus route the signals a match rule describes to this connection. */ - void addMatch(String rule) throws IOException { - call(BUS, "/org/freedesktop/DBus", BUS, "AddMatch", "s", rule); - } - - /** Calls a method and waits for its reply's arguments. */ - List call(String destination, String path, String iface, String member, String signature, - Object... args) throws IOException { - long serial = serials.incrementAndGet(); - CompletableFuture> reply = new CompletableFuture<>(); - pending.put(serial, reply); - try { - byte[] message = DBusWire.methodCall(serial, destination, path, iface, member, signature, args); - synchronized (channel) { - ByteBuffer b = ByteBuffer.wrap(message); - while (b.hasRemaining()) channel.write(b); - } - return reply.get(CALL_TIMEOUT_MS, TimeUnit.MILLISECONDS); - } catch (ExecutionException e) { - throw new IOException(e.getCause().getMessage(), e.getCause()); - } catch (TimeoutException e) { - throw new IOException(member + " got no reply", e); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new IOException("Interrupted", e); - } finally { - pending.remove(serial); - } - } - - private void readLoop() { - try { - ByteBuffer header = ByteBuffer.allocate(DBusWire.FIXED_HEADER); - while (!closed) { - header.clear(); - readFully(header); - ByteBuffer message = ByteBuffer.allocate(DBusWire.messageLength(header)); - message.put(header.flip()); - readFully(message); - dispatch(DBusWire.parse(message.array())); - } - } catch (IOException | RuntimeException e) { - if (!closed) System.err.println("D-Bus connection lost: " + e); - } finally { - closed = true; - pending.values().forEach(f -> f.completeExceptionally(new IOException("D-Bus connection closed"))); - } - } - - private void readFully(ByteBuffer b) throws IOException { - while (b.hasRemaining()) { - if (channel.read(b) < 0) throw new EOFException("D-Bus closed the connection"); - } - } - - private void dispatch(DBusWire.Message m) { - switch (m.type()) { - case DBusWire.METHOD_RETURN -> { - CompletableFuture> reply = pending.get(m.replySerial()); - if (reply != null) reply.complete(m.body()); - } - case DBusWire.ERROR -> { - CompletableFuture> reply = pending.get(m.replySerial()); - String detail = m.body().isEmpty() ? "" : ": " + m.body().getFirst(); - if (reply != null) reply.completeExceptionally(new IOException(m.string(DBusWire.FIELD_ERROR_NAME) + detail)); - } - case DBusWire.SIGNAL -> { - try { - signals.signal(m.string(DBusWire.FIELD_INTERFACE), m.string(DBusWire.FIELD_MEMBER), m.body()); - } catch (RuntimeException e) { - System.err.println("D-Bus signal handler failed: " + e); - } - } - default -> { } - } - } - - @Override - public void close() { - closed = true; - try { - channel.close(); - } catch (IOException ignored) { - // Nothing left to release. - } - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/notify/desktop/DBusWire.java b/ts3-client/desktop/src/main/java/com/ts3client/notify/desktop/DBusWire.java deleted file mode 100644 index 652b24b..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/notify/desktop/DBusWire.java +++ /dev/null @@ -1,322 +0,0 @@ -package com.ts3client.notify.desktop; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -/** - * The D-Bus wire format, for the handful of types a notification service speaks: - * basic types, arrays, structs, dictionaries and variants. - * - *

    Values map to Java as: {@code y} Integer, {@code b} Boolean, {@code i} Integer, - * {@code u} Long, {@code s o g} String, {@code a} List (or Map for a dictionary), - * a struct Object[], a variant the value it holds. - */ -final class DBusWire { - - static final int METHOD_CALL = 1; - static final int METHOD_RETURN = 2; - static final int ERROR = 3; - static final int SIGNAL = 4; - - static final int FIELD_PATH = 1; - static final int FIELD_INTERFACE = 2; - static final int FIELD_MEMBER = 3; - static final int FIELD_ERROR_NAME = 4; - static final int FIELD_REPLY_SERIAL = 5; - static final int FIELD_DESTINATION = 6; - static final int FIELD_SIGNATURE = 8; - - /** Everything before the header fields: byte order, type, flags, version and three lengths. */ - static final int FIXED_HEADER = 16; - - private DBusWire() { - } - - /** A message as read off the bus. */ - record Message(int type, long serial, Map fields, List body) { - - String string(int field) { - Object value = fields.get(field); - return value instanceof String s ? s : null; - } - - long replySerial() { - return fields.get(FIELD_REPLY_SERIAL) instanceof Long l ? l : -1; - } - } - - /** Builds a method call; the body is written after the header, aligned to 8 as the format wants. */ - static byte[] methodCall(long serial, String destination, String path, String iface, String member, - String signature, Object... args) { - Writer body = new Writer(); - body.values(signature, args); - - Writer out = new Writer(); - out.put('l'); - out.put(METHOD_CALL); - out.put(0); - out.put(1); - out.u32(body.size()); - out.u32(serial); - out.array(8, () -> { - out.field(FIELD_PATH, "o", path); - out.field(FIELD_DESTINATION, "s", destination); - out.field(FIELD_INTERFACE, "s", iface); - out.field(FIELD_MEMBER, "s", member); - if (!signature.isEmpty()) out.field(FIELD_SIGNATURE, "g", signature); - }); - out.align(8); - out.bytes(body.toBytes()); - return out.toBytes(); - } - - /** @return the length of the whole message whose fixed header this is */ - static int messageLength(ByteBuffer fixedHeader) { - ByteBuffer b = fixedHeader.duplicate().order(order(fixedHeader.get(0))); - int body = b.getInt(4); - int fields = b.getInt(12); - return pad8(FIXED_HEADER + fields) + body; - } - - static Message parse(byte[] data) { - Reader r = new Reader(ByteBuffer.wrap(data).order(order(data[0]))); - r.skip(1); - int type = r.buf.get() & 0xff; - r.skip(2); - int bodyLength = r.buf.getInt(); - long serial = Integer.toUnsignedLong(r.buf.getInt()); - - Map fields = new java.util.HashMap<>(); - for (Object field : (List) r.read("a(yv)")) { - Object[] pair = (Object[]) field; - fields.put((Integer) pair[0], pair[1]); - } - r.align(8); - String signature = fields.get(FIELD_SIGNATURE) instanceof String s ? s : ""; - List body = new ArrayList<>(); - int end = r.buf.position() + bodyLength; - for (int i = 0; i < signature.length() && r.buf.position() < end; ) { - int next = typeEnd(signature, i); - body.add(r.read(signature.substring(i, next))); - i = next; - } - return new Message(type, serial, fields, body); - } - - private static ByteOrder order(byte marker) { - return marker == 'B' ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN; - } - - private static int pad8(int n) { - return (n + 7) & ~7; - } - - /** @return the index just past the single complete type starting at {@code start} */ - static int typeEnd(String signature, int start) { - char c = signature.charAt(start); - if (c == 'a') return typeEnd(signature, start + 1); - if (c == '(' || c == '{') { - char close = c == '(' ? ')' : '}'; - int i = start + 1; - while (signature.charAt(i) != close) i = typeEnd(signature, i); - return i + 1; - } - return start + 1; - } - - static int alignment(char type) { - return switch (type) { - case 'y', 'g', 'v' -> 1; - case 'n', 'q' -> 2; - case 'x', 't', 'd', '(', '{' -> 8; - default -> 4; - }; - } - - /** Marshals values; positions count from the start of what it writes. */ - static final class Writer { - private byte[] buf = new byte[256]; - private int pos; - - int size() { - return pos; - } - - byte[] toBytes() { - return Arrays.copyOf(buf, pos); - } - - void put(int b) { - if (pos == buf.length) buf = Arrays.copyOf(buf, buf.length * 2); - buf[pos++] = (byte) b; - } - - void bytes(byte[] b) { - for (byte x : b) put(x); - } - - void align(int n) { - while (pos % n != 0) put(0); - } - - void u32(long v) { - align(4); - for (int i = 0; i < 4; i++) put((int) (v >>> (8 * i))); - } - - private void setU32(int at, long v) { - for (int i = 0; i < 4; i++) buf[at + i] = (byte) (v >>> (8 * i)); - } - - void string(String s) { - byte[] b = s.getBytes(StandardCharsets.UTF_8); - u32(b.length); - bytes(b); - put(0); - } - - void signature(String s) { - byte[] b = s.getBytes(StandardCharsets.US_ASCII); - put(b.length); - bytes(b); - put(0); - } - - /** An array; the length leaves out the padding before its first element. */ - void array(int elementAlignment, Runnable elements) { - u32(0); - int lengthAt = pos - 4; - align(elementAlignment); - int start = pos; - elements.run(); - setU32(lengthAt, pos - start); - } - - void field(int code, String signature, Object value) { - align(8); - put(code); - signature(signature); - value(signature, value); - } - - void values(String signature, Object... values) { - int v = 0; - for (int i = 0; i < signature.length(); v++) { - int next = typeEnd(signature, i); - value(signature.substring(i, next), values[v]); - i = next; - } - } - - void value(String type, Object value) { - char c = type.charAt(0); - align(alignment(c)); - switch (c) { - case 'y' -> put(((Number) value).intValue()); - case 'b' -> u32((Boolean) value ? 1 : 0); - case 'i' -> u32(((Number) value).intValue() & 0xffffffffL); - case 'u' -> u32(((Number) value).longValue()); - case 's', 'o' -> string((String) value); - case 'g' -> signature((String) value); - case 'v' -> { - String inner = variantType(value); - signature(inner); - value(inner, value); - } - case 'a' -> { - String element = type.substring(1); - array(alignment(element.charAt(0)), () -> { - if (element.charAt(0) == '{') { - String key = element.substring(1, typeEnd(element, 1)); - String val = element.substring(1 + key.length(), element.length() - 1); - for (Map.Entry e : ((Map) value).entrySet()) { - align(8); - value(key, e.getKey()); - value(val, e.getValue()); - } - } else { - for (Object item : (List) value) value(element, item); - } - }); - } - default -> throw new IllegalArgumentException("Cannot write D-Bus type " + type); - } - } - - private static String variantType(Object value) { - if (value instanceof String) return "s"; - if (value instanceof Boolean) return "b"; - if (value instanceof Byte) return "y"; - if (value instanceof Integer) return "i"; - if (value instanceof Long) return "u"; - throw new IllegalArgumentException("No D-Bus type for " + value.getClass()); - } - } - - /** Unmarshals values; alignment counts from the start of the message. */ - static final class Reader { - final ByteBuffer buf; - - Reader(ByteBuffer buf) { - this.buf = buf; - } - - void skip(int n) { - buf.position(buf.position() + n); - } - - void align(int n) { - int p = buf.position(); - buf.position((p + n - 1) / n * n); - } - - Object read(String type) { - char c = type.charAt(0); - align(alignment(c)); - return switch (c) { - case 'y' -> buf.get() & 0xff; - case 'b' -> buf.getInt() != 0; - case 'n' -> (int) buf.getShort(); - case 'q' -> buf.getShort() & 0xffff; - case 'i' -> buf.getInt(); - case 'u' -> Integer.toUnsignedLong(buf.getInt()); - case 'x', 't' -> buf.getLong(); - case 'd' -> buf.getDouble(); - case 's', 'o' -> text(buf.getInt()); - case 'g' -> text(buf.get() & 0xff); - case 'v' -> read((String) read("g")); - case 'a' -> { - int length = buf.getInt(); - String element = type.substring(1, typeEnd(type, 1)); - align(alignment(element.charAt(0))); - int end = buf.position() + length; - List items = new ArrayList<>(); - while (buf.position() < end) items.add(read(element)); - yield items; - } - case '(', '{' -> { - List members = new ArrayList<>(); - for (int i = 1; i < type.length() - 1; ) { - int next = typeEnd(type, i); - members.add(read(type.substring(i, next))); - i = next; - } - yield members.toArray(); - } - default -> throw new IllegalArgumentException("Cannot read D-Bus type " + type); - }; - } - - private String text(int length) { - byte[] b = new byte[length]; - buf.get(b); - buf.get(); // the terminating NUL - return new String(b, StandardCharsets.UTF_8); - } - } -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/notify/desktop/DesktopNotifications.java b/ts3-client/desktop/src/main/java/com/ts3client/notify/desktop/DesktopNotifications.java deleted file mode 100644 index 1526e01..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/notify/desktop/DesktopNotifications.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.ts3client.notify.desktop; - -import java.util.function.Consumer; - -/** - * The desktop's own notifications — the ones its notification centre collects. Calls - * may block on the desktop, so they belong off the event thread; the callbacks come - * on a thread of the implementation's. - */ -public interface DesktopNotifications { - - /** - * @param title the headline, such as who a message is from - * @param body plain text - * @param onOpen run when the user clicks the notification - * @param onReply given the text typed into the notification, where {@link #canReply()}; may be {@code null} - */ - record Notice(String title, String body, Runnable onOpen, Consumer onReply) { - } - - /** - * Shows a notice, in place of an earlier one still on screen. - * - * @param replaces what an earlier call returned, or 0 - * @return the notice's id for {@link #close} and later replacement, or 0 if it could not be shown - */ - int show(Notice notice, int replaces); - - /** Takes a notice away, from the notification centre too. */ - void close(int id); - - /** Whether a notice can take a reply typed into it. */ - boolean canReply(); - - void shutdown(); -} diff --git a/ts3-client/desktop/src/main/java/com/ts3client/notify/desktop/FreedesktopNotifications.java b/ts3-client/desktop/src/main/java/com/ts3client/notify/desktop/FreedesktopNotifications.java deleted file mode 100644 index 751538a..0000000 --- a/ts3-client/desktop/src/main/java/com/ts3client/notify/desktop/FreedesktopNotifications.java +++ /dev/null @@ -1,126 +0,0 @@ -package com.ts3client.notify.desktop; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Notifications through the freedesktop.org notification service, which every Linux - * desktop (Plasma, GNOME, XFCE, a standalone daemon such as dunst) provides on the - * session bus. Plasma also takes a reply typed into the notification. - */ -public final class FreedesktopNotifications implements DesktopNotifications { - - private static final String SERVICE = "org.freedesktop.Notifications"; - private static final String PATH = "/org/freedesktop/Notifications"; - private static final String DEFAULT_ACTION = "default"; - /** Plasma's extension for a reply field in the notification. */ - private static final String REPLY_ACTION = "inline-reply"; - - private final DBusConnection bus; - private final String appName; - private final String desktopEntry; - private final String icon; - private final boolean markup; - private final boolean reply; - /** The notices on screen, by the id the service gave them. */ - private final Map shown = new ConcurrentHashMap<>(); - - /** - * @param desktopEntry the name of the application's {@code .desktop} file, without the - * extension; the desktop takes the application's name and icon from it - * @param icon an icon file, for services that do not look at the desktop entry - * @return the service, or {@code null} where there is none to reach - */ - public static FreedesktopNotifications connect(String appName, String desktopEntry, String icon) { - DBusConnection bus = null; - try { - bus = DBusConnection.session(); - List capabilities = (List) bus.call(SERVICE, PATH, SERVICE, "GetCapabilities", "").getFirst(); - bus.addMatch("type='signal',interface='" + SERVICE + "'"); - return new FreedesktopNotifications(bus, appName, desktopEntry, icon, capabilities); - } catch (IOException | RuntimeException e) { - System.err.println("Desktop notifications unavailable: " + e.getMessage()); - if (bus != null) bus.close(); - return null; - } - } - - private FreedesktopNotifications(DBusConnection bus, String appName, String desktopEntry, String icon, - List capabilities) { - this.bus = bus; - this.appName = appName; - this.desktopEntry = desktopEntry; - this.icon = icon == null ? "" : icon; - this.markup = capabilities.contains("body-markup"); - this.reply = capabilities.contains(REPLY_ACTION); - bus.onSignal(this::signal); - } - - @Override - public boolean canReply() { - return reply; - } - - @Override - public int show(Notice notice, int replaces) { - List actions = new ArrayList<>(List.of(DEFAULT_ACTION, "Open")); - if (reply && notice.onReply() != null) actions.addAll(List.of(REPLY_ACTION, "Reply")); - Map hints = new LinkedHashMap<>(); - hints.put("desktop-entry", desktopEntry); - hints.put("category", "im.received"); - // The client plays the sound pack's own sound for whatever it notifies of. - hints.put("suppress-sound", true); - try { - long id = (Long) bus.call(SERVICE, PATH, SERVICE, "Notify", "susssasa{sv}i", - appName, (long) replaces, icon, notice.title(), - markup ? escape(notice.body()) : notice.body(), actions, hints, -1).getFirst(); - shown.remove((long) replaces); - shown.put(id, notice); - return (int) id; - } catch (IOException | RuntimeException e) { - System.err.println("Cannot show a notification: " + e.getMessage()); - return 0; - } - } - - @Override - public void close(int id) { - if (shown.remove((long) id) == null) return; - try { - bus.call(SERVICE, PATH, SERVICE, "CloseNotification", "u", (long) id); - } catch (IOException e) { - // Gone with the service; nothing to take away. - } - } - - @Override - public void shutdown() { - for (Long id : List.copyOf(shown.keySet())) close(id.intValue()); - bus.close(); - } - - private void signal(String iface, String member, List args) { - if (!SERVICE.equals(iface) || args.isEmpty() || !(args.getFirst() instanceof Long id)) return; - switch (member) { - case "ActionInvoked" -> { - Notice notice = shown.get(id); - if (notice != null && DEFAULT_ACTION.equals(args.get(1))) notice.onOpen().run(); - } - case "NotificationReplied" -> { - Notice notice = shown.get(id); - if (notice != null && notice.onReply() != null) notice.onReply().accept((String) args.get(1)); - } - case "NotificationClosed" -> shown.remove(id); - default -> { } - } - } - - /** The body is markup where the service says so; message text must not turn into any. */ - private static String escape(String text) { - return text.replace("&", "&").replace("<", "<").replace(">", ">"); - } -} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/AudioDevices.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/AudioDevices.java new file mode 100644 index 0000000..0c80306 --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/AudioDevices.java @@ -0,0 +1,210 @@ +package eu.lixko.ts3j.client.audio.desktop; + +import eu.lixko.ts3j.client.audio.AudioCapture; +import eu.lixko.ts3j.client.audio.AudioDevice; +import eu.lixko.ts3j.client.audio.AudioIo; +import eu.lixko.ts3j.client.audio.AudioPlayback; +import eu.lixko.ts3j.client.audio.VoiceFormat; +import eu.lixko.ts3j.client.audio.desktop.pipewire.PipeWire; + +import javax.sound.sampled.AudioFormat; +import javax.sound.sampled.AudioSystem; +import javax.sound.sampled.DataLine; +import javax.sound.sampled.Line; +import javax.sound.sampled.LineUnavailableException; +import javax.sound.sampled.Mixer; +import javax.sound.sampled.SourceDataLine; +import javax.sound.sampled.TargetDataLine; +import java.util.ArrayList; +import java.util.List; + +/** + * Enumerates audio devices and opens capture/playback lines on them. + * + *

    The TS3 protocol uses 48 kHz 16-bit signed little-endian PCM for Opus, mono for + * {@code OPUS_VOICE} and stereo for {@code OPUS_MUSIC}, so the channel count is + * negotiated per line rather than fixed. + * + *

    Two backends sit behind {@link AudioCapture} / {@link AudioPlayback}: + *

      + *
    • {@link PipeWire} — used for the system default and for every {@code pw:} device + * when a PipeWire session is reachable. It sees the graph's real devices and each + * stream shows up separately in volume mixers.
    • + *
    • Java Sound — everywhere else, and for the raw ALSA devices which stay in the + * list because they still work without PipeWire and can be opened exclusively.
    • + *
    + * + *

    Java Sound enumeration deliberately asks only for "a mixer that can do + * capture/playback" instead of "a mixer that can do exactly this format": the PipeWire + * and PulseAudio ALSA plugins advertise a narrow set of formats (typically stereo only), + * so a format-specific query hides them entirely. The desired format is negotiated in + * {@link #openCapture} / {@link #openPlayback}, which fall back through the supported + * channel counts. + */ +public final class AudioDevices implements AudioIo { + + public static final AudioDevices INSTANCE = new AudioDevices(); + + /** Buffer size, in 20 ms frames, requested when opening a Java Sound line. */ + private static final int BUFFER_FRAMES = 8; + + /** Marks a device id as a PipeWire node name rather than a Java Sound mixer name. */ + private static final String PIPEWIRE_PREFIX = "pw:"; + + private AudioDevices() { + } + + /** 48 kHz signed 16-bit little-endian PCM with the given channel count. */ + public static AudioFormat format(int channels) { + return new AudioFormat(VoiceFormat.SAMPLE_RATE, 16, channels, true, false); + } + + @Override + public List inputDevices() { + return devices(TargetDataLine.class, false); + } + + @Override + public List outputDevices() { + return devices(SourceDataLine.class, true); + } + + private static List devices(Class lineClass, boolean sinks) { + List devices = new ArrayList<>(); + devices.add(AudioDevice.DEFAULT); + + for (PipeWire.Node node : PipeWire.nodes()) { + if (node.sink() == sinks) { + devices.add(new AudioDevice(PIPEWIRE_PREFIX + node.name(), node.description())); + } + } + + Line.Info anyFormat = new Line.Info(lineClass); + for (Mixer.Info mi : AudioSystem.getMixerInfo()) { + String name = mi.getName(); + if (name == null || name.isEmpty()) continue; + // The ALSA "default" PCM is what the system-default entry already opens. + if (isDefaultMixer(name)) continue; + if (!AudioSystem.getMixer(mi).isLineSupported(anyFormat)) continue; + if (devices.stream().anyMatch(d -> d.id().equals(name))) continue; + devices.add(new AudioDevice(name, "ALSA: " + name)); + } + return devices; + } + + /** + * Java Sound names its ALSA {@code default} mixer after the PCM it opened, which under + * pipewire-alsa is our own stream node (e.g. {@code alsa_playback.java [default]}), so + * only the bracketed device part is stable. + */ + private static boolean isDefaultMixer(String mixerName) { + return mixerName.endsWith("[default]"); + } + + @Override + public AudioCapture openCapture(String deviceId, int preferredChannels) + throws LineUnavailableException { + if (usePipeWire(deviceId)) { + try { + return PipeWire.openCapture("TeamSpook TS3j Microphone", pipeWireNode(deviceId), + VoiceFormat.SAMPLE_RATE, clampChannels(preferredChannels)); + } catch (Exception e) { + if (isPipeWireDevice(deviceId)) throw unavailable(true, deviceId, e); + // The default device: Java Sound may still reach it through ALSA. + } + } + return new JavaSoundCapture(open(TargetDataLine.class, deviceId, preferredChannels)); + } + + @Override + public AudioPlayback openPlayback(String deviceId, int preferredChannels) + throws LineUnavailableException { + if (usePipeWire(deviceId)) { + try { + return PipeWire.openPlayback("TeamSpook TS3j Playback", pipeWireNode(deviceId), + VoiceFormat.SAMPLE_RATE, clampChannels(preferredChannels)); + } catch (Exception e) { + if (isPipeWireDevice(deviceId)) throw unavailable(false, deviceId, e); + } + } + return new JavaSoundPlayback(open(SourceDataLine.class, deviceId, preferredChannels)); + } + + /** + * PipeWire handles its own devices and, when a session is running, the system default + * too — a Java Sound "default" would only reach the same graph through the ALSA + * compatibility plugin, with no way to pick the device. + */ + private static boolean usePipeWire(String deviceId) { + if (!isPipeWireDevice(deviceId) && !isDefault(deviceId)) return false; + return PipeWire.isAvailable(); + } + + private static boolean isDefault(String deviceId) { + return deviceId == null || deviceId.isEmpty(); + } + + private static boolean isPipeWireDevice(String deviceId) { + return deviceId != null && deviceId.startsWith(PIPEWIRE_PREFIX); + } + + /** The PipeWire node name behind a device id; empty for "let the server choose". */ + private static String pipeWireNode(String deviceId) { + return isPipeWireDevice(deviceId) ? deviceId.substring(PIPEWIRE_PREFIX.length()) : ""; + } + + /** PipeWire converts freely, so any channel count works; keep it in the range we handle. */ + private static int clampChannels(int channels) { + return Math.max(1, Math.min(VoiceFormat.MAX_CHANNELS, channels)); + } + + private static T open(Class lineClass, String deviceId, int preferredChannels) + throws LineUnavailableException { + Mixer mixer = findMixer(deviceId, lineClass); // null -> platform default + Exception failure = null; + for (int channels : channelOrder(preferredChannels)) { + AudioFormat fmt = format(channels); + DataLine.Info info = new DataLine.Info(lineClass, fmt); + try { + T line = lineClass.cast( + (mixer != null) ? mixer.getLine(info) : AudioSystem.getLine(info)); + openLine(line, fmt, VoiceFormat.FRAME_SIZE * 2 * fmt.getChannels() * BUFFER_FRAMES); + return line; + } catch (Exception e) { + failure = e; + } + } + throw unavailable(lineClass == TargetDataLine.class, deviceId, failure); + } + + private static LineUnavailableException unavailable(boolean capture, String deviceId, + Exception failure) { + LineUnavailableException e = new LineUnavailableException( + "No usable " + (capture ? "capture" : "playback") + " line for " + + (isDefault(deviceId) ? "the system default" : deviceId)); + if (failure != null) e.initCause(failure); + return e; + } + + /** {@code open(format, bufferSize)} lives on the two line interfaces, not on {@code DataLine}. */ + private static void openLine(DataLine line, AudioFormat fmt, int bufferSize) + throws LineUnavailableException { + if (line instanceof TargetDataLine target) target.open(fmt, bufferSize); + else ((SourceDataLine) line).open(fmt, bufferSize); + } + + private static int[] channelOrder(int preferred) { + return preferred >= 2 ? new int[]{2, 1} : new int[]{1, 2}; + } + + private static Mixer findMixer(String deviceId, Class lineClass) { + if (isDefault(deviceId) || isPipeWireDevice(deviceId)) return null; + Line.Info anyFormat = new Line.Info(lineClass); + for (Mixer.Info mi : AudioSystem.getMixerInfo()) { + if (!deviceId.equals(mi.getName())) continue; + Mixer mixer = AudioSystem.getMixer(mi); + if (mixer.isLineSupported(anyFormat)) return mixer; + } + return null; // device went away: fall back to the system default + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/DesktopAudioBackend.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/DesktopAudioBackend.java new file mode 100644 index 0000000..6929bec --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/DesktopAudioBackend.java @@ -0,0 +1,50 @@ +package eu.lixko.ts3j.client.audio.desktop; + +import eu.lixko.ts3j.client.audio.AudioBackend; +import eu.lixko.ts3j.client.audio.AudioIo; +import eu.lixko.ts3j.client.audio.StreamingVoiceOutput; +import eu.lixko.ts3j.client.audio.desktop.pipewire.PipeWire; +import eu.lixko.ts3j.client.audio.opus.OpusCodec; + +/** + * Desktop audio backend: PipeWire for capture/playback where it is running, Java Sound + * everywhere else, and native Opus (via the FFM API) for the codec. + */ +public final class DesktopAudioBackend implements AudioBackend { + + private final OpusCodec opus = new NativeOpusCodec(); + + @Override + public AudioIo io() { + return AudioDevices.INSTANCE; + } + + @Override + public OpusCodec opus() { + return opus; + } + + /** Every speaker gets a line of their own, so each shows up in the desktop's mixer. */ + @Override + public StreamingVoiceOutput.Lines outputLines() { + return StreamingVoiceOutput.Lines.PER_SPEAKER; + } + + @Override + public String description() { + return codec() + ", " + audioSystem(); + } + + private String codec() { + try { + return "Opus " + opus.version(); + } catch (Throwable t) { + return "Opus (native library unavailable)"; + } + } + + private static String audioSystem() { + String pipeWire = PipeWire.version(); + return pipeWire != null ? "PipeWire " + pipeWire : "Java Sound"; + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/EncodeSoundPacks.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/EncodeSoundPacks.java new file mode 100644 index 0000000..026ac11 --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/EncodeSoundPacks.java @@ -0,0 +1,26 @@ +package eu.lixko.ts3j.client.audio.desktop; + +import eu.lixko.ts3j.client.sound.SoundPackConverter; + +import java.io.File; +import java.io.IOException; + +/** + * Converts a folder of sound packs to Opus with the bundled libopus — the Android build + * ships TeamSpeak's packs this way. + * + *

    Usage: {@code EncodeSoundPacks } + */ +public final class EncodeSoundPacks { + + private EncodeSoundPacks() { + } + + public static void main(String[] args) throws IOException { + if (args.length != 2) { + System.err.println("Usage: EncodeSoundPacks "); + System.exit(2); + } + SoundPackConverter.convert(new File(args[0]), new File(args[1]), new NativeOpusCodec()); + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/JavaSoundCapture.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/JavaSoundCapture.java new file mode 100644 index 0000000..bd1111e --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/JavaSoundCapture.java @@ -0,0 +1,51 @@ +package eu.lixko.ts3j.client.audio.desktop; + +import eu.lixko.ts3j.client.audio.AudioCapture; + +import javax.sound.sampled.TargetDataLine; + +/** {@link AudioCapture} backed by a Java Sound {@link TargetDataLine}. */ +final class JavaSoundCapture implements AudioCapture { + + private final TargetDataLine line; + + JavaSoundCapture(TargetDataLine line) { + this.line = line; + } + + @Override + public int channels() { + return line.getFormat().getChannels(); + } + + @Override + public void start() { + line.start(); + } + + /** {@code TargetDataLine.read} may return early, so it is repeated until satisfied. */ + @Override + public int read(byte[] buffer, int offset, int length) { + int read = 0; + while (read < length) { + int n; + try { + n = line.read(buffer, offset + read, length - read); + } catch (Exception e) { + break; + } + if (n <= 0) break; + read += n; + } + return read; + } + + @Override + public void close() { + try { + line.stop(); + line.close(); + } catch (Exception ignored) { + } + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/JavaSoundPlayback.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/JavaSoundPlayback.java new file mode 100644 index 0000000..36421f4 --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/JavaSoundPlayback.java @@ -0,0 +1,53 @@ +package eu.lixko.ts3j.client.audio.desktop; + +import eu.lixko.ts3j.client.audio.AudioPlayback; + +import javax.sound.sampled.SourceDataLine; + +/** {@link AudioPlayback} backed by a Java Sound {@link SourceDataLine}. */ +final class JavaSoundPlayback implements AudioPlayback { + + private final SourceDataLine line; + + JavaSoundPlayback(SourceDataLine line) { + this.line = line; + } + + @Override + public int channels() { + return line.getFormat().getChannels(); + } + + @Override + public void start() { + line.start(); + } + + @Override + public void write(byte[] buffer, int offset, int length) { + int written; + try { + written = line.write(buffer, offset, length); + } catch (RuntimeException e) { + throw new IllegalStateException("The playback line failed", e); + } + if (written < length && !line.isOpen()) throw new IllegalStateException("The playback line closed"); + } + + @Override + public void drain() { + try { + line.drain(); + } catch (Exception ignored) { + } + } + + @Override + public void close() { + try { + line.stop(); + line.close(); + } catch (Exception ignored) { + } + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/NativeOpusCodec.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/NativeOpusCodec.java new file mode 100644 index 0000000..002475c --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/NativeOpusCodec.java @@ -0,0 +1,25 @@ +package eu.lixko.ts3j.client.audio.desktop; + +import eu.lixko.ts3j.client.audio.opus.LibOpus; +import eu.lixko.ts3j.client.audio.opus.OpusCodec; +import eu.lixko.ts3j.client.audio.opus.OpusDecoder; +import eu.lixko.ts3j.client.audio.opus.OpusEncoder; + +/** The system's (or the bundled) libopus, reached through the FFM API. */ +public final class NativeOpusCodec implements OpusCodec { + + @Override + public OpusEncoder createEncoder(int sampleRate, int frameSize, int channels, Application application) { + return new NativeOpusEncoder(sampleRate, frameSize, channels, LibOpus.application(application)); + } + + @Override + public OpusDecoder createDecoder(int sampleRate, int maxFrameSize, int channels) { + return new NativeOpusDecoder(sampleRate, maxFrameSize, channels); + } + + @Override + public String version() { + return Opus.getVersionString(); + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/NativeOpusDecoder.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/NativeOpusDecoder.java new file mode 100644 index 0000000..952ed84 --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/NativeOpusDecoder.java @@ -0,0 +1,97 @@ +package eu.lixko.ts3j.client.audio.desktop; + +import eu.lixko.ts3j.client.audio.opus.LibOpus; +import eu.lixko.ts3j.client.audio.opus.OpusDecoder; + +import java.lang.foreign.Arena; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.ValueLayout; + +/** + * Thin wrapper around a native Opus decoder. + * + *

    Fixed at 48 kHz. The channel count should match the stream being decoded + * (mono for {@code OPUS_VOICE}, stereo for {@code OPUS_MUSIC}); Opus will up-/down-mix + * a mismatched stream, which costs the stereo image. + */ +final class NativeOpusDecoder implements OpusDecoder { + + private static final int MAX_PACKET_BYTES = 4096; + + private final Arena arena = Arena.ofShared(); + private final MemorySegment handle; + private final MemorySegment packetBuffer; + private final MemorySegment pcmBuffer; + private final int frameSize; + private final int channels; + private boolean closed; + + NativeOpusDecoder(int sampleRate, int frameSize, int channels) { + this.frameSize = frameSize; + this.channels = channels; + + MemorySegment error = arena.allocate(ValueLayout.JAVA_INT); + MemorySegment created = Opus.decoderCreate(sampleRate, channels, error); + int errorCode = error.get(ValueLayout.JAVA_INT, 0); + if (created.address() == 0 || errorCode != 0) { + arena.close(); + throw new IllegalStateException("opus_decoder_create failed: " + Opus.strerror(errorCode)); + } + + this.handle = created; + this.packetBuffer = arena.allocate(MAX_PACKET_BYTES); + this.pcmBuffer = arena.allocate(ValueLayout.JAVA_FLOAT, (long) frameSize * channels); + } + + /** + * @param packet an Opus packet, at most {@value #MAX_PACKET_BYTES} bytes + * @param out output buffer, at least {@code frameSize * channels} long + * @return number of samples decoded per channel + */ + @Override + public int decode(byte[] packet, float[] out) { + if (packet.length > MAX_PACKET_BYTES) { + throw new IllegalArgumentException("packet too large: " + packet.length); + } + MemorySegment.copy(packet, 0, packetBuffer, ValueLayout.JAVA_BYTE, 0, packet.length); + return decode(packetBuffer, packet.length, out, frameSize, 0); + } + + @Override + public int conceal(float[] out, int frameSize) { + return decode(MemorySegment.NULL, 0, out, Math.min(frameSize, this.frameSize), 0); + } + + @Override + public int recover(byte[] next, float[] out, int frameSize) { + if (next.length > MAX_PACKET_BYTES) { + throw new IllegalArgumentException("packet too large: " + next.length); + } + MemorySegment.copy(next, 0, packetBuffer, ValueLayout.JAVA_BYTE, 0, next.length); + return decode(packetBuffer, next.length, out, Math.min(frameSize, this.frameSize), 1); + } + + private int decode(MemorySegment data, int len, float[] out, int maxSamples, int fec) { + if (closed) throw new IllegalStateException("decoder closed"); + int samples = Opus.decodeFloat(handle, data, len, pcmBuffer, maxSamples, fec); + if (samples < 0) { + throw new IllegalStateException("opus_decode_float failed: " + Opus.strerror(samples)); + } + MemorySegment.copy(pcmBuffer, ValueLayout.JAVA_FLOAT, 0, out, 0, samples * channels); + return samples; + } + + @Override + public void reset() { + if (closed) return; + Opus.decoderCtl(handle, LibOpus.RESET_STATE, 0); + } + + @Override + public void close() { + if (closed) return; + closed = true; + Opus.decoderDestroy(handle); + arena.close(); + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/NativeOpusEncoder.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/NativeOpusEncoder.java new file mode 100644 index 0000000..0f016f8 --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/NativeOpusEncoder.java @@ -0,0 +1,95 @@ +package eu.lixko.ts3j.client.audio.desktop; + +import eu.lixko.ts3j.client.audio.opus.CtlOpusEncoder; + +import java.lang.foreign.Arena; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.ValueLayout; + +/** + * Thin wrapper around a native Opus encoder configured for TeamSpeak voice. + * + *

    Fixed at 48 kHz. Frames are 20 ms (960 samples per channel), which + * is the frame size the TS3 client uses. + * + *

    The native scratch buffers live in a shared arena owned by this instance and + * are freed by {@link #close()}; access is serialised by the instance lock, so the + * encoder may be driven from any thread. + */ +final class NativeOpusEncoder extends CtlOpusEncoder { + + private static final int MAX_PACKET_BYTES = 4096; + + private final Arena arena = Arena.ofShared(); + private final MemorySegment handle; + private final MemorySegment pcmBuffer; + private final MemorySegment packetBuffer; + private final int frameSize; + private final int channels; + private final Object lock = new Object(); + private boolean closed; + + NativeOpusEncoder(int sampleRate, int frameSize, int channels, int application) { + this.frameSize = frameSize; + this.channels = channels; + + MemorySegment error = arena.allocate(ValueLayout.JAVA_INT); + MemorySegment created = Opus.encoderCreate(sampleRate, channels, application, error); + int errorCode = error.get(ValueLayout.JAVA_INT, 0); + if (created.address() == 0 || errorCode != 0) { + arena.close(); + throw new IllegalStateException("opus_encoder_create failed: " + Opus.strerror(errorCode)); + } + + this.handle = created; + this.pcmBuffer = arena.allocate(ValueLayout.JAVA_FLOAT, (long) frameSize * channels); + this.packetBuffer = arena.allocate(MAX_PACKET_BYTES); + } + + @Override + protected void ctl(int request, int value) { + synchronized (lock) { + if (closed) return; + int r = Opus.encoderCtl(handle, request, value); + if (r < 0) { + throw new IllegalStateException("opus_encoder_ctl(" + request + ") failed: " + + Opus.strerror(r)); + } + } + } + + /** + * Encodes one frame of interleaved float PCM ({@code frameSize * channels} samples) + * into an Opus packet. + * + * @return a newly allocated byte array holding the encoded packet + */ + @Override + public byte[] encode(float[] pcm) { + int expected = frameSize * channels; + if (pcm.length != expected) { + throw new IllegalArgumentException("expected " + expected + " samples, got " + pcm.length); + } + synchronized (lock) { + if (closed) throw new IllegalStateException("encoder closed"); + MemorySegment.copy(pcm, 0, pcmBuffer, ValueLayout.JAVA_FLOAT, 0, expected); + int len = Opus.encodeFloat(handle, pcmBuffer, frameSize, packetBuffer, MAX_PACKET_BYTES); + if (len < 0) { + throw new IllegalStateException("opus_encode_float failed: " + Opus.strerror(len)); + } + byte[] packet = new byte[len]; + MemorySegment.copy(packetBuffer, ValueLayout.JAVA_BYTE, 0, packet, 0, len); + return packet; + } + } + + @Override + public void close() { + synchronized (lock) { + if (closed) return; + closed = true; + Opus.encoderDestroy(handle); + arena.close(); + } + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/Opus.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/Opus.java new file mode 100644 index 0000000..777c010 --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/Opus.java @@ -0,0 +1,264 @@ +package eu.lixko.ts3j.client.audio.desktop; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.foreign.Arena; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.Linker; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.SymbolLookup; +import java.lang.foreign.ValueLayout; +import java.lang.invoke.MethodHandle; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.List; + +/** + * Binding to the native Opus codec library (libopus) via the Foreign Function & + * Memory API (project Panama). + * + *

    The library is resolved by first trying the system-installed {@code libopus} + * under its usual SONAMEs; failing that, the copy we bundle on the classpath for + * the running platform (e.g. {@code linux-x86-64/libopus.so}, {@code win32-x86-64/opus.dll}) + * is extracted to a temporary file and loaded, so the client runs from the single + * JAR with no external Opus install. Opus always operates internally at 48 kHz + * which matches what the TeamSpeak 3 protocol uses on the wire. + */ +public final class Opus { + + private Opus() { + } + + private static final ValueLayout.OfInt INT = ValueLayout.JAVA_INT; + private static final java.lang.foreign.AddressLayout PTR = ValueLayout.ADDRESS; + + private static final Linker LINKER = Linker.nativeLinker(); + private static final SymbolLookup LOOKUP = NativeLibraries.loadOpus(); + + // OpusEncoder *opus_encoder_create(opus_int32 fs, int channels, int application, int *error) + private static final MethodHandle ENCODER_CREATE = + downcall("opus_encoder_create", FunctionDescriptor.of(PTR, INT, INT, INT, PTR)); + // opus_int32 opus_encode_float(OpusEncoder *st, const float *pcm, int frame_size, + // unsigned char *data, opus_int32 max_data_bytes) + private static final MethodHandle ENCODE_FLOAT = + downcall("opus_encode_float", FunctionDescriptor.of(INT, PTR, PTR, INT, PTR, INT)); + private static final MethodHandle ENCODER_DESTROY = + downcall("opus_encoder_destroy", FunctionDescriptor.ofVoid(PTR)); + + // OpusDecoder *opus_decoder_create(opus_int32 fs, int channels, int *error) + private static final MethodHandle DECODER_CREATE = + downcall("opus_decoder_create", FunctionDescriptor.of(PTR, INT, INT, PTR)); + // int opus_decode_float(OpusDecoder *st, const unsigned char *data, opus_int32 len, + // float *pcm, int frame_size, int decode_fec) + private static final MethodHandle DECODE_FLOAT = + downcall("opus_decode_float", FunctionDescriptor.of(INT, PTR, PTR, INT, PTR, INT, INT)); + private static final MethodHandle DECODER_DESTROY = + downcall("opus_decoder_destroy", FunctionDescriptor.ofVoid(PTR)); + + private static final MethodHandle STRERROR = + downcall("opus_strerror", FunctionDescriptor.of(PTR, INT)); + private static final MethodHandle GET_VERSION_STRING = + downcall("opus_get_version_string", FunctionDescriptor.of(PTR)); + + // int opus_encoder_ctl(OpusEncoder *st, int request, ...) — the value argument is + // variadic, so the linker must be told where the variadic part starts (index 2). + private static final MethodHandle ENCODER_CTL_SET = variadicCtl("opus_encoder_ctl"); + private static final MethodHandle DECODER_CTL_SET = variadicCtl("opus_decoder_ctl"); + + private static MethodHandle downcall(String symbol, FunctionDescriptor descriptor) { + return LINKER.downcallHandle(find(symbol), descriptor); + } + + private static MethodHandle variadicCtl(String symbol) { + return LINKER.downcallHandle( + find(symbol), + FunctionDescriptor.of(INT, PTR, INT, INT), + Linker.Option.firstVariadicArg(2)); + } + + private static MemorySegment find(String symbol) { + return LOOKUP.find(symbol) + .orElseThrow(() -> new UnsatisfiedLinkError("libopus: unresolved symbol " + symbol)); + } + + static MemorySegment encoderCreate(int sampleRate, int channels, int application, MemorySegment error) { + try { + return (MemorySegment) ENCODER_CREATE.invokeExact(sampleRate, channels, application, error); + } catch (Throwable t) { + throw wrap(t); + } + } + + static int encodeFloat(MemorySegment st, MemorySegment pcm, int frameSize, + MemorySegment data, int maxDataBytes) { + try { + return (int) ENCODE_FLOAT.invokeExact(st, pcm, frameSize, data, maxDataBytes); + } catch (Throwable t) { + throw wrap(t); + } + } + + static void encoderDestroy(MemorySegment st) { + try { + ENCODER_DESTROY.invokeExact(st); + } catch (Throwable t) { + throw wrap(t); + } + } + + static int encoderCtl(MemorySegment st, int request, int value) { + try { + return (int) ENCODER_CTL_SET.invokeExact(st, request, value); + } catch (Throwable t) { + throw wrap(t); + } + } + + static MemorySegment decoderCreate(int sampleRate, int channels, MemorySegment error) { + try { + return (MemorySegment) DECODER_CREATE.invokeExact(sampleRate, channels, error); + } catch (Throwable t) { + throw wrap(t); + } + } + + static int decodeFloat(MemorySegment st, MemorySegment data, int len, + MemorySegment pcm, int frameSize, int decodeFec) { + try { + return (int) DECODE_FLOAT.invokeExact(st, data, len, pcm, frameSize, decodeFec); + } catch (Throwable t) { + throw wrap(t); + } + } + + static void decoderDestroy(MemorySegment st) { + try { + DECODER_DESTROY.invokeExact(st); + } catch (Throwable t) { + throw wrap(t); + } + } + + static int decoderCtl(MemorySegment st, int request, int value) { + try { + return (int) DECODER_CTL_SET.invokeExact(st, request, value); + } catch (Throwable t) { + throw wrap(t); + } + } + + /** Human-readable message for an Opus error code. */ + public static String strerror(int error) { + try { + MemorySegment message = (MemorySegment) STRERROR.invokeExact(error); + return cString(message); + } catch (Throwable t) { + throw wrap(t); + } + } + + /** Version string of the loaded libopus, e.g. {@code libopus 1.4}. */ + public static String getVersionString() { + try { + MemorySegment version = (MemorySegment) GET_VERSION_STRING.invokeExact(); + return cString(version); + } catch (Throwable t) { + throw wrap(t); + } + } + + /** Reads a NUL-terminated C string from a zero-length (unbounded) return segment. */ + private static String cString(MemorySegment segment) { + if (segment.address() == 0) { + return null; + } + return segment.reinterpret(Long.MAX_VALUE).getString(0); + } + + private static RuntimeException wrap(Throwable t) { + if (t instanceof RuntimeException re) { + return re; + } + if (t instanceof Error e) { + throw e; + } + return new IllegalStateException("libopus call failed", t); + } + + /** + * Resolves libopus: system install first, bundled classpath copy second. + */ + private static final class NativeLibraries { + + static SymbolLookup loadOpus() { + Arena arena = Arena.global(); + for (String name : candidateNames()) { + try { + return SymbolLookup.libraryLookup(name, arena); + } catch (IllegalArgumentException ignored) { + // not present under this name; try the next one + } + } + return SymbolLookup.libraryLookup(extractBundled(), arena); + } + + /** SONAMEs/filenames a system-installed libopus may carry, in preference order. */ + private static List candidateNames() { + String os = System.getProperty("os.name", "").toLowerCase(); + if (os.contains("win")) { + return List.of("opus.dll", "libopus-0.dll", "libopus.dll"); + } + if (os.contains("mac") || os.contains("darwin")) { + return List.of("libopus.dylib", "libopus.0.dylib"); + } + return List.of("libopus.so.0", "libopus.so"); + } + + private static Path extractBundled() { + String libraryName = System.mapLibraryName("opus"); + for (String directory : platformDirectories()) { + String resource = directory + "/" + libraryName; + try (InputStream in = Opus.class.getClassLoader().getResourceAsStream(resource)) { + if (in == null) { + continue; + } + Path dir = Files.createTempDirectory("ts3-client-opus"); + dir.toFile().deleteOnExit(); + Path file = dir.resolve(libraryName); + Files.copy(in, file, StandardCopyOption.REPLACE_EXISTING); + file.toFile().deleteOnExit(); + return file; + } catch (IOException e) { + throw new UnsatisfiedLinkError("failed to extract bundled libopus: " + e); + } + } + throw new UnsatisfiedLinkError("libopus not found on this system and no bundled copy for " + + platformDirectories()); + } + + /** + * Classpath directories that may hold the bundled native (JNA's platform layout), + * most specific first — macOS also ships an architecture-agnostic {@code darwin/}. + */ + private static List platformDirectories() { + String os = System.getProperty("os.name", "").toLowerCase(); + String arch = System.getProperty("os.arch", "").toLowerCase(); + + String normalizedArch = switch (arch) { + case "amd64", "x86_64" -> "x86-64"; + case "i386", "i486", "i586", "i686", "x86" -> "x86"; + case "aarch64", "arm64" -> "aarch64"; + default -> arch.startsWith("arm") ? "arm" : arch; + }; + + if (os.contains("win")) { + return List.of("win32-" + normalizedArch); + } + if (os.contains("mac") || os.contains("darwin")) { + return List.of("darwin-" + normalizedArch, "darwin"); + } + return List.of("linux-" + normalizedArch); + } + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PcmRing.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PcmRing.java new file mode 100644 index 0000000..6213926 --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PcmRing.java @@ -0,0 +1,141 @@ +package eu.lixko.ts3j.client.audio.desktop.pipewire; + +import java.lang.foreign.MemorySegment; + +/** + * Byte ring buffer between the application threads and PipeWire's loop thread. + * + *

    The stream callbacks must never block — a late buffer is a glitch for the whole + * graph — so the loop side ({@link #put}/{@link #take}) always returns immediately and + * absorbs the mismatch: a capture overrun drops the oldest audio, a playback underrun is + * reported as a short read and padded with silence by the caller. The application side + * ({@link #write}/{@link #read}) blocks instead, which is what {@code SourceDataLine} and + * {@code TargetDataLine} do and what the voice pipeline expects. + */ +final class PcmRing { + + private final byte[] data; + private final MemorySegment view; + private int start; // index of the oldest byte + private int count; // bytes currently held + private boolean closed; + + PcmRing(int capacity) { + this.data = new byte[capacity]; + this.view = MemorySegment.ofArray(data); + } + + int capacity() { + return data.length; + } + + synchronized int available() { + return count; + } + + synchronized void clear() { + start = 0; + count = 0; + notifyAll(); + } + + /** Unblocks every waiter; subsequent reads report end-of-stream and writes are dropped. */ + synchronized void close() { + closed = true; + notifyAll(); + } + + synchronized boolean isClosed() { + return closed; + } + + // ---- loop-thread side (never blocks) ---- + + /** Appends up to {@code length} bytes, dropping the oldest audio if that overruns. */ + synchronized void put(MemorySegment source, long offset, int length) { + if (closed) return; + int overflow = count + length - data.length; + if (overflow > 0) skip(overflow); + int copied = Math.min(length, data.length); + long from = offset + (length - copied); + int end = (start + count) % data.length; + int firstChunk = Math.min(copied, data.length - end); + MemorySegment.copy(source, from, view, end, firstChunk); + MemorySegment.copy(source, from + firstChunk, view, 0, copied - firstChunk); + count += copied; + notifyAll(); + } + + /** Removes up to {@code length} bytes into {@code destination}; returns how many. */ + synchronized int take(MemorySegment destination, long offset, int length) { + int copied = Math.min(length, count); + int firstChunk = Math.min(copied, data.length - start); + MemorySegment.copy(view, start, destination, offset, firstChunk); + MemorySegment.copy(view, 0, destination, offset + firstChunk, copied - firstChunk); + skip(copied); + notifyAll(); + return copied; + } + + // ---- application side (blocks) ---- + + /** + * Blocks until {@code length} bytes have been read, the ring is closed, or the calling + * thread is interrupted. Returns the number of bytes actually read. + */ + synchronized int read(byte[] destination, int offset, int length) { + MemorySegment target = MemorySegment.ofArray(destination); + int read = 0; + while (read < length) { + if (count == 0) { + if (closed || !await()) break; + continue; + } + read += take(target, offset + read, length - read); + } + return read; + } + + /** + * Blocks until {@code length} bytes have been queued, the ring is closed, or the + * calling thread is interrupted. Returns the number of bytes actually written. + */ + synchronized int write(byte[] source, int offset, int length) { + MemorySegment target = MemorySegment.ofArray(source); + int written = 0; + while (written < length && !closed) { + int free = data.length - count; + if (free == 0) { + if (!await()) break; + continue; + } + int chunk = Math.min(free, length - written); + put(target, offset + written, chunk); + written += chunk; + } + return written; + } + + /** Blocks until the ring has drained (or was closed / the wait was interrupted). */ + synchronized void drain() { + while (count > 0 && !closed) { + if (!await()) return; + } + } + + /** Waits for a state change; {@code false} when interrupted. */ + private boolean await() { + try { + wait(100); + return true; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + } + + private void skip(int bytes) { + start = (start + bytes) % data.length; + count -= bytes; + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWire.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWire.java new file mode 100644 index 0000000..8e60f44 --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWire.java @@ -0,0 +1,78 @@ +package eu.lixko.ts3j.client.audio.desktop.pipewire; + +import eu.lixko.ts3j.client.audio.AudioCapture; +import eu.lixko.ts3j.client.audio.AudioPlayback; + +import java.util.List; + +/** + * PipeWire audio backend. + * + *

    On a PipeWire desktop this replaces Java Sound entirely: devices are enumerated + * from the graph — with their real names, including Bluetooth and virtual devices, + * which Java Sound's ALSA-only provider never sees — and capture and playback run as + * ordinary {@code pw_stream}s that appear individually in volume mixers. + * + *

    Everything here is a no-op on a machine without PipeWire: {@link #isAvailable()} + * reports {@code false} and {@link eu.lixko.ts3j.client.audio.desktop.AudioDevices} falls back + * to Java Sound. + */ +public final class PipeWire { + + /** A selectable PipeWire device. {@code name} is the node name used to target it. */ + public record Node(String name, String description, boolean sink) { + } + + private PipeWire() { + } + + /** {@code true} when libpipewire loaded and a session is reachable. */ + public static boolean isAvailable() { + return PipeWireSession.get() != null; + } + + /** The version of the loaded libpipewire, or {@code null} when it is not available. */ + public static String version() { + if (!isAvailable()) return null; + try { + return PipeWireLibrary.libraryVersion(); + } catch (Throwable t) { + return null; + } + } + + /** The audio sinks and sources currently in the graph; empty without PipeWire. */ + public static List nodes() { + PipeWireSession session = PipeWireSession.get(); + if (session == null) return List.of(); + return session.nodes().stream() + .map(node -> new Node(node.name(), node.description(), node.sink())) + .toList(); + } + + /** + * Opens a capture stream on {@code targetNode} (empty or {@code null} for the default + * source). + * + * @throws IllegalStateException if PipeWire is unavailable or the stream is refused + */ + public static AudioCapture openCapture(String name, String targetNode, int rate, int channels) { + return new PipeWireCapture(session(), name, targetNode, rate, channels); + } + + /** + * Opens a playback stream on {@code targetNode} (empty or {@code null} for the default + * sink). + * + * @throws IllegalStateException if PipeWire is unavailable or the stream is refused + */ + public static AudioPlayback openPlayback(String name, String targetNode, int rate, int channels) { + return new PipeWirePlayback(session(), name, targetNode, rate, channels); + } + + private static PipeWireSession session() { + PipeWireSession session = PipeWireSession.get(); + if (session == null) throw new IllegalStateException("PipeWire is not available"); + return session; + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWireCapture.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWireCapture.java new file mode 100644 index 0000000..d700182 --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWireCapture.java @@ -0,0 +1,28 @@ +package eu.lixko.ts3j.client.audio.desktop.pipewire; + +import eu.lixko.ts3j.client.audio.AudioCapture; + +import java.lang.foreign.MemorySegment; + +import static eu.lixko.ts3j.client.audio.desktop.pipewire.PipeWireLibrary.INT; + +/** A PipeWire capture stream ({@code PW_DIRECTION_INPUT}). */ +final class PipeWireCapture extends PipeWireStream implements AudioCapture { + + PipeWireCapture(PipeWireSession session, String name, String targetNode, int rate, int channels) { + super(session, name, targetNode, rate, channels, true); + } + + /** Copies the valid part of the buffer — which need not start at zero — into the ring. */ + @Override + void process(MemorySegment header, MemorySegment audio, MemorySegment chunk, int maxSize) { + int offset = Math.min(chunk.get(INT, PipeWireLibrary.SPA_CHUNK_OFFSET), maxSize); + int size = Math.min(chunk.get(INT, PipeWireLibrary.SPA_CHUNK_SIZE), maxSize - offset); + if (size > 0) ring.put(audio, offset, size); + } + + @Override + public int read(byte[] buffer, int offset, int length) { + return ring.read(buffer, offset, length); + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWireLibrary.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWireLibrary.java new file mode 100644 index 0000000..1cdb83b --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWireLibrary.java @@ -0,0 +1,409 @@ +package eu.lixko.ts3j.client.audio.desktop.pipewire; + +import java.lang.foreign.AddressLayout; +import java.lang.foreign.Arena; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.Linker; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.SymbolLookup; +import java.lang.foreign.ValueLayout; +import java.lang.invoke.MethodHandle; + +/** + * Raw binding to {@code libpipewire-0.3} through the Foreign Function & Memory API. + * + *

    This class is the only place that knows about the C ABI: the exported entry points, + * the SPA/PipeWire constants, and the offsets of the few structures that are read or + * written directly. Everything above it works with Java types. + * + *

    Loading is lazy and failure is expected: on a machine without PipeWire (or without + * a session running) {@link #isAvailable()} returns {@code false} and the caller falls + * back to Java Sound. The class initialiser is what fails, so both the first + * {@link ExceptionInInitializerError} and the later {@link NoClassDefFoundError} are + * caught. + * + *

    Interface methods

    + * The registry API ({@code pw_core_get_registry}, {@code pw_registry_add_listener}, + * {@code pw_core_sync}, ...) is declared {@code static inline} in the headers. PipeWire + * only began exporting compiled copies of those helpers in 1.1; to work on older + * versions too they are instead called the way the inline code does, through the + * object's {@code spa_interface} method table — see {@link #interfaceMethod}. + * + *

    Constants and structure offsets below were taken from the pipewire 1.4 headers and + * are part of the frozen 0.3 ABI. + */ +final class PipeWireLibrary { + + private PipeWireLibrary() { + } + + static final AddressLayout PTR = ValueLayout.ADDRESS; + static final ValueLayout.OfInt INT = ValueLayout.JAVA_INT; + static final ValueLayout.OfLong LONG = ValueLayout.JAVA_LONG; + static final ValueLayout.OfBoolean BOOL = ValueLayout.JAVA_BOOLEAN; + + // ---- enum pw_direction ---- + static final int PW_DIRECTION_INPUT = 0; + static final int PW_DIRECTION_OUTPUT = 1; + + // ---- well-known object ids ---- + static final int PW_ID_CORE = 0; + static final int PW_ID_ANY = 0xFFFFFFFF; + + // ---- interface versions we ask for / implement ---- + static final int PW_VERSION_REGISTRY = 3; + static final int PW_VERSION_CORE_EVENTS = 1; + static final int PW_VERSION_REGISTRY_EVENTS = 0; + static final int PW_VERSION_STREAM_EVENTS = 2; + + // ---- enum pw_stream_flags ---- + static final int PW_STREAM_FLAG_AUTOCONNECT = 1 << 0; + static final int PW_STREAM_FLAG_INACTIVE = 1 << 1; + static final int PW_STREAM_FLAG_MAP_BUFFERS = 1 << 2; + + // ---- enum pw_stream_state ---- + static final int PW_STREAM_STATE_ERROR = -1; + static final int PW_STREAM_STATE_UNCONNECTED = 0; + static final int PW_STREAM_STATE_CONNECTING = 1; + static final int PW_STREAM_STATE_PAUSED = 2; + static final int PW_STREAM_STATE_STREAMING = 3; + + // ---- property keys (pipewire/keys.h) ---- + static final String KEY_APP_NAME = "application.name"; + static final String KEY_MEDIA_TYPE = "media.type"; + static final String KEY_MEDIA_CATEGORY = "media.category"; + static final String KEY_MEDIA_ROLE = "media.role"; + static final String KEY_MEDIA_CLASS = "media.class"; + static final String KEY_NODE_NAME = "node.name"; + static final String KEY_NODE_DESCRIPTION = "node.description"; + static final String KEY_NODE_NICK = "node.nick"; + static final String KEY_NODE_LATENCY = "node.latency"; + static final String KEY_NODE_RATE = "node.rate"; + static final String KEY_TARGET_OBJECT = "target.object"; + + static final String TYPE_INTERFACE_NODE = "PipeWire:Interface:Node"; + + // ---- struct offsets (x86-64/aarch64 LP64; all fields are naturally aligned) ---- + + /** {@code struct spa_interface { const char *type; uint32_t version; struct spa_callbacks cb; }} */ + private static final long SPA_INTERFACE_SIZE = 32; + private static final long SPA_INTERFACE_CB_FUNCS = 16; + private static final long SPA_INTERFACE_CB_DATA = 24; + + /** {@code struct spa_dict { uint32_t flags, n_items; const struct spa_dict_item *items; }} */ + static final long SPA_DICT_SIZE = 16; + static final long SPA_DICT_N_ITEMS = 4; + static final long SPA_DICT_ITEMS = 8; + + /** {@code struct spa_dict_item { const char *key, *value; }} */ + static final long SPA_DICT_ITEM_SIZE = 16; + static final long SPA_DICT_ITEM_VALUE = 8; + + /** {@code struct pw_buffer { struct spa_buffer *buffer; void *user_data; uint64_t size, requested, time; }} */ + static final long PW_BUFFER_BUFFER = 0; + static final long PW_BUFFER_SIZE = 16; + static final long PW_BUFFER_REQUESTED = 24; + static final long PW_BUFFER_SIZEOF = 40; + + /** {@code struct spa_buffer { uint32_t n_metas, n_datas; struct spa_meta *metas; struct spa_data *datas; }} */ + static final long SPA_BUFFER_N_DATAS = 4; + static final long SPA_BUFFER_DATAS = 16; + static final long SPA_BUFFER_SIZEOF = 24; + + /** + * {@code struct spa_data { uint32_t type, flags; int64_t fd; uint32_t mapoffset, maxsize; + * void *data; struct spa_chunk *chunk; }} + */ + static final long SPA_DATA_MAXSIZE = 20; + static final long SPA_DATA_DATA = 24; + static final long SPA_DATA_CHUNK = 32; + static final long SPA_DATA_SIZEOF = 40; + + /** {@code struct spa_chunk { uint32_t offset, size; int32_t stride, flags; }} */ + static final long SPA_CHUNK_OFFSET = 0; + static final long SPA_CHUNK_SIZE = 4; + static final long SPA_CHUNK_STRIDE = 8; + static final long SPA_CHUNK_SIZEOF = 16; + + /** Slot (pointer index) of a method inside {@code struct pw_core_methods}. */ + static final int CORE_METHOD_ADD_LISTENER = 1; + static final int CORE_METHOD_SYNC = 3; + static final int CORE_METHOD_GET_REGISTRY = 6; + + /** Slot of a method inside {@code struct pw_registry_methods}. */ + static final int REGISTRY_METHOD_ADD_LISTENER = 1; + + /** Field offsets in {@code struct pw_core_events} (version at 0, then one pointer each). */ + static final long CORE_EVENTS_SIZEOF = 80; + static final long CORE_EVENTS_DONE = 16; + + /** Field offsets in {@code struct pw_registry_events}. */ + static final long REGISTRY_EVENTS_SIZEOF = 24; + static final long REGISTRY_EVENTS_GLOBAL = 8; + static final long REGISTRY_EVENTS_GLOBAL_REMOVE = 16; + + /** Field offsets in {@code struct pw_stream_events}. */ + static final long STREAM_EVENTS_SIZEOF = 96; + static final long STREAM_EVENTS_STATE_CHANGED = 16; + static final long STREAM_EVENTS_PROCESS = 64; + + /** {@code struct spa_hook}; over-allocated so a future growth cannot corrupt anything. */ + static final long SPA_HOOK_SIZEOF = 128; + + static final Linker LINKER = Linker.nativeLinker(); + + /** SONAMEs to try, newest packaging first. */ + private static final String[] LIBRARY_NAMES = {"libpipewire-0.3.so.0", "libpipewire-0.3.so"}; + + private static final class Handles { + static final SymbolLookup LOOKUP = load(); + + static final MethodHandle PW_INIT = + downcall("pw_init", FunctionDescriptor.ofVoid(PTR, PTR)); + static final MethodHandle PW_GET_LIBRARY_VERSION = + downcall("pw_get_library_version", FunctionDescriptor.of(PTR)); + + static final MethodHandle PW_THREAD_LOOP_NEW = + downcall("pw_thread_loop_new", FunctionDescriptor.of(PTR, PTR, PTR)); + static final MethodHandle PW_THREAD_LOOP_DESTROY = + downcall("pw_thread_loop_destroy", FunctionDescriptor.ofVoid(PTR)); + static final MethodHandle PW_THREAD_LOOP_GET_LOOP = + downcall("pw_thread_loop_get_loop", FunctionDescriptor.of(PTR, PTR)); + static final MethodHandle PW_THREAD_LOOP_START = + downcall("pw_thread_loop_start", FunctionDescriptor.of(INT, PTR)); + static final MethodHandle PW_THREAD_LOOP_STOP = + downcall("pw_thread_loop_stop", FunctionDescriptor.ofVoid(PTR)); + static final MethodHandle PW_THREAD_LOOP_LOCK = + downcall("pw_thread_loop_lock", FunctionDescriptor.ofVoid(PTR)); + static final MethodHandle PW_THREAD_LOOP_UNLOCK = + downcall("pw_thread_loop_unlock", FunctionDescriptor.ofVoid(PTR)); + static final MethodHandle PW_THREAD_LOOP_SIGNAL = + downcall("pw_thread_loop_signal", FunctionDescriptor.ofVoid(PTR, BOOL)); + static final MethodHandle PW_THREAD_LOOP_TIMED_WAIT = + downcall("pw_thread_loop_timed_wait", FunctionDescriptor.of(INT, PTR, INT)); + + static final MethodHandle PW_CONTEXT_NEW = + downcall("pw_context_new", FunctionDescriptor.of(PTR, PTR, PTR, LONG)); + static final MethodHandle PW_CONTEXT_CONNECT = + downcall("pw_context_connect", FunctionDescriptor.of(PTR, PTR, PTR, LONG)); + static final MethodHandle PW_CONTEXT_DESTROY = + downcall("pw_context_destroy", FunctionDescriptor.ofVoid(PTR)); + static final MethodHandle PW_CORE_DISCONNECT = + downcall("pw_core_disconnect", FunctionDescriptor.of(INT, PTR)); + static final MethodHandle PW_PROXY_DESTROY = + downcall("pw_proxy_destroy", FunctionDescriptor.ofVoid(PTR)); + + static final MethodHandle PW_PROPERTIES_NEW_DICT = + downcall("pw_properties_new_dict", FunctionDescriptor.of(PTR, PTR)); + + static final MethodHandle PW_STREAM_NEW_SIMPLE = + downcall("pw_stream_new_simple", FunctionDescriptor.of(PTR, PTR, PTR, PTR, PTR, PTR)); + static final MethodHandle PW_STREAM_CONNECT = + downcall("pw_stream_connect", FunctionDescriptor.of(INT, PTR, INT, INT, INT, PTR, INT)); + static final MethodHandle PW_STREAM_DISCONNECT = + downcall("pw_stream_disconnect", FunctionDescriptor.of(INT, PTR)); + static final MethodHandle PW_STREAM_DESTROY = + downcall("pw_stream_destroy", FunctionDescriptor.ofVoid(PTR)); + static final MethodHandle PW_STREAM_SET_ACTIVE = + downcall("pw_stream_set_active", FunctionDescriptor.of(INT, PTR, BOOL)); + static final MethodHandle PW_STREAM_FLUSH = + downcall("pw_stream_flush", FunctionDescriptor.of(INT, PTR, BOOL)); + static final MethodHandle PW_STREAM_DEQUEUE_BUFFER = + downcall("pw_stream_dequeue_buffer", FunctionDescriptor.of(PTR, PTR)); + static final MethodHandle PW_STREAM_QUEUE_BUFFER = + downcall("pw_stream_queue_buffer", FunctionDescriptor.of(INT, PTR, PTR)); + + private static SymbolLookup load() { + IllegalArgumentException last = null; + for (String name : LIBRARY_NAMES) { + try { + return SymbolLookup.libraryLookup(name, Arena.global()); + } catch (IllegalArgumentException e) { + last = e; + } + } + throw (last != null) ? last : new IllegalArgumentException("libpipewire not found"); + } + + private static MethodHandle downcall(String symbol, FunctionDescriptor descriptor) { + return LINKER.downcallHandle( + LOOKUP.find(symbol).orElseThrow(() -> + new UnsatisfiedLinkError("libpipewire: unresolved symbol " + symbol)), + descriptor); + } + } + + /** {@code true} when libpipewire could be loaded and every symbol we need resolved. */ + static boolean isAvailable() { + try { + return Handles.LOOKUP != null; + } catch (Throwable t) { + return false; + } + } + + // ---- library ---- + + static void init() { + invokeVoid(Handles.PW_INIT, MemorySegment.NULL, MemorySegment.NULL); + } + + static String libraryVersion() { + MemorySegment version = (MemorySegment) invoke(Handles.PW_GET_LIBRARY_VERSION); + return cString(version); + } + + // ---- thread loop ---- + + static MemorySegment threadLoopNew(MemorySegment name) { + return (MemorySegment) invoke(Handles.PW_THREAD_LOOP_NEW, name, MemorySegment.NULL); + } + + static void threadLoopDestroy(MemorySegment loop) { + invokeVoid(Handles.PW_THREAD_LOOP_DESTROY, loop); + } + + static MemorySegment threadLoopGetLoop(MemorySegment loop) { + return (MemorySegment) invoke(Handles.PW_THREAD_LOOP_GET_LOOP, loop); + } + + static int threadLoopStart(MemorySegment loop) { + return (int) invoke(Handles.PW_THREAD_LOOP_START, loop); + } + + static void threadLoopStop(MemorySegment loop) { + invokeVoid(Handles.PW_THREAD_LOOP_STOP, loop); + } + + static void threadLoopLock(MemorySegment loop) { + invokeVoid(Handles.PW_THREAD_LOOP_LOCK, loop); + } + + static void threadLoopUnlock(MemorySegment loop) { + invokeVoid(Handles.PW_THREAD_LOOP_UNLOCK, loop); + } + + static void threadLoopSignal(MemorySegment loop, boolean waitForAccept) { + invokeVoid(Handles.PW_THREAD_LOOP_SIGNAL, loop, waitForAccept); + } + + /** Waits for a {@code signal}, returning {@code -ETIMEDOUT} when {@code seconds} elapse. */ + static int threadLoopTimedWait(MemorySegment loop, int seconds) { + return (int) invoke(Handles.PW_THREAD_LOOP_TIMED_WAIT, loop, seconds); + } + + // ---- context / core ---- + + static MemorySegment contextNew(MemorySegment loop, MemorySegment properties) { + return (MemorySegment) invoke(Handles.PW_CONTEXT_NEW, loop, properties, 0L); + } + + static MemorySegment contextConnect(MemorySegment context, MemorySegment properties) { + return (MemorySegment) invoke(Handles.PW_CONTEXT_CONNECT, context, properties, 0L); + } + + static void contextDestroy(MemorySegment context) { + invokeVoid(Handles.PW_CONTEXT_DESTROY, context); + } + + static int coreDisconnect(MemorySegment core) { + return (int) invoke(Handles.PW_CORE_DISCONNECT, core); + } + + static void proxyDestroy(MemorySegment proxy) { + invokeVoid(Handles.PW_PROXY_DESTROY, proxy); + } + + static MemorySegment propertiesNewDict(MemorySegment dict) { + return (MemorySegment) invoke(Handles.PW_PROPERTIES_NEW_DICT, dict); + } + + // ---- stream ---- + + static MemorySegment streamNewSimple(MemorySegment loop, MemorySegment name, + MemorySegment properties, MemorySegment events, + MemorySegment data) { + return (MemorySegment) invoke(Handles.PW_STREAM_NEW_SIMPLE, loop, name, properties, events, data); + } + + static int streamConnect(MemorySegment stream, int direction, int targetId, int flags, + MemorySegment params, int paramCount) { + return (int) invoke(Handles.PW_STREAM_CONNECT, stream, direction, targetId, flags, params, paramCount); + } + + static int streamDisconnect(MemorySegment stream) { + return (int) invoke(Handles.PW_STREAM_DISCONNECT, stream); + } + + static void streamDestroy(MemorySegment stream) { + invokeVoid(Handles.PW_STREAM_DESTROY, stream); + } + + static int streamSetActive(MemorySegment stream, boolean active) { + return (int) invoke(Handles.PW_STREAM_SET_ACTIVE, stream, active); + } + + static int streamFlush(MemorySegment stream, boolean drain) { + return (int) invoke(Handles.PW_STREAM_FLUSH, stream, drain); + } + + static MemorySegment streamDequeueBuffer(MemorySegment stream) { + return (MemorySegment) invoke(Handles.PW_STREAM_DEQUEUE_BUFFER, stream); + } + + static int streamQueueBuffer(MemorySegment stream, MemorySegment buffer) { + return (int) invoke(Handles.PW_STREAM_QUEUE_BUFFER, stream, buffer); + } + + // ---- spa_interface method dispatch ---- + + /** The {@code cb.data} pointer an interface's methods expect as their first argument. */ + static MemorySegment interfaceSelf(MemorySegment iface) { + return iface.reinterpret(SPA_INTERFACE_SIZE).get(PTR, SPA_INTERFACE_CB_DATA); + } + + /** + * Binds slot {@code slot} of an interface's method table as a downcall. The table is + * a {@code uint32_t version} followed by one function pointer per method, so the slot + * is the pointer index (1 for the first method). + */ + static MethodHandle interfaceMethod(MemorySegment iface, int slot, FunctionDescriptor descriptor) { + MemorySegment methods = iface.reinterpret(SPA_INTERFACE_SIZE).get(PTR, SPA_INTERFACE_CB_FUNCS); + MemorySegment function = methods.reinterpret(8L * (slot + 1)).get(PTR, 8L * slot); + if (function.address() == 0) { + throw new UnsatisfiedLinkError("libpipewire: interface method slot " + slot + " is null"); + } + return LINKER.downcallHandle(function, descriptor); + } + + // ---- helpers ---- + + /** Reads a NUL-terminated C string from an unbounded pointer; {@code null} for NULL. */ + static String cString(MemorySegment pointer) { + if (pointer == null || pointer.address() == 0) return null; + return pointer.reinterpret(Long.MAX_VALUE).getString(0); + } + + /** Gives a pointer returned by C a known extent so its fields can be read. */ + static MemorySegment at(MemorySegment pointer, long size) { + return pointer.reinterpret(size); + } + + static Object invoke(MethodHandle handle, Object... arguments) { + try { + return handle.invokeWithArguments(arguments); + } catch (Throwable t) { + throw wrap(t); + } + } + + static void invokeVoid(MethodHandle handle, Object... arguments) { + invoke(handle, arguments); + } + + private static RuntimeException wrap(Throwable t) { + if (t instanceof RuntimeException re) return re; + if (t instanceof Error e) throw e; + return new IllegalStateException("libpipewire call failed", t); + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWirePlayback.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWirePlayback.java new file mode 100644 index 0000000..a3f8511 --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWirePlayback.java @@ -0,0 +1,49 @@ +package eu.lixko.ts3j.client.audio.desktop.pipewire; + +import eu.lixko.ts3j.client.audio.AudioPlayback; + +import java.lang.foreign.MemorySegment; + +import static eu.lixko.ts3j.client.audio.desktop.pipewire.PipeWireLibrary.INT; +import static eu.lixko.ts3j.client.audio.desktop.pipewire.PipeWireLibrary.LONG; + +/** A PipeWire playback stream ({@code PW_DIRECTION_OUTPUT}). */ +final class PipeWirePlayback extends PipeWireStream implements AudioPlayback { + + PipeWirePlayback(PipeWireSession session, String name, String targetNode, int rate, int channels) { + super(session, name, targetNode, rate, channels, false); + } + + /** + * Fills the buffer with as much queued audio as there is, padding with silence on an + * underrun so the graph always gets a full quantum. + */ + @Override + void process(MemorySegment header, MemorySegment audio, MemorySegment chunk, int maxSize) { + int stride = stride(); + long requested = header.get(LONG, PipeWireLibrary.PW_BUFFER_REQUESTED); + int bytes = maxSize; + if (requested > 0) bytes = (int) Math.min(bytes, requested * stride); + bytes -= bytes % stride; + + int filled = ring.take(audio, 0, bytes); + if (filled < bytes) audio.asSlice(filled, bytes - filled).fill((byte) 0); + + chunk.set(INT, PipeWireLibrary.SPA_CHUNK_OFFSET, 0); + chunk.set(INT, PipeWireLibrary.SPA_CHUNK_STRIDE, stride); + chunk.set(INT, PipeWireLibrary.SPA_CHUNK_SIZE, bytes); + header.set(LONG, PipeWireLibrary.PW_BUFFER_SIZE, bytes / stride); + } + + @Override + public void write(byte[] buffer, int offset, int length) { + if (ring.write(buffer, offset, length) < length && ring.isClosed()) { + throw new IllegalStateException("The PipeWire stream ended"); + } + } + + @Override + public void drain() { + ring.drain(); + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWireSession.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWireSession.java new file mode 100644 index 0000000..8919163 --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWireSession.java @@ -0,0 +1,287 @@ +package eu.lixko.ts3j.client.audio.desktop.pipewire; + +import java.lang.foreign.Arena; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.MemorySegment; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static eu.lixko.ts3j.client.audio.desktop.pipewire.PipeWireLibrary.INT; +import static eu.lixko.ts3j.client.audio.desktop.pipewire.PipeWireLibrary.PTR; + +/** + * The process-wide connection to the PipeWire daemon. + * + *

    Owns the thread loop that every stream runs on, and keeps a live view of the + * graph's audio nodes by listening to the registry — so the device list is always + * current without polling. The session is created on first use and then kept: the + * loop is a native thread that does not hold the JVM open, and re-connecting per + * device query would cost a round trip each time. + * + *

    Every libpipewire call from outside the loop thread must hold the loop lock; the + * {@code lock}/{@code unlock} pairs below are that lock, not a Java monitor. + */ +final class PipeWireSession { + + /** An audio sink (playback device) or source (capture device) in the graph. */ + record Node(String name, String description, boolean sink) { + } + + private static final int ROUNDTRIP_TIMEOUT_SECONDS = 2; + + private static volatile PipeWireSession instance; + private static volatile boolean failed; + + private final Arena arena = Arena.ofShared(); + private final MemorySegment threadLoop; + private final MemorySegment loop; + private final MemorySegment context; + private final MemorySegment core; + private final MemorySegment registry; + + private final MethodHandle coreSync; + + /** Nodes by global id, in the order the registry announced them. Guarded by itself. */ + private final Map nodes = new LinkedHashMap<>(); + + // Written on the caller's thread, read on the loop thread; the native loop mutex + // that orders them is invisible to the Java memory model. + private volatile int pendingSync; + private volatile boolean syncDone; + + /** + * Returns the shared session, or {@code null} when PipeWire is not usable here — + * no library, no daemon, or a connection that was refused. The first failure is + * remembered so an unavailable system is not retried on every device query. + */ + static PipeWireSession get() { + PipeWireSession existing = instance; + if (existing != null || failed) return existing; + synchronized (PipeWireSession.class) { + if (instance == null && !failed) { + try { + instance = new PipeWireSession(); + } catch (Throwable t) { + failed = true; + } + } + return instance; + } + } + + private PipeWireSession() { + if (!PipeWireLibrary.isAvailable()) { + throw new UnsupportedOperationException("libpipewire is not available"); + } + PipeWireLibrary.init(); + + threadLoop = nonNull(PipeWireLibrary.threadLoopNew(arena.allocateFrom("ts3-client")), + "pw_thread_loop_new"); + loop = PipeWireLibrary.threadLoopGetLoop(threadLoop); + context = nonNull(PipeWireLibrary.contextNew(loop, MemorySegment.NULL), "pw_context_new"); + + if (PipeWireLibrary.threadLoopStart(threadLoop) < 0) { + throw new IllegalStateException("pw_thread_loop_start failed"); + } + + PipeWireLibrary.threadLoopLock(threadLoop); + try { + core = nonNull(PipeWireLibrary.contextConnect(context, MemorySegment.NULL), + "pw_context_connect"); + coreSync = PipeWireLibrary.interfaceMethod(core, PipeWireLibrary.CORE_METHOD_SYNC, + FunctionDescriptor.of(INT, PTR, INT, INT)); + addCoreListener(); + registry = nonNull(getRegistry(), "pw_core_get_registry"); + addRegistryListener(); + roundtrip(); + } catch (Throwable t) { + PipeWireLibrary.threadLoopUnlock(threadLoop); + close(); + throw t; + } + PipeWireLibrary.threadLoopUnlock(threadLoop); + } + + // ---- registry / core wiring ---- + + private MemorySegment getRegistry() { + MethodHandle getRegistry = PipeWireLibrary.interfaceMethod(core, + PipeWireLibrary.CORE_METHOD_GET_REGISTRY, + FunctionDescriptor.of(PTR, PTR, INT, PipeWireLibrary.LONG)); + return (MemorySegment) PipeWireLibrary.invoke(getRegistry, + PipeWireLibrary.interfaceSelf(core), PipeWireLibrary.PW_VERSION_REGISTRY, 0L); + } + + private void addCoreListener() { + // Arena allocations are zero-filled, so every callback we do not set stays NULL. + MemorySegment events = arena.allocate(PipeWireLibrary.CORE_EVENTS_SIZEOF, 8); + events.set(INT, 0, PipeWireLibrary.PW_VERSION_CORE_EVENTS); + events.set(PTR, PipeWireLibrary.CORE_EVENTS_DONE, + upcall("onDone", MethodType.methodType(void.class, MemorySegment.class, int.class, int.class), + FunctionDescriptor.ofVoid(PTR, INT, INT))); + + MethodHandle addListener = PipeWireLibrary.interfaceMethod(core, + PipeWireLibrary.CORE_METHOD_ADD_LISTENER, + FunctionDescriptor.of(INT, PTR, PTR, PTR, PTR)); + PipeWireLibrary.invoke(addListener, PipeWireLibrary.interfaceSelf(core), + hook(), events, MemorySegment.NULL); + } + + private void addRegistryListener() { + MemorySegment events = arena.allocate(PipeWireLibrary.REGISTRY_EVENTS_SIZEOF, 8); + events.set(INT, 0, PipeWireLibrary.PW_VERSION_REGISTRY_EVENTS); + events.set(PTR, PipeWireLibrary.REGISTRY_EVENTS_GLOBAL, + upcall("onGlobal", MethodType.methodType(void.class, MemorySegment.class, int.class, + int.class, MemorySegment.class, int.class, MemorySegment.class), + FunctionDescriptor.ofVoid(PTR, INT, INT, PTR, INT, PTR))); + events.set(PTR, PipeWireLibrary.REGISTRY_EVENTS_GLOBAL_REMOVE, + upcall("onGlobalRemove", MethodType.methodType(void.class, MemorySegment.class, int.class), + FunctionDescriptor.ofVoid(PTR, INT))); + + MethodHandle addListener = PipeWireLibrary.interfaceMethod(registry, + PipeWireLibrary.REGISTRY_METHOD_ADD_LISTENER, + FunctionDescriptor.of(INT, PTR, PTR, PTR, PTR)); + PipeWireLibrary.invoke(addListener, PipeWireLibrary.interfaceSelf(registry), + hook(), events, MemorySegment.NULL); + } + + /** A zeroed {@code struct spa_hook} for a listener; it must outlive the object it hooks. */ + private MemorySegment hook() { + return arena.allocate(PipeWireLibrary.SPA_HOOK_SIZEOF, 8); + } + + private MemorySegment upcall(String method, MethodType type, FunctionDescriptor descriptor) { + try { + MethodHandle handle = MethodHandles.lookup() + .bind(this, method, type) + .asType(descriptor.toMethodType()); + return PipeWireLibrary.LINKER.upcallStub(handle, descriptor, arena); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException("cannot bind PipeWire callback " + method, e); + } + } + + // ---- callbacks, all invoked on the loop thread ---- + + @SuppressWarnings("unused") // bound as an upcall + private void onDone(MemorySegment data, int id, int seq) { + if (id != PipeWireLibrary.PW_ID_CORE || seq != pendingSync) return; + syncDone = true; + PipeWireLibrary.threadLoopSignal(threadLoop, false); + } + + @SuppressWarnings("unused") // bound as an upcall + private void onGlobal(MemorySegment data, int id, int permissions, MemorySegment type, + int version, MemorySegment props) { + try { + if (!PipeWireLibrary.TYPE_INTERFACE_NODE.equals(PipeWireLibrary.cString(type))) return; + if (props.address() == 0) return; + + Map properties = readDict(props); + String mediaClass = properties.get(PipeWireLibrary.KEY_MEDIA_CLASS); + boolean sink = "Audio/Sink".equals(mediaClass); + if (!sink && !"Audio/Source".equals(mediaClass)) return; + + String name = properties.get(PipeWireLibrary.KEY_NODE_NAME); + if (name == null || name.isBlank()) return; + + String description = firstNonBlank( + properties.get(PipeWireLibrary.KEY_NODE_DESCRIPTION), + properties.get(PipeWireLibrary.KEY_NODE_NICK), + name); + synchronized (nodes) { + nodes.put(id, new Node(name, description, sink)); + } + } catch (Throwable ignored) { + // An upcall must not throw: a node we cannot read is simply not listed. + } + } + + @SuppressWarnings("unused") // bound as an upcall + private void onGlobalRemove(MemorySegment data, int id) { + synchronized (nodes) { + nodes.remove(id); + } + } + + /** Copies a {@code struct spa_dict} into a Java map. */ + private static Map readDict(MemorySegment dict) { + MemorySegment header = PipeWireLibrary.at(dict, PipeWireLibrary.SPA_DICT_SIZE); + int itemCount = header.get(INT, PipeWireLibrary.SPA_DICT_N_ITEMS); + MemorySegment items = header.get(PTR, PipeWireLibrary.SPA_DICT_ITEMS); + Map properties = new LinkedHashMap<>(); + if (items.address() == 0 || itemCount <= 0) return properties; + + MemorySegment array = PipeWireLibrary.at(items, PipeWireLibrary.SPA_DICT_ITEM_SIZE * itemCount); + for (int i = 0; i < itemCount; i++) { + long offset = PipeWireLibrary.SPA_DICT_ITEM_SIZE * i; + String key = PipeWireLibrary.cString(array.get(PTR, offset)); + String value = PipeWireLibrary.cString( + array.get(PTR, offset + PipeWireLibrary.SPA_DICT_ITEM_VALUE)); + if (key != null) properties.put(key, value); + } + return properties; + } + + private static String firstNonBlank(String... candidates) { + for (String candidate : candidates) { + if (candidate != null && !candidate.isBlank()) return candidate; + } + return null; + } + + // ---- public surface ---- + + /** The audio sinks and sources currently in the graph. */ + List nodes() { + synchronized (nodes) { + return new ArrayList<>(nodes.values()); + } + } + + /** The loop streams are created on; only touch it under {@link #lock()}. */ + MemorySegment loop() { + return loop; + } + + void lock() { + PipeWireLibrary.threadLoopLock(threadLoop); + } + + void unlock() { + PipeWireLibrary.threadLoopUnlock(threadLoop); + } + + /** + * Waits until the server has processed everything sent so far, so that the initial + * burst of registry events has been delivered. Call with the loop lock held. + */ + private void roundtrip() { + pendingSync = (int) PipeWireLibrary.invoke(coreSync, + PipeWireLibrary.interfaceSelf(core), PipeWireLibrary.PW_ID_CORE, pendingSync + 1); + syncDone = false; + while (!syncDone) { + if (PipeWireLibrary.threadLoopTimedWait(threadLoop, ROUNDTRIP_TIMEOUT_SECONDS) != 0) break; + } + } + + private void close() { + if (threadLoop != null) PipeWireLibrary.threadLoopStop(threadLoop); + if (registry != null) PipeWireLibrary.proxyDestroy(registry); + if (core != null) PipeWireLibrary.coreDisconnect(core); + if (context != null) PipeWireLibrary.contextDestroy(context); + if (threadLoop != null) PipeWireLibrary.threadLoopDestroy(threadLoop); + } + + private static MemorySegment nonNull(MemorySegment pointer, String what) { + if (pointer == null || pointer.address() == 0) { + throw new IllegalStateException(what + " failed"); + } + return pointer; + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWireStream.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWireStream.java new file mode 100644 index 0000000..cd9d198 --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/PipeWireStream.java @@ -0,0 +1,222 @@ +package eu.lixko.ts3j.client.audio.desktop.pipewire; + +import java.lang.foreign.Arena; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.MemorySegment; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.util.LinkedHashMap; +import java.util.Map; + +import static eu.lixko.ts3j.client.audio.desktop.pipewire.PipeWireLibrary.INT; +import static eu.lixko.ts3j.client.audio.desktop.pipewire.PipeWireLibrary.PTR; + +/** + * One {@code pw_stream} plus the ring buffer that decouples it from the application. + * + *

    PipeWire is pull-based: it calls {@code process} on the loop thread whenever a + * buffer can be filled (playback) or has arrived (capture). The voice pipeline, on the + * other hand, wants to block on a line. {@link PcmRing} bridges the two — see there for + * what happens when the two sides drift apart. + * + *

    {@code PW_STREAM_FLAG_RT_PROCESS} is deliberately not used: it would run the + * callback on a real-time thread, where a garbage collection pause would be an xrun. + * Without it PipeWire schedules the callback on the loop thread instead, which is a + * normal thread and can safely run Java code. + */ +abstract class PipeWireStream { + + /** Ring capacity, as a multiple of the 20 ms frame the pipeline works in. */ + private static final int RING_FRAMES = 20; + + private static final int QUANTUM = 960; // 20 ms at 48 kHz + + private final PipeWireSession session; + private final Arena arena = Arena.ofShared(); + private final int channels; + private final int rate; + private final int stride; + protected final PcmRing ring; + + private volatile MemorySegment stream; + private volatile boolean started; + private volatile boolean closed; + + PipeWireStream(PipeWireSession session, String name, String targetNode, + int rate, int channels, boolean capture) { + this.session = session; + this.rate = rate; + this.channels = channels; + this.stride = channels * 2; // S16, interleaved + this.ring = new PcmRing(QUANTUM * stride * RING_FRAMES); + + session.lock(); + try { + stream = PipeWireLibrary.streamNewSimple(session.loop(), arena.allocateFrom(name), + properties(name, targetNode, capture), events(), MemorySegment.NULL); + if (stream.address() == 0) { + throw new IllegalStateException("pw_stream_new_simple failed"); + } + MemorySegment params = arena.allocate(PTR, 1); + params.set(PTR, 0, SpaPod.audioFormat(arena, rate, channels)); + + int flags = PipeWireLibrary.PW_STREAM_FLAG_AUTOCONNECT + | PipeWireLibrary.PW_STREAM_FLAG_MAP_BUFFERS + | PipeWireLibrary.PW_STREAM_FLAG_INACTIVE; + int result = PipeWireLibrary.streamConnect(stream, + capture ? PipeWireLibrary.PW_DIRECTION_INPUT : PipeWireLibrary.PW_DIRECTION_OUTPUT, + PipeWireLibrary.PW_ID_ANY, flags, params, 1); + if (result < 0) { + throw new IllegalStateException("pw_stream_connect failed: " + result); + } + } catch (Throwable t) { + session.unlock(); + close(); + throw t; + } + session.unlock(); + } + + /** + * Properties the server uses to place and label the stream: the target device, the + * name shown in volume mixers, and the quantum we would like to be called with. + */ + private MemorySegment properties(String name, String targetNode, boolean capture) { + Map properties = new LinkedHashMap<>(); + properties.put(PipeWireLibrary.KEY_MEDIA_TYPE, "Audio"); + properties.put(PipeWireLibrary.KEY_MEDIA_CATEGORY, capture ? "Capture" : "Playback"); + properties.put(PipeWireLibrary.KEY_MEDIA_ROLE, "Communication"); + properties.put(PipeWireLibrary.KEY_APP_NAME, "TeamSpook TS3j"); + properties.put(PipeWireLibrary.KEY_NODE_NAME, name); + properties.put(PipeWireLibrary.KEY_NODE_LATENCY, QUANTUM + "/" + rate); + properties.put(PipeWireLibrary.KEY_NODE_RATE, "1/" + rate); + if (targetNode != null && !targetNode.isEmpty()) { + properties.put(PipeWireLibrary.KEY_TARGET_OBJECT, targetNode); + } + return PipeWireLibrary.propertiesNewDict(dict(properties)); + } + + /** Builds a temporary {@code struct spa_dict}; {@code pw_properties_new_dict} copies it. */ + private MemorySegment dict(Map properties) { + MemorySegment items = arena.allocate( + PipeWireLibrary.SPA_DICT_ITEM_SIZE * properties.size(), 8); + int index = 0; + for (Map.Entry entry : properties.entrySet()) { + long offset = PipeWireLibrary.SPA_DICT_ITEM_SIZE * index++; + items.set(PTR, offset, arena.allocateFrom(entry.getKey())); + items.set(PTR, offset + PipeWireLibrary.SPA_DICT_ITEM_VALUE, + arena.allocateFrom(entry.getValue())); + } + MemorySegment dict = arena.allocate(PipeWireLibrary.SPA_DICT_SIZE, 8); + dict.set(INT, PipeWireLibrary.SPA_DICT_N_ITEMS, properties.size()); + dict.set(PTR, PipeWireLibrary.SPA_DICT_ITEMS, items); + return dict; + } + + private MemorySegment events() { + MemorySegment events = arena.allocate(PipeWireLibrary.STREAM_EVENTS_SIZEOF, 8); + events.set(INT, 0, PipeWireLibrary.PW_VERSION_STREAM_EVENTS); + events.set(PTR, PipeWireLibrary.STREAM_EVENTS_PROCESS, + upcall("onProcess", MethodType.methodType(void.class, MemorySegment.class), + FunctionDescriptor.ofVoid(PTR))); + events.set(PTR, PipeWireLibrary.STREAM_EVENTS_STATE_CHANGED, + upcall("onStateChanged", MethodType.methodType(void.class, MemorySegment.class, + int.class, int.class, MemorySegment.class), + FunctionDescriptor.ofVoid(PTR, INT, INT, PTR))); + return events; + } + + private MemorySegment upcall(String method, MethodType type, FunctionDescriptor descriptor) { + try { + MethodHandle handle = MethodHandles.lookup().bind(this, method, type); + return PipeWireLibrary.LINKER.upcallStub(handle, descriptor, arena); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException("cannot bind PipeWire callback " + method, e); + } + } + + // ---- callbacks, invoked on the loop thread with the loop lock held ---- + + @SuppressWarnings("unused") // bound as an upcall + private void onStateChanged(MemorySegment data, int previous, int current, MemorySegment message) { + // A stream that errored will never be scheduled again, so unblock the pipeline + // instead of letting it wait for audio that cannot arrive. + if (current == PipeWireLibrary.PW_STREAM_STATE_ERROR) ring.close(); + } + + @SuppressWarnings("unused") // bound as an upcall + private void onProcess(MemorySegment data) { + try { + MemorySegment pwBuffer = PipeWireLibrary.streamDequeueBuffer(stream); + if (pwBuffer.address() == 0) return; // out of buffers; skip a cycle + try { + MemorySegment header = PipeWireLibrary.at(pwBuffer, PipeWireLibrary.PW_BUFFER_SIZEOF); + MemorySegment spaBuffer = PipeWireLibrary.at( + header.get(PTR, PipeWireLibrary.PW_BUFFER_BUFFER), PipeWireLibrary.SPA_BUFFER_SIZEOF); + if (spaBuffer.get(INT, PipeWireLibrary.SPA_BUFFER_N_DATAS) < 1) return; + + MemorySegment datum = PipeWireLibrary.at( + spaBuffer.get(PTR, PipeWireLibrary.SPA_BUFFER_DATAS), PipeWireLibrary.SPA_DATA_SIZEOF); + MemorySegment audio = datum.get(PTR, PipeWireLibrary.SPA_DATA_DATA); + if (audio.address() == 0) return; // not mapped (e.g. a DmaBuf) + + int maxSize = datum.get(INT, PipeWireLibrary.SPA_DATA_MAXSIZE); + MemorySegment chunk = PipeWireLibrary.at( + datum.get(PTR, PipeWireLibrary.SPA_DATA_CHUNK), PipeWireLibrary.SPA_CHUNK_SIZEOF); + process(header, PipeWireLibrary.at(audio, maxSize), chunk, maxSize); + } finally { + PipeWireLibrary.streamQueueBuffer(stream, pwBuffer); + } + } catch (Throwable ignored) { + // An upcall must not throw: drop the cycle rather than take the JVM down. + } + } + + /** + * Moves one buffer between {@code audio} and the ring. + * + * @param header the {@code struct pw_buffer}, for {@code requested} and {@code size} + * @param audio the mapped payload, {@code maxSize} bytes long + * @param chunk the {@code struct spa_chunk} describing the valid part of {@code audio} + */ + abstract void process(MemorySegment header, MemorySegment audio, MemorySegment chunk, int maxSize); + + // ---- lifecycle ---- + + public int channels() { + return channels; + } + + final int stride() { + return stride; + } + + public synchronized void start() { + if (started || closed) return; + started = true; + session.lock(); + try { + PipeWireLibrary.streamSetActive(stream, true); + } finally { + session.unlock(); + } + } + + public synchronized void close() { + if (closed) return; + closed = true; + ring.close(); + if (stream != null && stream.address() != 0) { + session.lock(); + try { + PipeWireLibrary.streamDestroy(stream); // disconnects and drops the listeners + } finally { + session.unlock(); + } + stream = null; + } + // Only safe once the loop can no longer reach the upcall stubs, i.e. after destroy. + arena.close(); + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/SpaPod.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/SpaPod.java new file mode 100644 index 0000000..e7f7337 --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/audio/desktop/pipewire/SpaPod.java @@ -0,0 +1,161 @@ +package eu.lixko.ts3j.client.audio.desktop.pipewire; + +import java.lang.foreign.MemorySegment; +import java.lang.foreign.SegmentAllocator; +import java.lang.foreign.ValueLayout; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +/** + * Builder for the SPA "plain old data" objects PipeWire uses to describe formats. + * + *

    A POD is a length-prefixed tree: every value is an 8-byte header + * ({@code uint32_t size; uint32_t type;}) followed by {@code size} bytes of body, padded + * out to a multiple of 8. An object adds {@code uint32_t type; uint32_t id;} in front of + * its properties, and each property is {@code uint32_t key; uint32_t flags;} followed by + * one value POD. + * + *

    libpipewire only offers {@code spa_pod_builder} as inline C, so the bytes are + * assembled here instead. {@code SpaPodTest} pins the output against the bytes the real + * {@code spa_format_audio_raw_build()} produces. + */ +final class SpaPod { + + // ---- enum spa_type ---- + private static final int SPA_TYPE_ID = 3; + private static final int SPA_TYPE_INT = 4; + private static final int SPA_TYPE_ARRAY = 13; + private static final int SPA_TYPE_OBJECT = 15; + private static final int SPA_TYPE_OBJECT_FORMAT = 0x0004_0003; + + // ---- enum spa_param_type ---- + static final int SPA_PARAM_ENUM_FORMAT = 3; + + // ---- enum spa_format (object property keys) ---- + private static final int SPA_FORMAT_MEDIA_TYPE = 1; + private static final int SPA_FORMAT_MEDIA_SUBTYPE = 2; + private static final int SPA_FORMAT_AUDIO_FORMAT = 0x0001_0001; + private static final int SPA_FORMAT_AUDIO_RATE = 0x0001_0003; + private static final int SPA_FORMAT_AUDIO_CHANNELS = 0x0001_0004; + private static final int SPA_FORMAT_AUDIO_POSITION = 0x0001_0005; + + private static final int SPA_MEDIA_TYPE_AUDIO = 1; + private static final int SPA_MEDIA_SUBTYPE_RAW = 1; + + /** {@code SPA_AUDIO_FORMAT_S16_LE} — interleaved signed 16-bit, what our pipeline uses. */ + static final int SPA_AUDIO_FORMAT_S16_LE = 0x103; + + // ---- enum spa_audio_channel ---- + private static final int SPA_AUDIO_CHANNEL_UNKNOWN = 0; + private static final int SPA_AUDIO_CHANNEL_MONO = 2; + private static final int SPA_AUDIO_CHANNEL_FL = 3; + private static final int SPA_AUDIO_CHANNEL_FR = 4; + + private final ByteBuffer buffer; + + private SpaPod(int capacity) { + this.buffer = ByteBuffer.allocate(capacity).order(ByteOrder.LITTLE_ENDIAN); + } + + /** + * Builds the single {@code EnumFormat} parameter a stream offers when connecting: + * interleaved S16 audio at one fixed rate and channel count. Offering exactly one + * format lets the server put its own converter in front of us, so the negotiated + * format is always the one asked for here. + */ + static MemorySegment audioFormat(SegmentAllocator allocator, int rate, int channels) { + SpaPod pod = new SpaPod(256); + pod.beginObject(SPA_TYPE_OBJECT_FORMAT, SPA_PARAM_ENUM_FORMAT); + pod.id(SPA_FORMAT_MEDIA_TYPE, SPA_MEDIA_TYPE_AUDIO); + pod.id(SPA_FORMAT_MEDIA_SUBTYPE, SPA_MEDIA_SUBTYPE_RAW); + pod.id(SPA_FORMAT_AUDIO_FORMAT, SPA_AUDIO_FORMAT_S16_LE); + pod.integer(SPA_FORMAT_AUDIO_RATE, rate); + pod.integer(SPA_FORMAT_AUDIO_CHANNELS, channels); + pod.idArray(SPA_FORMAT_AUDIO_POSITION, positions(channels)); + pod.endObject(); + return pod.toSegment(allocator); + } + + /** Channel map for the layouts we use; anything wider is left for the server to assign. */ + private static int[] positions(int channels) { + return switch (channels) { + case 1 -> new int[]{SPA_AUDIO_CHANNEL_MONO}; + case 2 -> new int[]{SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR}; + default -> { + int[] unknown = new int[channels]; + java.util.Arrays.fill(unknown, SPA_AUDIO_CHANNEL_UNKNOWN); + yield unknown; + } + }; + } + + // ---- writing ---- + + /** Offset of the size field of the object being built, patched by {@link #endObject}. */ + private int objectSizeOffset = -1; + + private void beginObject(int type, int id) { + objectSizeOffset = buffer.position(); + buffer.putInt(0); // size, patched in endObject + buffer.putInt(SPA_TYPE_OBJECT); + buffer.putInt(type); + buffer.putInt(id); + } + + private void endObject() { + int bodyStart = objectSizeOffset + 8; + buffer.putInt(objectSizeOffset, buffer.position() - bodyStart); + } + + private void id(int key, int value) { + property(key, SPA_TYPE_ID, 4); + buffer.putInt(value); + pad(); + } + + private void integer(int key, int value) { + property(key, SPA_TYPE_INT, 4); + buffer.putInt(value); + pad(); + } + + /** An array POD: a child header describing one element, then the elements. */ + private void idArray(int key, int[] values) { + property(key, SPA_TYPE_ARRAY, 8 + 4 * values.length); + buffer.putInt(4); + buffer.putInt(SPA_TYPE_ID); + for (int value : values) { + buffer.putInt(value); + } + pad(); + } + + /** Writes {@code key/flags} plus the value header; the caller writes the body. */ + private void property(int key, int type, int size) { + buffer.putInt(key); + buffer.putInt(0); // flags + buffer.putInt(size); + buffer.putInt(type); + } + + /** Bodies are padded to 8 bytes; the padding is not counted in the declared size. */ + private void pad() { + while ((buffer.position() & 7) != 0) { + buffer.put((byte) 0); + } + } + + private MemorySegment toSegment(SegmentAllocator allocator) { + MemorySegment segment = allocator.allocate(buffer.position(), 8); + MemorySegment.copy(MemorySegment.ofBuffer(buffer.flip()), 0, segment, 0, segment.byteSize()); + return segment; + } + + /** The bytes this builder produced, for tests. */ + static byte[] audioFormatBytes(int rate, int channels) { + try (java.lang.foreign.Arena arena = java.lang.foreign.Arena.ofConfined()) { + MemorySegment pod = audioFormat(arena, rate, channels); + return pod.toArray(ValueLayout.JAVA_BYTE); + } + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/DesktopInputHooks.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/DesktopInputHooks.java new file mode 100644 index 0000000..d813162 --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/DesktopInputHooks.java @@ -0,0 +1,102 @@ +package eu.lixko.ts3j.client.hotkey.desktop; + +import eu.lixko.ts3j.client.hotkey.GlobalInputHook; +import eu.lixko.ts3j.client.hotkey.HotkeyKey; + +import java.util.ArrayList; +import java.util.List; + +/** + * Picks the global input hook that suits the running session and starts it. + * + *

    Windows has one answer, raw input. On X11 it is XInput2, with RECORD behind it for + * servers that lack it: neither needs privileges or devices to open. On Wayland the X + * server sees only what the compositor forwards, so reading evdev is the surest way to + * catch every key — and when that is not permitted either, the returned hook is simply + * not running and says why. + */ +public final class DesktopInputHooks { + + private DesktopInputHooks() { + } + + /** @return a hook, started when it could be; check {@link GlobalInputHook#isRunning()} */ + public static GlobalInputHook start(GlobalInputHook.Listener listener) { + List reasons = new ArrayList<>(); + for (GlobalInputHook hook : candidates()) { + hook.start(listener); + if (hook.isRunning()) return hook; + reasons.add(hook.getClass().getSimpleName() + ": " + hook.unavailableReason()); + hook.close(); + } + return new Unavailable(reasons.isEmpty() + ? "no global input backend for this session" + : String.join("; ", reasons)); + } + + private static List candidates() { + List hooks = new ArrayList<>(); + if (Win32.isWindows()) { + if (WindowsInputHook.isSupported()) hooks.add(new WindowsInputHook()); + return hooks; + } + if (isWayland()) { + // Evdev first: it is the only backend guaranteed to see keys aimed at native + // Wayland windows. Failing that, Xwayland still covers every X11 app, and on + // compositors that forward the rest — KWin, with legacy X11 app support on — + // it covers those too. + if (EvdevInputHook.isSupported()) hooks.add(new EvdevInputHook()); + addX11Hooks(hooks); + } else { + addX11Hooks(hooks); + if (EvdevInputHook.isSupported()) hooks.add(new EvdevInputHook()); + } + return hooks; + } + + /** + * RECORD before XInput2: on at least some driver stacks, XInput2's raw + * {@code XI_RawButtonRelease} never reaches a client that hasn't grabbed the pointer — + * see {@link XInput2InputHook} — which makes a bound mouse button look stuck down. + * RECORD taps the same core events {@code xev} sees and is not affected. XInput2 stays + * as the fallback for servers where RECORD is disabled or missing. + */ + private static void addX11Hooks(List hooks) { + if (XRecordInputHook.isSupported()) hooks.add(new XRecordInputHook()); + if (XInput2InputHook.isSupported()) hooks.add(new XInput2InputHook()); + } + + private static boolean isWayland() { + return System.getenv("WAYLAND_DISPLAY") != null + || "wayland".equalsIgnoreCase(System.getenv("XDG_SESSION_TYPE")); + } + + /** Stands in when no backend could start, so callers need no null checks. */ + private record Unavailable(String reason) implements GlobalInputHook { + + @Override + public void start(Listener listener) { + } + + @Override + public boolean isRunning() { + return false; + } + + @Override + public String unavailableReason() { + return reason; + } + + @Override + public String keyName(HotkeyKey key) { + // Bindings recorded earlier still deserve their real names in the dialog, + // even with no hook running to have produced them. + return Win32.isWindows() ? WindowsKeyNamer.name(key) : X11KeyNamer.name(key); + } + + @Override + public void close() { + } + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/EvdevInputHook.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/EvdevInputHook.java new file mode 100644 index 0000000..907f938 --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/EvdevInputHook.java @@ -0,0 +1,151 @@ +package eu.lixko.ts3j.client.hotkey.desktop; + +import eu.lixko.ts3j.client.hotkey.GlobalInputHook; +import eu.lixko.ts3j.client.hotkey.HotkeyKey; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.ArrayList; +import java.util.List; + +/** + * System-wide input hook that reads the kernel's evdev devices directly, for sessions + * where {@link XRecordInputHook} cannot see everything — Wayland above all, where the X + * server is only told about events aimed at X clients. + * + *

    It needs read access to {@code /dev/input/event*}, which normally means membership + * of the {@code input} group; without it the hook reports itself unavailable and the + * client carries on without global hotkeys. + * + *

    Key codes are reported as X keycodes (the kernel code plus 8) and buttons as X + * button numbers, so bindings mean the same thing whichever backend recorded them. + */ +public final class EvdevInputHook implements GlobalInputHook { + + private static final File INPUT_DIR = new File("/dev/input"); + /** {@code struct input_event} on 64-bit Linux: two 8-byte time fields, then type/code/value. */ + private static final int EVENT_SIZE = 24; + private static final int EV_KEY = 1; + /** Kernel key codes below this are keyboard keys; from here up they are BTN_* buttons. */ + private static final int BTN_MISC = 0x100; + private static final int BTN_LEFT = 0x110; + + private final List streams = new ArrayList<>(); + private final List threads = new ArrayList<>(); + private volatile Listener listener; + private volatile boolean running; + private volatile String unavailable = "not started"; + + public static boolean isSupported() { + File[] devices = INPUT_DIR.listFiles((dir, name) -> name.startsWith("event")); + if (devices == null) return false; + for (File device : devices) { + if (device.canRead()) return true; + } + return false; + } + + @Override + public void start(Listener listener) { + this.listener = listener; + File[] devices = INPUT_DIR.listFiles((dir, name) -> name.startsWith("event")); + if (devices == null || devices.length == 0) { + unavailable = "no /dev/input devices"; + return; + } + for (File device : devices) { + try { + InputStream in = new FileInputStream(device); + streams.add(in); + Thread t = new Thread(() -> read(in), "ts3j-hotkeys-evdev-" + device.getName()); + t.setDaemon(true); + threads.add(t); + } catch (Exception ignored) { + // Devices we may not read are simply skipped. + } + } + if (streams.isEmpty()) { + unavailable = "no readable /dev/input device — add your user to the \"input\" group"; + return; + } + running = true; + unavailable = ""; + for (Thread t : threads) t.start(); + } + + private void read(InputStream in) { + byte[] buffer = new byte[EVENT_SIZE * 16]; + ByteBuffer view = ByteBuffer.wrap(buffer).order(ByteOrder.nativeOrder()); + while (running) { + try { + int read = in.read(buffer); + if (read < 0) return; + for (int offset = 0; offset + EVENT_SIZE <= read; offset += EVENT_SIZE) { + int type = view.getShort(offset + 16) & 0xffff; + int code = view.getShort(offset + 18) & 0xffff; + int value = view.getInt(offset + 20); + // 2 is auto-repeat, which must not look like a fresh press. + if (type == EV_KEY && value != 2) dispatch(code, value == 1); + } + } catch (Exception e) { + return; + } + } + } + + private void dispatch(int code, boolean pressed) { + Listener l = listener; + if (l == null) return; + HotkeyKey key = code < BTN_MISC ? HotkeyKey.keyboard(code + 8) : mouse(code); + if (key != null) l.onInput(key, pressed); + } + + /** Maps the kernel's BTN_* codes onto the X button numbering. */ + private static HotkeyKey mouse(int code) { + return switch (code) { + case BTN_LEFT -> HotkeyKey.mouse(1); + case BTN_LEFT + 1 -> HotkeyKey.mouse(3); // BTN_RIGHT + case BTN_LEFT + 2 -> HotkeyKey.mouse(2); // BTN_MIDDLE + case BTN_LEFT + 3 -> HotkeyKey.mouse(8); // BTN_SIDE, "mouse 4" + case BTN_LEFT + 4 -> HotkeyKey.mouse(9); // BTN_EXTRA, "mouse 5" + case BTN_LEFT + 5 -> HotkeyKey.mouse(10); // BTN_FORWARD + case BTN_LEFT + 6 -> HotkeyKey.mouse(11); // BTN_BACK + case BTN_LEFT + 7 -> HotkeyKey.mouse(12); // BTN_TASK + default -> null; // joysticks, lid switches, … + }; + } + + @Override + public boolean isRunning() { + return running; + } + + @Override + public String unavailableReason() { + return running ? "" : unavailable; + } + + @Override + public String keyName(HotkeyKey key) { + // The kernel knows scancodes, not layouts; let X name the key when it can. + return X11KeyNamer.name(key); + } + + @Override + public void close() { + running = false; + listener = null; + // Closing the descriptor is what breaks the readers out of their blocking read. + for (InputStream in : streams) { + try { + in.close(); + } catch (Exception ignored) { + } + } + streams.clear(); + threads.clear(); + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/KeyNames.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/KeyNames.java new file mode 100644 index 0000000..ee67dfe --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/KeyNames.java @@ -0,0 +1,47 @@ +package eu.lixko.ts3j.client.hotkey.desktop; + +import java.util.Map; + +/** Turns X keysym names into the labels users expect on a hotkey button. */ +final class KeyNames { + + private KeyNames() { + } + + private static final Map SPECIAL = Map.ofEntries( + Map.entry("Control_L", "Left Ctrl"), + Map.entry("Control_R", "Right Ctrl"), + Map.entry("Shift_L", "Left Shift"), + Map.entry("Shift_R", "Right Shift"), + Map.entry("Alt_L", "Left Alt"), + Map.entry("Alt_R", "Right Alt"), + Map.entry("ISO_Level3_Shift", "AltGr"), + Map.entry("Super_L", "Left Super"), + Map.entry("Super_R", "Right Super"), + Map.entry("Meta_L", "Left Meta"), + Map.entry("Meta_R", "Right Meta"), + Map.entry("Prior", "Page Up"), + Map.entry("Next", "Page Down"), + Map.entry("Return", "Enter"), + Map.entry("space", "Space"), + Map.entry("BackSpace", "Backspace"), + Map.entry("Escape", "Esc"), + Map.entry("Caps_Lock", "Caps Lock"), + Map.entry("Num_Lock", "Num Lock"), + Map.entry("Scroll_Lock", "Scroll Lock"), + Map.entry("Menu", "Menu"), + Map.entry("Print", "Print Screen")); + + /** + * @param keysym the X name of the keysym, e.g. {@code a}, {@code Control_L}, {@code KP_Add} + * @return a display name, or {@code null} when there is nothing sensible to show + */ + static String pretty(String keysym) { + if (keysym == null || keysym.isBlank()) return null; + String special = SPECIAL.get(keysym); + if (special != null) return special; + if (keysym.startsWith("KP_")) return "Numpad " + pretty(keysym.substring(3)); + if (keysym.length() == 1) return keysym.toUpperCase(); + return keysym.replace('_', ' '); + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/RawInput.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/RawInput.java new file mode 100644 index 0000000..1273a35 --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/RawInput.java @@ -0,0 +1,109 @@ +package eu.lixko.ts3j.client.hotkey.desktop; + +import eu.lixko.ts3j.client.hotkey.HotkeyKey; + +import java.util.ArrayList; +import java.util.List; + +/** + * Layout of a {@code RAWINPUT} structure and the reading of the two kinds we ask for, + * split out from {@link WindowsInputHook} so the decoding can be tested anywhere. + * + *

    Keyboards report a set-1 scan code, which is what a binding stores: it names the + * physical key, so it survives a layout change exactly as an X keycode does on Linux. + * Mice are renumbered to the X button numbering the rest of the client already speaks, + * so {@link HotkeyKey#fallbackName()} and the saved bindings mean the same thing on + * both platforms. + */ +final class RawInput { + + private RawInput() { + } + + /** {@code RAWINPUTHEADER.dwType}. */ + static final int TYPE_MOUSE = 0; + static final int TYPE_KEYBOARD = 1; + + /** Field offsets in {@code RAWINPUT} under x64, past the 24-byte header. */ + static final long HEADER_TYPE = 0; + static final long HEADER_SIZE = 24; + static final long KEYBOARD_MAKE_CODE = 24; + static final long KEYBOARD_FLAGS = 26; + static final long KEYBOARD_VKEY = 30; + static final long MOUSE_BUTTON_FLAGS = 28; + + /** Both event kinds fit comfortably; the larger, {@code RAWMOUSE}, needs 48 bytes. */ + static final long BUFFER_SIZE = 64; + + /** {@code RAWKEYBOARD.Flags}. */ + static final int RI_KEY_BREAK = 0x01; + static final int RI_KEY_E0 = 0x02; + static final int RI_KEY_E1 = 0x04; + + /** {@code VK_NO_VKEY}: the filler half of an escaped sequence, carrying no key. */ + private static final int VKEY_NONE = 0xFF; + + /** {@code RAWMOUSE.usButtonFlags}, in down/up pairs. */ + private static final int[] BUTTON_FLAGS = { + 0x0001, 0x0002, 1, // left + 0x0010, 0x0020, 2, // middle + 0x0004, 0x0008, 3, // right + 0x0040, 0x0080, 8, // X1, "Mouse 4" + 0x0100, 0x0200, 9, // X2, "Mouse 5" + }; + + private static final int RI_MOUSE_WHEEL = 0x0400; + private static final int RI_MOUSE_HWHEEL = 0x0800; + + /** + * The scan code identifying a key, with the escape prefix folded into the high byte + * so that e.g. right Ctrl ({@code E0 1D}) stays distinct from left ({@code 1D}). + * + * @return the code, or -1 when the event names no key of its own + */ + static int scanCode(int makeCode, int flags, int vkey) { + if (vkey == VKEY_NONE) return -1; + int code = makeCode & 0xFF; + if (code == 0) return -1; + if ((flags & RI_KEY_E0) != 0) code |= 0xE000; + else if ((flags & RI_KEY_E1) != 0) code |= 0xE100; + return code; + } + + static boolean isRelease(int flags) { + return (flags & RI_KEY_BREAK) != 0; + } + + /** One button transition, in the order the flags word packs them. */ + record ButtonEvent(HotkeyKey key, boolean pressed) { + } + + /** + * Unpacks a mouse event, which may carry several transitions at once. + * + * @param buttonFlags {@code usButtonFlags} + * @param wheelDelta {@code usButtonData}, read as a signed delta when a wheel bit is set + */ + static List buttons(int buttonFlags, short wheelDelta) { + List events = new ArrayList<>(); + for (int i = 0; i < BUTTON_FLAGS.length; i += 3) { + HotkeyKey key = HotkeyKey.mouse(BUTTON_FLAGS[i + 2]); + if ((buttonFlags & BUTTON_FLAGS[i]) != 0) events.add(new ButtonEvent(key, true)); + if ((buttonFlags & BUTTON_FLAGS[i + 1]) != 0) events.add(new ButtonEvent(key, false)); + } + // A wheel notch has no release of its own; X reports it as a button tap, and the + // hotkey engine expects the same shape, so synthesise both edges. + if ((buttonFlags & RI_MOUSE_WHEEL) != 0 && wheelDelta != 0) { + tap(events, wheelDelta > 0 ? 4 : 5); + } + if ((buttonFlags & RI_MOUSE_HWHEEL) != 0 && wheelDelta != 0) { + tap(events, wheelDelta > 0 ? 7 : 6); + } + return events; + } + + private static void tap(List events, int button) { + events.add(new ButtonEvent(HotkeyKey.mouse(button), true)); + events.add(new ButtonEvent(HotkeyKey.mouse(button), false)); + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/Win32.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/Win32.java new file mode 100644 index 0000000..2386d50 --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/Win32.java @@ -0,0 +1,210 @@ +package eu.lixko.ts3j.client.hotkey.desktop; + +import java.lang.foreign.Arena; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.Linker; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.SymbolLookup; +import java.lang.foreign.ValueLayout; +import java.lang.invoke.MethodHandle; +import java.nio.charset.StandardCharsets; + +/** + * Raw binding to {@code user32} and {@code kernel32}, with just the calls + * {@link WindowsInputHook} needs to own a message-only window and read raw input from it. + * + *

    Raw input is the polite way to watch the whole machine on Windows: registering with + * {@code RIDEV_INPUTSINK} delivers every key and button even while another application is + * in the foreground, and — unlike a {@code WH_KEYBOARD_LL} hook — it observes rather than + * intercepts, so nothing can be swallowed and nothing serialises the system input queue. + * + *

    Loading is lazy and failure is expected off Windows, where {@link #isAvailable()} + * returns {@code false} and the caller falls back to another backend. + */ +final class Win32 { + + private Win32() { + } + + private static final ValueLayout.OfInt INT = ValueLayout.JAVA_INT; + private static final ValueLayout.OfLong LONG = ValueLayout.JAVA_LONG; + private static final java.lang.foreign.AddressLayout PTR = ValueLayout.ADDRESS; + + /** Window messages we care about. */ + static final int WM_DESTROY = 0x0002; + static final int WM_CLOSE = 0x0010; + static final int WM_INPUT = 0x00FF; + + /** {@code HWND_MESSAGE}: parent for a window that only ever receives messages. */ + static final long HWND_MESSAGE = -3L; + + /** {@code RIDEV_INPUTSINK}: deliver input even when the window is not in front. */ + static final int RIDEV_INPUTSINK = 0x00000100; + + /** HID usages for the two devices we register (usage page 1, "generic desktop"). */ + static final int USAGE_PAGE_GENERIC = 0x01; + static final int USAGE_MOUSE = 0x02; + static final int USAGE_KEYBOARD = 0x06; + + /** {@code RID_INPUT}: ask {@code GetRawInputData} for the payload, not the header. */ + static final int RID_INPUT = 0x10000003; + + /** {@code WNDCLASSEXW} size and the field offsets we fill, under x64. */ + static final long WNDCLASS_SIZE = 80; + static final long WNDCLASS_CBSIZE = 0; + static final long WNDCLASS_WNDPROC = 8; + static final long WNDCLASS_HINSTANCE = 24; + static final long WNDCLASS_CLASSNAME = 64; + + /** {@code RAWINPUTDEVICE}: usage page, usage, flags, target window. */ + static final long RAWINPUTDEVICE_SIZE = 16; + static final long RAWINPUTDEVICE_USAGE_PAGE = 0; + static final long RAWINPUTDEVICE_USAGE = 2; + static final long RAWINPUTDEVICE_FLAGS = 4; + static final long RAWINPUTDEVICE_TARGET = 8; + + /** {@code MSG} is 48 bytes under x64. */ + static final long MSG_SIZE = 48; + + /** The C signature of a {@code WNDPROC}. */ + static final FunctionDescriptor WND_PROC = + FunctionDescriptor.of(LONG, PTR, INT, LONG, LONG); + + private static final Linker LINKER = Linker.nativeLinker(); + + private static final class Libs { + static final SymbolLookup USER32 = SymbolLookup.libraryLookup("user32.dll", Arena.global()); + static final SymbolLookup KERNEL32 = SymbolLookup.libraryLookup("kernel32.dll", Arena.global()); + + static final MethodHandle GET_MODULE_HANDLE = + downcall(KERNEL32, "GetModuleHandleW", FunctionDescriptor.of(PTR, PTR)); + static final MethodHandle REGISTER_CLASS = + downcall(USER32, "RegisterClassExW", FunctionDescriptor.of(INT, PTR)); + static final MethodHandle UNREGISTER_CLASS = + downcall(USER32, "UnregisterClassW", FunctionDescriptor.of(INT, PTR, PTR)); + static final MethodHandle CREATE_WINDOW = + downcall(USER32, "CreateWindowExW", FunctionDescriptor.of(PTR, + INT, PTR, PTR, INT, INT, INT, INT, INT, PTR, PTR, PTR, PTR)); + static final MethodHandle DESTROY_WINDOW = + downcall(USER32, "DestroyWindow", FunctionDescriptor.of(INT, PTR)); + static final MethodHandle DEF_WINDOW_PROC = + downcall(USER32, "DefWindowProcW", FunctionDescriptor.of(LONG, PTR, INT, LONG, LONG)); + static final MethodHandle GET_MESSAGE = + downcall(USER32, "GetMessageW", FunctionDescriptor.of(INT, PTR, PTR, INT, INT)); + static final MethodHandle DISPATCH_MESSAGE = + downcall(USER32, "DispatchMessageW", FunctionDescriptor.of(LONG, PTR)); + static final MethodHandle POST_MESSAGE = + downcall(USER32, "PostMessageW", FunctionDescriptor.of(INT, PTR, INT, LONG, LONG)); + static final MethodHandle POST_QUIT_MESSAGE = + downcall(USER32, "PostQuitMessage", FunctionDescriptor.ofVoid(INT)); + static final MethodHandle REGISTER_RAW_INPUT = + downcall(USER32, "RegisterRawInputDevices", FunctionDescriptor.of(INT, PTR, INT, INT)); + static final MethodHandle GET_RAW_INPUT_DATA = + downcall(USER32, "GetRawInputData", + FunctionDescriptor.of(INT, PTR, INT, PTR, PTR, INT)); + static final MethodHandle GET_KEY_NAME_TEXT = + downcall(USER32, "GetKeyNameTextW", FunctionDescriptor.of(INT, INT, PTR, INT)); + } + + private static MethodHandle downcall(SymbolLookup lookup, String symbol, + FunctionDescriptor descriptor) { + return LINKER.downcallHandle( + lookup.find(symbol).orElseThrow(() -> + new UnsatisfiedLinkError("unresolved symbol " + symbol)), + descriptor); + } + + static boolean isWindows() { + return System.getProperty("os.name", "").toLowerCase().startsWith("windows"); + } + + static boolean isAvailable() { + if (!isWindows()) return false; + try { + return Libs.USER32 != null && Libs.KERNEL32 != null; + } catch (Throwable t) { + return false; + } + } + + /** Allocates a null-terminated UTF-16 string, as every {@code ...W} entry point wants. */ + static MemorySegment wide(Arena arena, String text) { + return arena.allocateFrom(text, StandardCharsets.UTF_16LE); + } + + static MemorySegment moduleHandle() { + return (MemorySegment) call(Libs.GET_MODULE_HANDLE, MemorySegment.NULL); + } + + /** @return the class atom, or 0 when registration failed */ + static int registerClass(MemorySegment wndClass) { + return (int) call(Libs.REGISTER_CLASS, wndClass); + } + + static void unregisterClass(MemorySegment className, MemorySegment instance) { + call(Libs.UNREGISTER_CLASS, className, instance); + } + + /** Creates a message-only window: no pixels, but it has a queue and can be a target. */ + static MemorySegment createMessageWindow(MemorySegment className, MemorySegment instance) { + return (MemorySegment) call(Libs.CREATE_WINDOW, 0, className, MemorySegment.NULL, 0, + 0, 0, 0, 0, MemorySegment.ofAddress(HWND_MESSAGE), + MemorySegment.NULL, instance, MemorySegment.NULL); + } + + static void destroyWindow(MemorySegment window) { + call(Libs.DESTROY_WINDOW, window); + } + + static long defWindowProc(MemorySegment window, int message, long wParam, long lParam) { + return (long) call(Libs.DEF_WINDOW_PROC, window, message, wParam, lParam); + } + + /** @return 1 for a message, 0 for {@code WM_QUIT}, -1 on error */ + static int getMessage(MemorySegment message) { + return (int) call(Libs.GET_MESSAGE, message, MemorySegment.NULL, 0, 0); + } + + static void dispatchMessage(MemorySegment message) { + call(Libs.DISPATCH_MESSAGE, message); + } + + static void postMessage(MemorySegment window, int message, long wParam, long lParam) { + call(Libs.POST_MESSAGE, window, message, wParam, lParam); + } + + static void postQuitMessage(int exitCode) { + call(Libs.POST_QUIT_MESSAGE, exitCode); + } + + /** @return whether the devices were registered for background delivery */ + static boolean registerRawInputDevices(MemorySegment devices, int count) { + return (int) call(Libs.REGISTER_RAW_INPUT, devices, count, (int) RAWINPUTDEVICE_SIZE) != 0; + } + + /** @return bytes written into {@code buffer}, or -1 on failure */ + static int getRawInputData(MemorySegment handle, MemorySegment buffer, MemorySegment size) { + return (int) call(Libs.GET_RAW_INPUT_DATA, handle, RID_INPUT, buffer, size, + (int) RawInput.HEADER_SIZE); + } + + /** + * The layout's name for a key. + * + * @param lParam scan code in bits 16..23, the extended flag in bit 24, as the API wants + */ + static String keyName(int lParam, Arena arena) { + MemorySegment buffer = arena.allocate(128); + int length = (int) call(Libs.GET_KEY_NAME_TEXT, lParam, buffer, 64); + if (length <= 0) return null; + return buffer.getString(0, StandardCharsets.UTF_16LE); + } + + private static Object call(MethodHandle handle, Object... args) { + try { + return handle.invokeWithArguments(args); + } catch (Throwable t) { + throw new IllegalStateException("Win32 call failed", t); + } + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/WindowsInputHook.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/WindowsInputHook.java new file mode 100644 index 0000000..cc2d6c1 --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/WindowsInputHook.java @@ -0,0 +1,234 @@ +package eu.lixko.ts3j.client.hotkey.desktop; + +import eu.lixko.ts3j.client.hotkey.GlobalInputHook; +import eu.lixko.ts3j.client.hotkey.HotkeyKey; + +import java.lang.foreign.Arena; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.ValueLayout; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * System-wide input hook for Windows, built on raw input: a message-only window + * registers the keyboard and mouse with {@code RIDEV_INPUTSINK}, so every key and button + * on the machine arrives as {@code WM_INPUT} whether or not this application is in front, + * and the event still reaches the foreground window untouched. + * + *

    Chosen over a {@code WH_KEYBOARD_LL} hook because raw input only observes: it cannot + * swallow a keystroke, it does not put this process in the path of the system input queue + * — where a slow callback stalls typing everywhere — and it reports the side buttons and + * both edges of every key, which push-to-talk needs. + * + *

    A window's messages belong to the thread that created it, so the window is created + * on the pump thread and {@link #start} waits to hear whether that succeeded. + */ +public final class WindowsInputHook implements GlobalInputHook { + + private static final String WINDOW_CLASS = "Ts3jHotkeyInputSink"; + + /** How long to wait for the pump thread to stand its window up before giving up. */ + private static final long STARTUP_TIMEOUT_SECONDS = 5; + + private static final MethodHandle WND_PROC; + + static { + try { + WND_PROC = MethodHandles.lookup().findStatic(WindowsInputHook.class, "onMessage", + MethodType.methodType(long.class, MemorySegment.class, int.class, + long.class, long.class)); + } catch (ReflectiveOperationException e) { + throw new ExceptionInInitializerError(e); + } + } + + /** The running hook, for the static window procedure to find its way back. */ + private static volatile WindowsInputHook current; + + private volatile MemorySegment window = MemorySegment.NULL; + private Thread thread; + private volatile Listener listener; + private volatile boolean running; + private volatile String unavailable = "not started"; + + public static boolean isSupported() { + return Win32.isAvailable(); + } + + @Override + public void start(Listener listener) { + this.listener = listener; + CountDownLatch ready = new CountDownLatch(1); + thread = new Thread(() -> pump(ready), "ts3j-hotkeys-rawinput"); + thread.setDaemon(true); + thread.start(); + try { + if (!ready.await(STARTUP_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + unavailable = "the raw input window did not come up"; + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + unavailable = "interrupted while starting"; + } + } + + /** Owns the window for its whole life: creates it, pumps it, tears it down. */ + private void pump(CountDownLatch ready) { + boolean signalled = false; + try (Arena arena = Arena.ofConfined()) { + MemorySegment className = Win32.wide(arena, WINDOW_CLASS); + MemorySegment instance = Win32.moduleHandle(); + MemorySegment stub = java.lang.foreign.Linker.nativeLinker() + .upcallStub(WND_PROC, Win32.WND_PROC, arena); + + MemorySegment wndClass = arena.allocate(Win32.WNDCLASS_SIZE); + wndClass.set(ValueLayout.JAVA_INT, Win32.WNDCLASS_CBSIZE, (int) Win32.WNDCLASS_SIZE); + wndClass.set(ValueLayout.ADDRESS, Win32.WNDCLASS_WNDPROC, stub); + wndClass.set(ValueLayout.ADDRESS, Win32.WNDCLASS_HINSTANCE, instance); + wndClass.set(ValueLayout.ADDRESS, Win32.WNDCLASS_CLASSNAME, className); + // A leftover registration from an earlier run in this process is harmless: + // CreateWindowEx only needs the class to exist. + Win32.registerClass(wndClass); + + MemorySegment hwnd = Win32.createMessageWindow(className, instance); + if (hwnd.equals(MemorySegment.NULL)) { + unavailable = "cannot create the raw input window"; + return; + } + window = hwnd; + + if (!Win32.registerRawInputDevices(rawInputDevices(arena, hwnd), 2)) { + unavailable = "RegisterRawInputDevices failed"; + Win32.destroyWindow(hwnd); + window = MemorySegment.NULL; + return; + } + + current = this; + running = true; + unavailable = ""; + ready.countDown(); + signalled = true; + + MemorySegment message = arena.allocate(Win32.MSG_SIZE); + while (running) { + int result = Win32.getMessage(message); + // 0 is WM_QUIT, -1 an error; either way the window is finished. + if (result <= 0) break; + Win32.dispatchMessage(message); + } + } catch (Throwable t) { + unavailable = describe(t); + } finally { + running = false; + window = MemorySegment.NULL; + if (current == this) current = null; + if (!signalled) ready.countDown(); + } + } + + /** The keyboard and the mouse, both asked for in the background. */ + private static MemorySegment rawInputDevices(Arena arena, MemorySegment hwnd) { + MemorySegment devices = arena.allocate(Win32.RAWINPUTDEVICE_SIZE * 2); + int[] usages = {Win32.USAGE_KEYBOARD, Win32.USAGE_MOUSE}; + for (int i = 0; i < usages.length; i++) { + long base = i * Win32.RAWINPUTDEVICE_SIZE; + devices.set(ValueLayout.JAVA_SHORT, base + Win32.RAWINPUTDEVICE_USAGE_PAGE, + (short) Win32.USAGE_PAGE_GENERIC); + devices.set(ValueLayout.JAVA_SHORT, base + Win32.RAWINPUTDEVICE_USAGE, + (short) usages[i]); + devices.set(ValueLayout.JAVA_INT, base + Win32.RAWINPUTDEVICE_FLAGS, + Win32.RIDEV_INPUTSINK); + devices.set(ValueLayout.ADDRESS, base + Win32.RAWINPUTDEVICE_TARGET, hwnd); + } + return devices; + } + + /** Upcall target: the window procedure. */ + @SuppressWarnings("unused") + private static long onMessage(MemorySegment hwnd, int message, long wParam, long lParam) { + WindowsInputHook hook = current; + try { + if (message == Win32.WM_INPUT && hook != null) { + hook.readInput(lParam); + } else if (message == Win32.WM_DESTROY) { + Win32.postQuitMessage(0); + return 0; + } + } catch (Throwable ignored) { + } + // WM_INPUT must reach DefWindowProc too, so the system can release the event. + return Win32.defWindowProc(hwnd, message, wParam, lParam); + } + + /** Copies one {@code RAWINPUT} out of the system and turns it into hotkey events. */ + private void readInput(long handle) { + Listener l = listener; + if (l == null) return; + try (Arena arena = Arena.ofConfined()) { + MemorySegment buffer = arena.allocate(RawInput.BUFFER_SIZE); + MemorySegment size = arena.allocate(ValueLayout.JAVA_INT); + size.set(ValueLayout.JAVA_INT, 0, (int) RawInput.BUFFER_SIZE); + if (Win32.getRawInputData(MemorySegment.ofAddress(handle), buffer, size) <= 0) return; + + switch (buffer.get(ValueLayout.JAVA_INT, RawInput.HEADER_TYPE)) { + case RawInput.TYPE_KEYBOARD -> { + int makeCode = buffer.get(ValueLayout.JAVA_SHORT, RawInput.KEYBOARD_MAKE_CODE) & 0xFFFF; + int flags = buffer.get(ValueLayout.JAVA_SHORT, RawInput.KEYBOARD_FLAGS) & 0xFFFF; + int vkey = buffer.get(ValueLayout.JAVA_SHORT, RawInput.KEYBOARD_VKEY) & 0xFFFF; + int code = RawInput.scanCode(makeCode, flags, vkey); + if (code >= 0) l.onInput(HotkeyKey.keyboard(code), !RawInput.isRelease(flags)); + } + case RawInput.TYPE_MOUSE -> { + int flags = buffer.get(ValueLayout.JAVA_SHORT, RawInput.MOUSE_BUTTON_FLAGS) & 0xFFFF; + short data = buffer.get(ValueLayout.JAVA_SHORT, RawInput.MOUSE_BUTTON_FLAGS + 2); + for (RawInput.ButtonEvent e : RawInput.buttons(flags, data)) { + l.onInput(e.key(), e.pressed()); + } + } + default -> { + } + } + } catch (Throwable ignored) { + } + } + + @Override + public boolean isRunning() { + return running; + } + + @Override + public String unavailableReason() { + return running ? "" : unavailable; + } + + @Override + public String keyName(HotkeyKey key) { + return WindowsKeyNamer.name(key); + } + + @Override + public void close() { + listener = null; + running = false; + MemorySegment hwnd = window; + try { + // Closing has to happen on the pump thread; ask it to, then let it unwind. + if (!hwnd.equals(MemorySegment.NULL)) Win32.postMessage(hwnd, Win32.WM_CLOSE, 0, 0); + if (thread != null) thread.join(2000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (Throwable ignored) { + } + thread = null; + } + + private static String describe(Throwable t) { + String message = t.getMessage(); + return (message == null || message.isBlank()) ? t.getClass().getSimpleName() : message; + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/WindowsKeyNamer.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/WindowsKeyNamer.java new file mode 100644 index 0000000..8781430 --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/WindowsKeyNamer.java @@ -0,0 +1,37 @@ +package eu.lixko.ts3j.client.hotkey.desktop; + +import eu.lixko.ts3j.client.hotkey.HotkeyKey; + +import java.lang.foreign.Arena; +import java.util.HashMap; +import java.util.Map; + +/** + * Names scan codes through the active Windows layout, so a hotkey button shows "A" + * rather than "Key 30" — the counterpart to {@link X11KeyNamer}. + * + *

    {@code GetKeyNameTextW} wants the scan code where a {@code WM_KEYDOWN} would carry + * it: bits 16..23, with bit 24 marking the {@code E0} escape. + */ +final class WindowsKeyNamer { + + private WindowsKeyNamer() { + } + + private static final Map CACHE = new HashMap<>(); + + static synchronized String name(HotkeyKey key) { + if (key.device() != HotkeyKey.Device.KEYBOARD) return null; + if (!Win32.isAvailable()) return null; + return CACHE.computeIfAbsent(key.code(), code -> { + try (Arena arena = Arena.ofConfined()) { + int lParam = (code & 0xFF) << 16; + if ((code & 0xE000) == 0xE000) lParam |= 1 << 24; + String name = Win32.keyName(lParam, arena); + return (name == null || name.isBlank()) ? null : name; + } catch (Throwable t) { + return null; + } + }); + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/X11KeyNamer.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/X11KeyNamer.java new file mode 100644 index 0000000..532b86a --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/X11KeyNamer.java @@ -0,0 +1,47 @@ +package eu.lixko.ts3j.client.hotkey.desktop; + +import eu.lixko.ts3j.client.hotkey.HotkeyKey; + +import java.lang.foreign.MemorySegment; +import java.util.HashMap; +import java.util.Map; + +/** + * Names keycodes using the X keyboard layout, so a hotkey button shows "A" rather than + * "Key 38". Bindings themselves stay layout-independent; only the label comes from here. + * + *

    Keeps one long-lived display connection of its own, opened on first use, so it can + * be asked from any thread without racing the input hooks' own connections. + */ +final class X11KeyNamer { + + private X11KeyNamer() { + } + + private static final Map CACHE = new HashMap<>(); + private static MemorySegment display; + private static boolean tried; + + static synchronized String name(HotkeyKey key) { + if (key.device() != HotkeyKey.Device.KEYBOARD) return null; + if (!tried) { + tried = true; + try { + if (Xlib.isCoreAvailable() && System.getenv("DISPLAY") != null) { + display = Xlib.openDisplay(); + } + } catch (Throwable ignored) { + display = null; + } + } + if (display == null || display.equals(MemorySegment.NULL)) return null; + return CACHE.computeIfAbsent(key.code(), code -> { + try { + long sym = Xlib.keysym(display, code); + return sym == 0 ? null : KeyNames.pretty(Xlib.keysymName(sym)); + } catch (Throwable t) { + return null; + } + }); + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/XInput2InputHook.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/XInput2InputHook.java new file mode 100644 index 0000000..c9290a1 --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/XInput2InputHook.java @@ -0,0 +1,206 @@ +package eu.lixko.ts3j.client.hotkey.desktop; + +import eu.lixko.ts3j.client.hotkey.GlobalInputHook; +import eu.lixko.ts3j.client.hotkey.HotkeyKey; + +import java.lang.foreign.Arena; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.ValueLayout; + +/** + * System-wide input hook built on XInput2 raw events, the way TeamSpeak's own Linux + * client does it: {@code XI_RawKeyPress} and friends are selected on the root window, so + * every key and button on the machine arrives here regardless of which window has focus, + * and the event still reaches that window untouched. + * + *

    Raw events report the device's own view of the key, before focus routing and before + * any layout mapping, which is precisely what a hotkey wants — the detail field is the + * keycode, matching how {@link HotkeyKey} identifies keys. + * + *

    On at least some driver stacks, {@code XI_RawButtonRelease} is never delivered here + * at all: the X server hands the initiating {@code XI_RawButtonPress} to every raw + * listener, but the matching release only reaches whichever client holds the pointer's + * implicit per-click grab, which is never us. An active {@code XIGrabDevice} grab makes + * this hook that owner and does fix delivery, but even with {@code owner_events} set it + * stopped clicks from reaching other windows at all — worse than the bug it fixes — so it + * is not used here. {@link XRecordInputHook} is unaffected and takes over first on X11 as + * a result; this hook stays as its fallback for servers without RECORD. + * + *

    Under Wayland this hook lives inside Xwayland and therefore sees what Xwayland is + * given: every X11 client, plus — on compositors that allow it, KWin's "legacy X11 app + * support" among them — keys aimed at native Wayland windows too. Where the compositor + * forwards nothing, {@link EvdevInputHook} is the way out. + */ +public final class XInput2InputHook implements GlobalInputHook { + + /** How long the event loop sleeps on the socket before rechecking {@link #running}. */ + private static final int POLL_TIMEOUT_MILLIS = 200; + + private Arena arena; + private MemorySegment display = MemorySegment.NULL; + private int opcode = -1; + private Thread thread; + private volatile Listener listener; + private volatile boolean running; + private volatile String unavailable = "not started"; + + public static boolean isSupported() { + return Xlib.isInputAvailable() && System.getenv("DISPLAY") != null; + } + + @Override + public void start(Listener listener) { + this.listener = listener; + try { + open(); + } catch (Throwable t) { + unavailable = describe(t); + closeQuietly(); + } + } + + private void open() { + arena = Arena.ofShared(); + display = Xlib.openDisplay(); + if (display.equals(MemorySegment.NULL)) { + throw new IllegalStateException("cannot open the X display"); + } + opcode = Xlib.queryExtension(display, "XInputExtension", arena); + if (opcode < 0) throw new IllegalStateException("the X server has no XInput extension"); + if (!Xlib.queryInputVersion(display, arena)) { + throw new IllegalStateException("the X server does not speak XInput 2"); + } + + long root = Xlib.defaultRootWindow(display); + int maskLen = maskLen(); + MemorySegment bits = rawMaskBits(maskLen); + int[] masters = Xlib.queryMasterDeviceIds(display, arena); + Xlib.selectInputEvents(display, root, masters, bits, maskLen, arena); + Xlib.sync(display); + + running = true; + unavailable = ""; + thread = new Thread(this::pump, "ts3j-hotkeys-xinput2"); + thread.setDaemon(true); + thread.start(); + } + + private static int maskLen() { + // XIMaskLen(event): the byte length of a mask covering event types up to this one. + return (Xlib.XI_RAW_BUTTON_RELEASE >> 3) + 1; + } + + /** The four raw event types, as a byte mask in {@code XISetMask} order. */ + private MemorySegment rawMaskBits(int maskLen) { + MemorySegment bits = arena.allocate(maskLen); + for (int type : new int[]{Xlib.XI_RAW_KEY_PRESS, Xlib.XI_RAW_KEY_RELEASE, + Xlib.XI_RAW_BUTTON_PRESS, Xlib.XI_RAW_BUTTON_RELEASE}) { + long index = type / 8; + byte bit = (byte) (1 << (type % 8)); + bits.set(ValueLayout.JAVA_BYTE, index, + (byte) (bits.get(ValueLayout.JAVA_BYTE, index) | bit)); + } + return bits; + } + + private void pump() { + try (Arena loop = Arena.ofConfined()) { + MemorySegment event = loop.allocate(Xlib.EVENT_SIZE); + MemorySegment pollFd = Xlib.pollFd(display, loop); + while (running) { + if (Xlib.pending(display) <= 0) { + Xlib.awaitEvent(pollFd, POLL_TIMEOUT_MILLIS); + continue; + } + Xlib.nextEvent(display, event); + handle(event); + } + } catch (Throwable t) { + unavailable = describe(t); + } finally { + running = false; + } + } + + /** Unpacks one event, which is ours only when it is a generic event from XInput2. */ + private void handle(MemorySegment event) { + if (event.get(ValueLayout.JAVA_INT, Xlib.COOKIE_TYPE) != Xlib.GENERIC_EVENT) return; + if (event.get(ValueLayout.JAVA_INT, Xlib.COOKIE_EXTENSION) != opcode) return; + if (!Xlib.getEventData(display, event)) return; + try { + int evtype = event.get(ValueLayout.JAVA_INT, Xlib.COOKIE_EVTYPE); + MemorySegment raw = event.get(ValueLayout.ADDRESS, Xlib.COOKIE_DATA); + if (raw.equals(MemorySegment.NULL)) return; + int detail = raw.reinterpret(Xlib.RAW_EVENT_SIZE) + .get(ValueLayout.JAVA_INT, Xlib.RAW_EVENT_DETAIL); + dispatch(evtype, detail); + } finally { + Xlib.freeEventData(display, event); + } + } + + private void dispatch(int evtype, int detail) { + Listener l = listener; + if (l == null) return; + switch (evtype) { + case Xlib.XI_RAW_KEY_PRESS -> l.onInput(HotkeyKey.keyboard(detail), true); + case Xlib.XI_RAW_KEY_RELEASE -> l.onInput(HotkeyKey.keyboard(detail), false); + case Xlib.XI_RAW_BUTTON_PRESS -> l.onInput(HotkeyKey.mouse(detail), true); + case Xlib.XI_RAW_BUTTON_RELEASE -> l.onInput(HotkeyKey.mouse(detail), false); + default -> { + } + } + } + + @Override + public boolean isRunning() { + return running; + } + + @Override + public String unavailableReason() { + return running ? "" : unavailable; + } + + @Override + public String keyName(HotkeyKey key) { + return X11KeyNamer.name(key); + } + + @Override + public void close() { + listener = null; + running = false; + try { + if (thread != null) thread.join(POLL_TIMEOUT_MILLIS * 5L); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + closeQuietly(); + } + + private synchronized void closeQuietly() { + // The pump owns the display connection; closing it underneath would crash Xlib. + boolean pumpDone = thread == null || !thread.isAlive(); + if (pumpDone) { + try { + if (!display.equals(MemorySegment.NULL)) Xlib.closeDisplay(display); + } catch (Throwable ignored) { + } + display = MemorySegment.NULL; + if (arena != null) { + try { + arena.close(); + } catch (Throwable ignored) { + } + arena = null; + } + thread = null; + } + } + + private static String describe(Throwable t) { + String message = t.getMessage(); + return (message == null || message.isBlank()) ? t.getClass().getSimpleName() : message; + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/XRecordInputHook.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/XRecordInputHook.java new file mode 100644 index 0000000..446e442 --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/XRecordInputHook.java @@ -0,0 +1,212 @@ +package eu.lixko.ts3j.client.hotkey.desktop; + +import eu.lixko.ts3j.client.hotkey.GlobalInputHook; +import eu.lixko.ts3j.client.hotkey.HotkeyKey; + +import java.lang.foreign.Arena; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.ValueLayout; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; + +/** + * System-wide input hook built on X11's RECORD extension: it taps the core key and + * button events the server delivers to every client, so hotkeys work no matter which + * window has focus, and the keystroke still reaches that window untouched. + * + *

    Two connections are needed, as RECORD demands: a control one that creates and + * later tears the context down, and a data one that blocks inside + * {@code XRecordEnableContext} handing us events. + * + *

    Under Wayland the X server only ever sees events aimed at X clients, so this hook + * is not truly global there; {@link EvdevInputHook} is the way out. + */ +public final class XRecordInputHook implements GlobalInputHook { + + private static final MethodHandle CALLBACK; + + static { + try { + CALLBACK = MethodHandles.lookup().findStatic(XRecordInputHook.class, "onRecorded", + MethodType.methodType(void.class, MemorySegment.class, MemorySegment.class)); + } catch (ReflectiveOperationException e) { + throw new ExceptionInInitializerError(e); + } + } + + /** The running hook, for the static upcall to find its way back. */ + private static volatile XRecordInputHook current; + + private Arena arena; + private MemorySegment control = MemorySegment.NULL; + private MemorySegment data = MemorySegment.NULL; + private long context; + private Thread thread; + private volatile Listener listener; + private volatile boolean running; + private volatile String unavailable = "not started"; + + public static boolean isSupported() { + return Xlib.isAvailable() && System.getenv("DISPLAY") != null; + } + + @Override + public void start(Listener listener) { + this.listener = listener; + try { + open(); + } catch (Throwable t) { + unavailable = describe(t); + closeQuietly(); + } + } + + private void open() { + arena = Arena.ofShared(); + control = Xlib.openDisplay(); + if (control.equals(MemorySegment.NULL)) { + throw new IllegalStateException("cannot open the X display"); + } + if (!Xlib.queryRecordVersion(control, arena)) { + throw new IllegalStateException("the X server has no RECORD extension"); + } + + MemorySegment range = Xlib.allocRange(); + if (range.equals(MemorySegment.NULL)) throw new IllegalStateException("XRecordAllocRange failed"); + MemorySegment r = range.reinterpret(64); + r.set(ValueLayout.JAVA_BYTE, Xlib.RANGE_DEVICE_EVENTS_FIRST, (byte) Xlib.KEY_PRESS); + r.set(ValueLayout.JAVA_BYTE, Xlib.RANGE_DEVICE_EVENTS_LAST, (byte) Xlib.BUTTON_RELEASE); + + MemorySegment clients = arena.allocate(ValueLayout.JAVA_LONG); + clients.set(ValueLayout.JAVA_LONG, 0, Xlib.ALL_CLIENTS); + MemorySegment ranges = arena.allocate(ValueLayout.ADDRESS); + ranges.set(ValueLayout.ADDRESS, 0, range); + + context = Xlib.createContext(control, clients, 1, ranges, 1); + if (context == 0) throw new IllegalStateException("XRecordCreateContext failed"); + // The context id is allocated client-side and the request is not a round trip: + // without this the second connection can enable a context the server has yet to + // create, which it answers with BadContext. + Xlib.sync(control); + + data = Xlib.openDisplay(); + if (data.equals(MemorySegment.NULL)) { + throw new IllegalStateException("cannot open the second X display connection"); + } + + MemorySegment stub = java.lang.foreign.Linker.nativeLinker() + .upcallStub(CALLBACK, Xlib.INTERCEPT_PROC, arena); + + current = this; + running = true; + unavailable = ""; + thread = new Thread(() -> { + try { + // Blocks until close() disables the context from the control connection. + Xlib.enableContext(data, context, stub); + } catch (Throwable ignored) { + } finally { + running = false; + } + }, "ts3j-hotkeys-xrecord"); + thread.setDaemon(true); + thread.start(); + } + + /** Upcall target: one recorded protocol datum. */ + @SuppressWarnings("unused") + private static void onRecorded(MemorySegment closure, MemorySegment recorded) { + XRecordInputHook hook = current; + MemorySegment d = recorded.reinterpret(48); + try { + if (hook == null || d.get(ValueLayout.JAVA_INT, Xlib.INTERCEPT_CATEGORY) != Xlib.FROM_SERVER) { + return; + } + long length = d.get(ValueLayout.JAVA_LONG, Xlib.INTERCEPT_DATA_LEN); + MemorySegment event = d.get(ValueLayout.ADDRESS, Xlib.INTERCEPT_DATA); + // data_len counts 4-byte units; a core event is always 32 bytes. + if (event.equals(MemorySegment.NULL) || length < 2) return; + event = event.reinterpret(32); + hook.dispatch(event.get(ValueLayout.JAVA_BYTE, 0) & 0x7f, + event.get(ValueLayout.JAVA_BYTE, 1) & 0xff); + } catch (Throwable ignored) { + } finally { + Xlib.freeData(recorded); + } + } + + private void dispatch(int type, int detail) { + Listener l = listener; + if (l == null) return; + switch (type) { + case Xlib.KEY_PRESS -> l.onInput(HotkeyKey.keyboard(detail), true); + case Xlib.KEY_RELEASE -> l.onInput(HotkeyKey.keyboard(detail), false); + case Xlib.BUTTON_PRESS -> l.onInput(HotkeyKey.mouse(detail), true); + case Xlib.BUTTON_RELEASE -> l.onInput(HotkeyKey.mouse(detail), false); + default -> { + } + } + } + + @Override + public boolean isRunning() { + return running; + } + + @Override + public String unavailableReason() { + return running ? "" : unavailable; + } + + @Override + public String keyName(HotkeyKey key) { + return X11KeyNamer.name(key); + } + + @Override + public void close() { + listener = null; + running = false; + try { + if (!control.equals(MemorySegment.NULL) && context != 0) { + Xlib.disableContext(control, context); + Xlib.flush(control); + } + if (thread != null) thread.join(1000); + } catch (Throwable ignored) { + } + closeQuietly(); + } + + private synchronized void closeQuietly() { + if (current == this) current = null; + try { + if (!control.equals(MemorySegment.NULL) && context != 0) Xlib.freeContext(control, context); + } catch (Throwable ignored) { + } + context = 0; + for (MemorySegment display : new MemorySegment[]{data, control}) { + try { + if (!display.equals(MemorySegment.NULL)) Xlib.closeDisplay(display); + } catch (Throwable ignored) { + } + } + data = control = MemorySegment.NULL; + // The arena owns the upcall stub: freeing it while the recording thread could + // still call into it would take the JVM down, so a stuck thread keeps it alive. + if (arena != null && (thread == null || !thread.isAlive())) { + try { + arena.close(); + } catch (Throwable ignored) { + } + arena = null; + } + thread = null; + } + + private static String describe(Throwable t) { + String message = t.getMessage(); + return (message == null || message.isBlank()) ? t.getClass().getSimpleName() : message; + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/Xlib.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/Xlib.java new file mode 100644 index 0000000..7dbfaeb --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/hotkey/desktop/Xlib.java @@ -0,0 +1,400 @@ +package eu.lixko.ts3j.client.hotkey.desktop; + +import java.lang.foreign.Arena; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.Linker; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.SymbolLookup; +import java.lang.foreign.ValueLayout; +import java.lang.invoke.MethodHandle; +import java.nio.charset.StandardCharsets; + +/** + * Raw binding to {@code libX11}, the XInput2 extension in {@code libXi} and the RECORD + * extension in {@code libXtst}, with just the calls the X11 hooks need. + * + *

    Both extensions let a client watch input the server delivers to everyone else + * without intercepting it, which is exactly what a global hotkey needs: the keystroke + * still reaches the focused application. See {@link DesktopInputHooks#addX11Hooks} for + * which one is preferred and why. + * + *

    Each library loads lazily and failure is expected — with no X11 around, the + * {@code is*Available()} probes return {@code false} and the caller falls back to + * another backend. + */ +final class Xlib { + + private Xlib() { + } + + static final ValueLayout.OfInt INT = ValueLayout.JAVA_INT; + static final ValueLayout.OfLong LONG = ValueLayout.JAVA_LONG; + private static final java.lang.foreign.AddressLayout PTR = ValueLayout.ADDRESS; + + /** Core event types (X.h) as they appear in the recorded protocol data. */ + static final int KEY_PRESS = 2; + static final int KEY_RELEASE = 3; + static final int BUTTON_PRESS = 4; + static final int BUTTON_RELEASE = 5; + + /** {@code XRecordAllClients}: record every client, present and future. */ + static final long ALL_CLIENTS = 3L; + + /** {@code XRecordInterceptData.category} values we care about. */ + static final int FROM_SERVER = 0; + + /** + * {@code XRecordRange}: only {@code device_events} is filled in. Its two bytes sit + * after the request/reply and delivered-event ranges, at a fixed LP64 offset. + */ + static final long RANGE_DEVICE_EVENTS_FIRST = 18; + static final long RANGE_DEVICE_EVENTS_LAST = 19; + + /** {@code XRecordInterceptData}: the protocol bytes and the reason we were called. */ + static final long INTERCEPT_CATEGORY = 24; + static final long INTERCEPT_DATA = 32; + static final long INTERCEPT_DATA_LEN = 40; + + /** {@code GenericEvent}, the envelope every extension event arrives in. */ + static final int GENERIC_EVENT = 35; + + /** XInput2 raw event types (XI2.h): the device's own view, before any focus routing. */ + static final int XI_RAW_KEY_PRESS = 13; + static final int XI_RAW_KEY_RELEASE = 14; + static final int XI_RAW_BUTTON_PRESS = 15; + static final int XI_RAW_BUTTON_RELEASE = 16; + + /** {@code XIAllMasterDevices}: raw events reach us through the master devices. */ + static final int XI_ALL_MASTER_DEVICES = 1; + + /** An {@code XEvent} is a union of 24 longs; a cookie is the widest member we read. */ + static final long EVENT_SIZE = 192; + + /** {@code XGenericEventCookie} field offsets under LP64. */ + static final long COOKIE_TYPE = 0; + static final long COOKIE_EXTENSION = 32; + static final long COOKIE_EVTYPE = 36; + static final long COOKIE_DATA = 48; + + /** + * {@code XIRawEvent.detail} — the keycode or button number — past the generic header, + * {@code time}, {@code deviceid} and {@code sourceid}. + */ + static final long RAW_EVENT_DETAIL = 56; + static final long RAW_EVENT_SIZE = 152; + + /** {@code XIEventMask}: {@code deviceid}, {@code mask_len}, then the mask pointer. */ + static final long EVENT_MASK_SIZE = 16; + static final long EVENT_MASK_DEVICEID = 0; + static final long EVENT_MASK_LEN = 4; + static final long EVENT_MASK_MASK = 8; + + /** {@code XIDeviceInfo.deviceid} — the only field {@link #queryMasterDeviceIds} needs. */ + static final long DEVICE_INFO_SIZE = 40; + static final long DEVICE_INFO_DEVICEID = 0; + + private static final Linker LINKER = Linker.nativeLinker(); + private static final String[] X11_NAMES = {"libX11.so.6", "libX11.so"}; + private static final String[] XI_NAMES = {"libXi.so.6", "libXi.so"}; + private static final String[] XTST_NAMES = {"libXtst.so.6", "libXtst.so"}; + + /** libX11 alone: enough to open a display and name keys. */ + private static final class Core { + static final SymbolLookup LIB = load(X11_NAMES, "libX11"); + + static final MethodHandle X_OPEN_DISPLAY = + downcall(LIB, "XOpenDisplay", FunctionDescriptor.of(PTR, PTR)); + static final MethodHandle X_CLOSE_DISPLAY = + downcall(LIB, "XCloseDisplay", FunctionDescriptor.of(INT, PTR)); + static final MethodHandle X_FLUSH = + downcall(LIB, "XFlush", FunctionDescriptor.of(INT, PTR)); + static final MethodHandle X_SYNC = + downcall(LIB, "XSync", FunctionDescriptor.of(INT, PTR, INT)); + static final MethodHandle XKB_KEYCODE_TO_KEYSYM = + downcall(LIB, "XkbKeycodeToKeysym", FunctionDescriptor.of(LONG, PTR, INT, INT, INT)); + static final MethodHandle X_KEYSYM_TO_STRING = + downcall(LIB, "XKeysymToString", FunctionDescriptor.of(PTR, LONG)); + static final MethodHandle X_QUERY_EXTENSION = + downcall(LIB, "XQueryExtension", FunctionDescriptor.of(INT, PTR, PTR, PTR, PTR, PTR)); + static final MethodHandle X_DEFAULT_ROOT_WINDOW = + downcall(LIB, "XDefaultRootWindow", FunctionDescriptor.of(LONG, PTR)); + static final MethodHandle X_CONNECTION_NUMBER = + downcall(LIB, "XConnectionNumber", FunctionDescriptor.of(INT, PTR)); + static final MethodHandle X_PENDING = + downcall(LIB, "XPending", FunctionDescriptor.of(INT, PTR)); + static final MethodHandle X_NEXT_EVENT = + downcall(LIB, "XNextEvent", FunctionDescriptor.of(INT, PTR, PTR)); + static final MethodHandle X_GET_EVENT_DATA = + downcall(LIB, "XGetEventData", FunctionDescriptor.of(INT, PTR, PTR)); + static final MethodHandle X_FREE_EVENT_DATA = + downcall(LIB, "XFreeEventData", FunctionDescriptor.ofVoid(PTR, PTR)); + } + + /** XInput2, which ships separately in libXi. */ + private static final class Input { + static final SymbolLookup LIB = load(XI_NAMES, "libXi"); + + static final MethodHandle XI_QUERY_VERSION = + downcall(LIB, "XIQueryVersion", FunctionDescriptor.of(INT, PTR, PTR, PTR)); + static final MethodHandle XI_SELECT_EVENTS = + downcall(LIB, "XISelectEvents", FunctionDescriptor.of(INT, PTR, LONG, PTR, INT)); + static final MethodHandle XI_QUERY_DEVICE = + downcall(LIB, "XIQueryDevice", FunctionDescriptor.of(PTR, PTR, INT, PTR)); + static final MethodHandle XI_FREE_DEVICE_INFO = + downcall(LIB, "XIFreeDeviceInfo", FunctionDescriptor.ofVoid(PTR)); + } + + /** {@code poll(2)}, so the event loop can wait on the X socket and still be woken. */ + private static final class Poll { + static final MethodHandle POLL = LINKER.downcallHandle( + LINKER.defaultLookup().find("poll").orElseThrow(() -> + new UnsatisfiedLinkError("unresolved symbol poll")), + FunctionDescriptor.of(INT, PTR, LONG, INT)); + } + + /** {@code struct pollfd} is an int and two shorts, and {@code POLLIN} is bit 0. */ + private static final long POLLFD_SIZE = 8; + private static final long POLLFD_EVENTS = 4; + private static final short POLLIN = 1; + + /** The RECORD extension, which ships separately in libXtst. */ + private static final class Record { + static final SymbolLookup LIB = load(XTST_NAMES, "libXtst"); + + static final MethodHandle QUERY_VERSION = + downcall(LIB, "XRecordQueryVersion", FunctionDescriptor.of(INT, PTR, PTR, PTR)); + static final MethodHandle ALLOC_RANGE = + downcall(LIB, "XRecordAllocRange", FunctionDescriptor.of(PTR)); + static final MethodHandle CREATE_CONTEXT = + downcall(LIB, "XRecordCreateContext", + FunctionDescriptor.of(LONG, PTR, INT, PTR, INT, PTR, INT)); + static final MethodHandle ENABLE_CONTEXT = + downcall(LIB, "XRecordEnableContext", FunctionDescriptor.of(INT, PTR, LONG, PTR, PTR)); + static final MethodHandle DISABLE_CONTEXT = + downcall(LIB, "XRecordDisableContext", FunctionDescriptor.of(INT, PTR, LONG)); + static final MethodHandle FREE_CONTEXT = + downcall(LIB, "XRecordFreeContext", FunctionDescriptor.of(INT, PTR, LONG)); + static final MethodHandle FREE_DATA = + downcall(LIB, "XRecordFreeData", FunctionDescriptor.ofVoid(PTR)); + } + + private static SymbolLookup load(String[] names, String what) { + IllegalArgumentException last = null; + for (String name : names) { + try { + return SymbolLookup.libraryLookup(name, Arena.global()); + } catch (IllegalArgumentException e) { + last = e; + } + } + throw (last != null) ? last : new IllegalArgumentException(what + " not found"); + } + + private static MethodHandle downcall(SymbolLookup lookup, String symbol, + FunctionDescriptor descriptor) { + return LINKER.downcallHandle( + lookup.find(symbol).orElseThrow(() -> + new UnsatisfiedLinkError("unresolved symbol " + symbol)), + descriptor); + } + + /** The C signature of {@code XRecordInterceptProc}. */ + static final FunctionDescriptor INTERCEPT_PROC = FunctionDescriptor.ofVoid(PTR, PTR); + + /** Whether libX11 loaded, which is all that naming keys needs. */ + static boolean isCoreAvailable() { + try { + return Core.LIB != null; + } catch (Throwable t) { + return false; + } + } + + static boolean isAvailable() { + try { + return Core.LIB != null && Record.LIB != null; + } catch (Throwable t) { + return false; + } + } + + /** Whether libX11 and libXi both loaded, which is what the XInput2 hook needs. */ + static boolean isInputAvailable() { + try { + return Core.LIB != null && Input.LIB != null && Poll.POLL != null; + } catch (Throwable t) { + return false; + } + } + + static MemorySegment openDisplay() { + return (MemorySegment) call(Core.X_OPEN_DISPLAY, MemorySegment.NULL); + } + + static void closeDisplay(MemorySegment display) { + call(Core.X_CLOSE_DISPLAY, display); + } + + static void flush(MemorySegment display) { + call(Core.X_FLUSH, display); + } + + /** Flushes and waits for the server to have processed everything sent so far. */ + static void sync(MemorySegment display) { + call(Core.X_SYNC, display, 0); + } + + /** @return whether the server has the RECORD extension */ + static boolean queryRecordVersion(MemorySegment display, Arena arena) { + MemorySegment major = arena.allocate(INT); + MemorySegment minor = arena.allocate(INT); + return (int) call(Record.QUERY_VERSION, display, major, minor) != 0; + } + + static MemorySegment allocRange() { + return (MemorySegment) call(Record.ALLOC_RANGE); + } + + static long createContext(MemorySegment display, MemorySegment clients, int clientCount, + MemorySegment ranges, int rangeCount) { + return (long) call(Record.CREATE_CONTEXT, display, 0, clients, clientCount, ranges, rangeCount); + } + + static int enableContext(MemorySegment display, long context, MemorySegment callback) { + return (int) call(Record.ENABLE_CONTEXT, display, context, callback, MemorySegment.NULL); + } + + static void disableContext(MemorySegment display, long context) { + call(Record.DISABLE_CONTEXT, display, context); + } + + static void freeContext(MemorySegment display, long context) { + call(Record.FREE_CONTEXT, display, context); + } + + static void freeData(MemorySegment data) { + call(Record.FREE_DATA, data); + } + + /** @return the extension's major opcode, or -1 when the server does not have it */ + static int queryExtension(MemorySegment display, String name, Arena arena) { + MemorySegment opcode = arena.allocate(INT); + MemorySegment event = arena.allocate(INT); + MemorySegment error = arena.allocate(INT); + int found = (int) call(Core.X_QUERY_EXTENSION, display, arena.allocateFrom(name), + opcode, event, error); + return found != 0 ? opcode.get(INT, 0) : -1; + } + + /** @return whether the server speaks at least XInput 2.0 */ + static boolean queryInputVersion(MemorySegment display, Arena arena) { + MemorySegment major = arena.allocate(INT); + MemorySegment minor = arena.allocate(INT); + major.set(INT, 0, 2); + minor.set(INT, 0, 0); + // Success is 0; anything else means the server would not agree on 2.x. + return (int) call(Input.XI_QUERY_VERSION, display, major, minor) == 0; + } + + static long defaultRootWindow(MemorySegment display) { + return (long) call(Core.X_DEFAULT_ROOT_WINDOW, display); + } + + /** + * Asks for the events set in {@code bits} on {@code window}, once per device in + * {@code deviceIds}: selecting against {@code XIAllMasterDevices} itself does not + * reliably deliver every raw event type, so callers resolve it to real device ids first + * with {@link #queryMasterDeviceIds}. + */ + static void selectInputEvents(MemorySegment display, long window, int[] deviceIds, + MemorySegment bits, int maskLen, Arena arena) { + MemorySegment masks = arena.allocate(EVENT_MASK_SIZE * deviceIds.length); + for (int i = 0; i < deviceIds.length; i++) { + long base = i * EVENT_MASK_SIZE; + masks.set(INT, base + EVENT_MASK_DEVICEID, deviceIds[i]); + masks.set(INT, base + EVENT_MASK_LEN, maskLen); + masks.set(PTR, base + EVENT_MASK_MASK, bits); + } + call(Input.XI_SELECT_EVENTS, display, window, masks, deviceIds.length); + } + + /** + * The real device ids behind the {@code XIAllMasterDevices} pseudo-device — selecting + * raw events against each one individually, rather than the pseudo-device itself, is + * the more correct form (some drivers reportedly need it), even though it alone does + * not fix the {@code XI_RawButtonRelease} gap {@link XInput2InputHook} documents. + */ + static int[] queryMasterDeviceIds(MemorySegment display, Arena arena) { + MemorySegment count = arena.allocate(INT); + MemorySegment infos = (MemorySegment) call(Input.XI_QUERY_DEVICE, display, + XI_ALL_MASTER_DEVICES, count); + int n = count.get(INT, 0); + if (infos.equals(MemorySegment.NULL) || n <= 0) return new int[0]; + try { + MemorySegment array = infos.reinterpret(DEVICE_INFO_SIZE * n); + int[] ids = new int[n]; + for (int i = 0; i < n; i++) { + ids[i] = array.get(INT, i * DEVICE_INFO_SIZE + DEVICE_INFO_DEVICEID); + } + return ids; + } finally { + call(Input.XI_FREE_DEVICE_INFO, infos); + } + } + + static int pending(MemorySegment display) { + return (int) call(Core.X_PENDING, display); + } + + static void nextEvent(MemorySegment display, MemorySegment event) { + call(Core.X_NEXT_EVENT, display, event); + } + + /** Fetches a generic event's payload; the caller must free it when this succeeds. */ + static boolean getEventData(MemorySegment display, MemorySegment cookie) { + return (int) call(Core.X_GET_EVENT_DATA, display, cookie) != 0; + } + + static void freeEventData(MemorySegment display, MemorySegment cookie) { + call(Core.X_FREE_EVENT_DATA, display, cookie); + } + + /** + * A {@code struct pollfd} watching the display connection, to be allocated once and + * handed to {@link #awaitEvent} for the life of an event loop. + */ + static MemorySegment pollFd(MemorySegment display, Arena arena) { + MemorySegment fds = arena.allocate(POLLFD_SIZE); + fds.set(INT, 0, (int) call(Core.X_CONNECTION_NUMBER, display)); + fds.set(ValueLayout.JAVA_SHORT, POLLFD_EVENTS, POLLIN); + return fds; + } + + /** + * Waits until the connection has something to read or the timeout runs out, so an + * event loop can stay asleep yet still notice it has been asked to stop. + */ + static void awaitEvent(MemorySegment pollFd, int timeoutMillis) { + call(Poll.POLL, pollFd, 1L, timeoutMillis); + } + + /** The unshifted keysym of a keycode in the first group, or 0 when unbound. */ + static long keysym(MemorySegment display, int keycode) { + return (long) call(Core.XKB_KEYCODE_TO_KEYSYM, display, keycode, 0, 0); + } + + /** The keysym's X name ("a", "Control_L", "F5"), or {@code null}. */ + static String keysymName(long keysym) { + MemorySegment name = (MemorySegment) call(Core.X_KEYSYM_TO_STRING, keysym); + if (name == null || name.equals(MemorySegment.NULL)) return null; + return name.reinterpret(Long.MAX_VALUE).getString(0, StandardCharsets.US_ASCII); + } + + private static Object call(MethodHandle handle, Object... args) { + try { + return handle.invokeWithArguments(args); + } catch (Throwable t) { + throw new IllegalStateException("X11 call failed", t); + } + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/notify/desktop/DBusConnection.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/notify/desktop/DBusConnection.java new file mode 100644 index 0000000..e0cd769 --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/notify/desktop/DBusConnection.java @@ -0,0 +1,215 @@ +package eu.lixko.ts3j.client.notify.desktop; + +import java.io.EOFException; +import java.io.IOException; +import java.net.StandardProtocolFamily; +import java.net.UnixDomainSocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicLong; + +/** + * A connection to the user's D-Bus session bus, spoken directly over its Unix socket: + * method calls and the signals a match rule lets through, which is all a client of a + * desktop service needs. Signals and replies are read on a thread of its own. + */ +final class DBusConnection implements AutoCloseable { + + private static final String BUS = "org.freedesktop.DBus"; + private static final long CALL_TIMEOUT_MS = 3_000; + + /** A signal from the bus. */ + interface SignalHandler { + void signal(String iface, String member, List args); + } + + private final SocketChannel channel; + private final AtomicLong serials = new AtomicLong(); + private final Map>> pending = new ConcurrentHashMap<>(); + private volatile SignalHandler signals = (iface, member, args) -> { }; + private volatile boolean closed; + + private DBusConnection(SocketChannel channel) { + this.channel = channel; + } + + /** Connects to the session bus named by {@code DBUS_SESSION_BUS_ADDRESS}, or the usual socket. */ + static DBusConnection session() throws IOException { + Path socket = sessionSocket(); + if (socket == null) throw new IOException("No D-Bus session bus socket"); + SocketChannel channel = SocketChannel.open(StandardProtocolFamily.UNIX); + try { + channel.connect(UnixDomainSocketAddress.of(socket)); + authenticate(channel); + DBusConnection bus = new DBusConnection(channel); + Thread reader = new Thread(bus::readLoop, "dbus-reader"); + reader.setDaemon(true); + reader.start(); + bus.call(BUS, "/org/freedesktop/DBus", BUS, "Hello", ""); + return bus; + } catch (IOException | RuntimeException e) { + channel.close(); + throw e; + } + } + + private static Path sessionSocket() { + String address = System.getenv("DBUS_SESSION_BUS_ADDRESS"); + if (address != null) { + for (String entry : address.split(";")) { + if (!entry.startsWith("unix:")) continue; + for (String pair : entry.substring(5).split(",")) { + // An abstract socket (unix:abstract=) is out of reach of Java's Unix sockets. + if (pair.startsWith("path=")) return Path.of(unescape(pair.substring(5))); + } + } + } + String runtime = System.getenv("XDG_RUNTIME_DIR"); + if (runtime == null) return null; + Path socket = Path.of(runtime, "bus"); + return Files.exists(socket) ? socket : null; + } + + /** Undoes the %xx escaping of D-Bus addresses. */ + private static String unescape(String value) { + StringBuilder out = new StringBuilder(); + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (c == '%' && i + 2 < value.length()) { + out.append((char) Integer.parseInt(value.substring(i + 1, i + 3), 16)); + i += 2; + } else { + out.append(c); + } + } + return out.toString(); + } + + /** The EXTERNAL mechanism: the bus checks the socket's peer credentials against our uid. */ + private static void authenticate(SocketChannel channel) throws IOException { + Object uid = Files.getAttribute(Path.of("/proc/self"), "unix:uid"); + String hexUid = HexFormat.of().formatHex(uid.toString().getBytes(StandardCharsets.US_ASCII)); + write(channel, "\0AUTH EXTERNAL " + hexUid + "\r\n"); + String reply = readLine(channel); + if (!reply.startsWith("OK ")) throw new IOException("D-Bus refused authentication: " + reply); + write(channel, "BEGIN\r\n"); + } + + private static void write(SocketChannel channel, String line) throws IOException { + ByteBuffer b = ByteBuffer.wrap(line.getBytes(StandardCharsets.US_ASCII)); + while (b.hasRemaining()) channel.write(b); + } + + private static String readLine(SocketChannel channel) throws IOException { + StringBuilder line = new StringBuilder(); + ByteBuffer one = ByteBuffer.allocate(1); + while (!line.toString().endsWith("\r\n")) { + one.clear(); + if (channel.read(one) < 0) throw new EOFException("D-Bus closed during authentication"); + line.append((char) one.get(0)); + } + return line.substring(0, line.length() - 2); + } + + void onSignal(SignalHandler handler) { + this.signals = handler; + } + + /** Lets the bus route the signals a match rule describes to this connection. */ + void addMatch(String rule) throws IOException { + call(BUS, "/org/freedesktop/DBus", BUS, "AddMatch", "s", rule); + } + + /** Calls a method and waits for its reply's arguments. */ + List call(String destination, String path, String iface, String member, String signature, + Object... args) throws IOException { + long serial = serials.incrementAndGet(); + CompletableFuture> reply = new CompletableFuture<>(); + pending.put(serial, reply); + try { + byte[] message = DBusWire.methodCall(serial, destination, path, iface, member, signature, args); + synchronized (channel) { + ByteBuffer b = ByteBuffer.wrap(message); + while (b.hasRemaining()) channel.write(b); + } + return reply.get(CALL_TIMEOUT_MS, TimeUnit.MILLISECONDS); + } catch (ExecutionException e) { + throw new IOException(e.getCause().getMessage(), e.getCause()); + } catch (TimeoutException e) { + throw new IOException(member + " got no reply", e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("Interrupted", e); + } finally { + pending.remove(serial); + } + } + + private void readLoop() { + try { + ByteBuffer header = ByteBuffer.allocate(DBusWire.FIXED_HEADER); + while (!closed) { + header.clear(); + readFully(header); + ByteBuffer message = ByteBuffer.allocate(DBusWire.messageLength(header)); + message.put(header.flip()); + readFully(message); + dispatch(DBusWire.parse(message.array())); + } + } catch (IOException | RuntimeException e) { + if (!closed) System.err.println("D-Bus connection lost: " + e); + } finally { + closed = true; + pending.values().forEach(f -> f.completeExceptionally(new IOException("D-Bus connection closed"))); + } + } + + private void readFully(ByteBuffer b) throws IOException { + while (b.hasRemaining()) { + if (channel.read(b) < 0) throw new EOFException("D-Bus closed the connection"); + } + } + + private void dispatch(DBusWire.Message m) { + switch (m.type()) { + case DBusWire.METHOD_RETURN -> { + CompletableFuture> reply = pending.get(m.replySerial()); + if (reply != null) reply.complete(m.body()); + } + case DBusWire.ERROR -> { + CompletableFuture> reply = pending.get(m.replySerial()); + String detail = m.body().isEmpty() ? "" : ": " + m.body().getFirst(); + if (reply != null) reply.completeExceptionally(new IOException(m.string(DBusWire.FIELD_ERROR_NAME) + detail)); + } + case DBusWire.SIGNAL -> { + try { + signals.signal(m.string(DBusWire.FIELD_INTERFACE), m.string(DBusWire.FIELD_MEMBER), m.body()); + } catch (RuntimeException e) { + System.err.println("D-Bus signal handler failed: " + e); + } + } + default -> { } + } + } + + @Override + public void close() { + closed = true; + try { + channel.close(); + } catch (IOException ignored) { + // Nothing left to release. + } + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/notify/desktop/DBusWire.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/notify/desktop/DBusWire.java new file mode 100644 index 0000000..02da8ac --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/notify/desktop/DBusWire.java @@ -0,0 +1,322 @@ +package eu.lixko.ts3j.client.notify.desktop; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +/** + * The D-Bus wire format, for the handful of types a notification service speaks: + * basic types, arrays, structs, dictionaries and variants. + * + *

    Values map to Java as: {@code y} Integer, {@code b} Boolean, {@code i} Integer, + * {@code u} Long, {@code s o g} String, {@code a} List (or Map for a dictionary), + * a struct Object[], a variant the value it holds. + */ +final class DBusWire { + + static final int METHOD_CALL = 1; + static final int METHOD_RETURN = 2; + static final int ERROR = 3; + static final int SIGNAL = 4; + + static final int FIELD_PATH = 1; + static final int FIELD_INTERFACE = 2; + static final int FIELD_MEMBER = 3; + static final int FIELD_ERROR_NAME = 4; + static final int FIELD_REPLY_SERIAL = 5; + static final int FIELD_DESTINATION = 6; + static final int FIELD_SIGNATURE = 8; + + /** Everything before the header fields: byte order, type, flags, version and three lengths. */ + static final int FIXED_HEADER = 16; + + private DBusWire() { + } + + /** A message as read off the bus. */ + record Message(int type, long serial, Map fields, List body) { + + String string(int field) { + Object value = fields.get(field); + return value instanceof String s ? s : null; + } + + long replySerial() { + return fields.get(FIELD_REPLY_SERIAL) instanceof Long l ? l : -1; + } + } + + /** Builds a method call; the body is written after the header, aligned to 8 as the format wants. */ + static byte[] methodCall(long serial, String destination, String path, String iface, String member, + String signature, Object... args) { + Writer body = new Writer(); + body.values(signature, args); + + Writer out = new Writer(); + out.put('l'); + out.put(METHOD_CALL); + out.put(0); + out.put(1); + out.u32(body.size()); + out.u32(serial); + out.array(8, () -> { + out.field(FIELD_PATH, "o", path); + out.field(FIELD_DESTINATION, "s", destination); + out.field(FIELD_INTERFACE, "s", iface); + out.field(FIELD_MEMBER, "s", member); + if (!signature.isEmpty()) out.field(FIELD_SIGNATURE, "g", signature); + }); + out.align(8); + out.bytes(body.toBytes()); + return out.toBytes(); + } + + /** @return the length of the whole message whose fixed header this is */ + static int messageLength(ByteBuffer fixedHeader) { + ByteBuffer b = fixedHeader.duplicate().order(order(fixedHeader.get(0))); + int body = b.getInt(4); + int fields = b.getInt(12); + return pad8(FIXED_HEADER + fields) + body; + } + + static Message parse(byte[] data) { + Reader r = new Reader(ByteBuffer.wrap(data).order(order(data[0]))); + r.skip(1); + int type = r.buf.get() & 0xff; + r.skip(2); + int bodyLength = r.buf.getInt(); + long serial = Integer.toUnsignedLong(r.buf.getInt()); + + Map fields = new java.util.HashMap<>(); + for (Object field : (List) r.read("a(yv)")) { + Object[] pair = (Object[]) field; + fields.put((Integer) pair[0], pair[1]); + } + r.align(8); + String signature = fields.get(FIELD_SIGNATURE) instanceof String s ? s : ""; + List body = new ArrayList<>(); + int end = r.buf.position() + bodyLength; + for (int i = 0; i < signature.length() && r.buf.position() < end; ) { + int next = typeEnd(signature, i); + body.add(r.read(signature.substring(i, next))); + i = next; + } + return new Message(type, serial, fields, body); + } + + private static ByteOrder order(byte marker) { + return marker == 'B' ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN; + } + + private static int pad8(int n) { + return (n + 7) & ~7; + } + + /** @return the index just past the single complete type starting at {@code start} */ + static int typeEnd(String signature, int start) { + char c = signature.charAt(start); + if (c == 'a') return typeEnd(signature, start + 1); + if (c == '(' || c == '{') { + char close = c == '(' ? ')' : '}'; + int i = start + 1; + while (signature.charAt(i) != close) i = typeEnd(signature, i); + return i + 1; + } + return start + 1; + } + + static int alignment(char type) { + return switch (type) { + case 'y', 'g', 'v' -> 1; + case 'n', 'q' -> 2; + case 'x', 't', 'd', '(', '{' -> 8; + default -> 4; + }; + } + + /** Marshals values; positions count from the start of what it writes. */ + static final class Writer { + private byte[] buf = new byte[256]; + private int pos; + + int size() { + return pos; + } + + byte[] toBytes() { + return Arrays.copyOf(buf, pos); + } + + void put(int b) { + if (pos == buf.length) buf = Arrays.copyOf(buf, buf.length * 2); + buf[pos++] = (byte) b; + } + + void bytes(byte[] b) { + for (byte x : b) put(x); + } + + void align(int n) { + while (pos % n != 0) put(0); + } + + void u32(long v) { + align(4); + for (int i = 0; i < 4; i++) put((int) (v >>> (8 * i))); + } + + private void setU32(int at, long v) { + for (int i = 0; i < 4; i++) buf[at + i] = (byte) (v >>> (8 * i)); + } + + void string(String s) { + byte[] b = s.getBytes(StandardCharsets.UTF_8); + u32(b.length); + bytes(b); + put(0); + } + + void signature(String s) { + byte[] b = s.getBytes(StandardCharsets.US_ASCII); + put(b.length); + bytes(b); + put(0); + } + + /** An array; the length leaves out the padding before its first element. */ + void array(int elementAlignment, Runnable elements) { + u32(0); + int lengthAt = pos - 4; + align(elementAlignment); + int start = pos; + elements.run(); + setU32(lengthAt, pos - start); + } + + void field(int code, String signature, Object value) { + align(8); + put(code); + signature(signature); + value(signature, value); + } + + void values(String signature, Object... values) { + int v = 0; + for (int i = 0; i < signature.length(); v++) { + int next = typeEnd(signature, i); + value(signature.substring(i, next), values[v]); + i = next; + } + } + + void value(String type, Object value) { + char c = type.charAt(0); + align(alignment(c)); + switch (c) { + case 'y' -> put(((Number) value).intValue()); + case 'b' -> u32((Boolean) value ? 1 : 0); + case 'i' -> u32(((Number) value).intValue() & 0xffffffffL); + case 'u' -> u32(((Number) value).longValue()); + case 's', 'o' -> string((String) value); + case 'g' -> signature((String) value); + case 'v' -> { + String inner = variantType(value); + signature(inner); + value(inner, value); + } + case 'a' -> { + String element = type.substring(1); + array(alignment(element.charAt(0)), () -> { + if (element.charAt(0) == '{') { + String key = element.substring(1, typeEnd(element, 1)); + String val = element.substring(1 + key.length(), element.length() - 1); + for (Map.Entry e : ((Map) value).entrySet()) { + align(8); + value(key, e.getKey()); + value(val, e.getValue()); + } + } else { + for (Object item : (List) value) value(element, item); + } + }); + } + default -> throw new IllegalArgumentException("Cannot write D-Bus type " + type); + } + } + + private static String variantType(Object value) { + if (value instanceof String) return "s"; + if (value instanceof Boolean) return "b"; + if (value instanceof Byte) return "y"; + if (value instanceof Integer) return "i"; + if (value instanceof Long) return "u"; + throw new IllegalArgumentException("No D-Bus type for " + value.getClass()); + } + } + + /** Unmarshals values; alignment counts from the start of the message. */ + static final class Reader { + final ByteBuffer buf; + + Reader(ByteBuffer buf) { + this.buf = buf; + } + + void skip(int n) { + buf.position(buf.position() + n); + } + + void align(int n) { + int p = buf.position(); + buf.position((p + n - 1) / n * n); + } + + Object read(String type) { + char c = type.charAt(0); + align(alignment(c)); + return switch (c) { + case 'y' -> buf.get() & 0xff; + case 'b' -> buf.getInt() != 0; + case 'n' -> (int) buf.getShort(); + case 'q' -> buf.getShort() & 0xffff; + case 'i' -> buf.getInt(); + case 'u' -> Integer.toUnsignedLong(buf.getInt()); + case 'x', 't' -> buf.getLong(); + case 'd' -> buf.getDouble(); + case 's', 'o' -> text(buf.getInt()); + case 'g' -> text(buf.get() & 0xff); + case 'v' -> read((String) read("g")); + case 'a' -> { + int length = buf.getInt(); + String element = type.substring(1, typeEnd(type, 1)); + align(alignment(element.charAt(0))); + int end = buf.position() + length; + List items = new ArrayList<>(); + while (buf.position() < end) items.add(read(element)); + yield items; + } + case '(', '{' -> { + List members = new ArrayList<>(); + for (int i = 1; i < type.length() - 1; ) { + int next = typeEnd(type, i); + members.add(read(type.substring(i, next))); + i = next; + } + yield members.toArray(); + } + default -> throw new IllegalArgumentException("Cannot read D-Bus type " + type); + }; + } + + private String text(int length) { + byte[] b = new byte[length]; + buf.get(b); + buf.get(); // the terminating NUL + return new String(b, StandardCharsets.UTF_8); + } + } +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/notify/desktop/DesktopNotifications.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/notify/desktop/DesktopNotifications.java new file mode 100644 index 0000000..32bad76 --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/notify/desktop/DesktopNotifications.java @@ -0,0 +1,36 @@ +package eu.lixko.ts3j.client.notify.desktop; + +import java.util.function.Consumer; + +/** + * The desktop's own notifications — the ones its notification centre collects. Calls + * may block on the desktop, so they belong off the event thread; the callbacks come + * on a thread of the implementation's. + */ +public interface DesktopNotifications { + + /** + * @param title the headline, such as who a message is from + * @param body plain text + * @param onOpen run when the user clicks the notification + * @param onReply given the text typed into the notification, where {@link #canReply()}; may be {@code null} + */ + record Notice(String title, String body, Runnable onOpen, Consumer onReply) { + } + + /** + * Shows a notice, in place of an earlier one still on screen. + * + * @param replaces what an earlier call returned, or 0 + * @return the notice's id for {@link #close} and later replacement, or 0 if it could not be shown + */ + int show(Notice notice, int replaces); + + /** Takes a notice away, from the notification centre too. */ + void close(int id); + + /** Whether a notice can take a reply typed into it. */ + boolean canReply(); + + void shutdown(); +} diff --git a/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/notify/desktop/FreedesktopNotifications.java b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/notify/desktop/FreedesktopNotifications.java new file mode 100644 index 0000000..4f6b9ae --- /dev/null +++ b/ts3-client/desktop/src/main/java/eu/lixko/ts3j/client/notify/desktop/FreedesktopNotifications.java @@ -0,0 +1,126 @@ +package eu.lixko.ts3j.client.notify.desktop; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Notifications through the freedesktop.org notification service, which every Linux + * desktop (Plasma, GNOME, XFCE, a standalone daemon such as dunst) provides on the + * session bus. Plasma also takes a reply typed into the notification. + */ +public final class FreedesktopNotifications implements DesktopNotifications { + + private static final String SERVICE = "org.freedesktop.Notifications"; + private static final String PATH = "/org/freedesktop/Notifications"; + private static final String DEFAULT_ACTION = "default"; + /** Plasma's extension for a reply field in the notification. */ + private static final String REPLY_ACTION = "inline-reply"; + + private final DBusConnection bus; + private final String appName; + private final String desktopEntry; + private final String icon; + private final boolean markup; + private final boolean reply; + /** The notices on screen, by the id the service gave them. */ + private final Map shown = new ConcurrentHashMap<>(); + + /** + * @param desktopEntry the name of the application's {@code .desktop} file, without the + * extension; the desktop takes the application's name and icon from it + * @param icon an icon file, for services that do not look at the desktop entry + * @return the service, or {@code null} where there is none to reach + */ + public static FreedesktopNotifications connect(String appName, String desktopEntry, String icon) { + DBusConnection bus = null; + try { + bus = DBusConnection.session(); + List capabilities = (List) bus.call(SERVICE, PATH, SERVICE, "GetCapabilities", "").getFirst(); + bus.addMatch("type='signal',interface='" + SERVICE + "'"); + return new FreedesktopNotifications(bus, appName, desktopEntry, icon, capabilities); + } catch (IOException | RuntimeException e) { + System.err.println("Desktop notifications unavailable: " + e.getMessage()); + if (bus != null) bus.close(); + return null; + } + } + + private FreedesktopNotifications(DBusConnection bus, String appName, String desktopEntry, String icon, + List capabilities) { + this.bus = bus; + this.appName = appName; + this.desktopEntry = desktopEntry; + this.icon = icon == null ? "" : icon; + this.markup = capabilities.contains("body-markup"); + this.reply = capabilities.contains(REPLY_ACTION); + bus.onSignal(this::signal); + } + + @Override + public boolean canReply() { + return reply; + } + + @Override + public int show(Notice notice, int replaces) { + List actions = new ArrayList<>(List.of(DEFAULT_ACTION, "Open")); + if (reply && notice.onReply() != null) actions.addAll(List.of(REPLY_ACTION, "Reply")); + Map hints = new LinkedHashMap<>(); + hints.put("desktop-entry", desktopEntry); + hints.put("category", "im.received"); + // The client plays the sound pack's own sound for whatever it notifies of. + hints.put("suppress-sound", true); + try { + long id = (Long) bus.call(SERVICE, PATH, SERVICE, "Notify", "susssasa{sv}i", + appName, (long) replaces, icon, notice.title(), + markup ? escape(notice.body()) : notice.body(), actions, hints, -1).getFirst(); + shown.remove((long) replaces); + shown.put(id, notice); + return (int) id; + } catch (IOException | RuntimeException e) { + System.err.println("Cannot show a notification: " + e.getMessage()); + return 0; + } + } + + @Override + public void close(int id) { + if (shown.remove((long) id) == null) return; + try { + bus.call(SERVICE, PATH, SERVICE, "CloseNotification", "u", (long) id); + } catch (IOException e) { + // Gone with the service; nothing to take away. + } + } + + @Override + public void shutdown() { + for (Long id : List.copyOf(shown.keySet())) close(id.intValue()); + bus.close(); + } + + private void signal(String iface, String member, List args) { + if (!SERVICE.equals(iface) || args.isEmpty() || !(args.getFirst() instanceof Long id)) return; + switch (member) { + case "ActionInvoked" -> { + Notice notice = shown.get(id); + if (notice != null && DEFAULT_ACTION.equals(args.get(1))) notice.onOpen().run(); + } + case "NotificationReplied" -> { + Notice notice = shown.get(id); + if (notice != null && notice.onReply() != null) notice.onReply().accept((String) args.get(1)); + } + case "NotificationClosed" -> shown.remove(id); + default -> { } + } + } + + /** The body is markup where the service says so; message text must not turn into any. */ + private static String escape(String text) { + return text.replace("&", "&").replace("<", "<").replace(">", ">"); + } +} diff --git a/ts3-client/desktop/src/test/java/com/ts3client/audio/desktop/pipewire/SpaPodTest.java b/ts3-client/desktop/src/test/java/com/ts3client/audio/desktop/pipewire/SpaPodTest.java deleted file mode 100644 index 82f484b..0000000 --- a/ts3-client/desktop/src/test/java/com/ts3client/audio/desktop/pipewire/SpaPodTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.ts3client.audio.desktop.pipewire; - -import org.junit.jupiter.api.Test; - -import java.util.HexFormat; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Pins {@link SpaPod} to the bytes libpipewire itself produces. - * - *

    The expected values are the output of {@code spa_format_audio_raw_build()} (pipewire - * 1.4, {@code SPA_AUDIO_FORMAT_S16_LE} at 48 kHz), captured from a C program linked - * against the real library. Since the POD layout is what the server parses, a mismatch - * here is a stream that will fail to negotiate. - */ -class SpaPodTest { - - private static final String MONO_48K = - "a00000000f000000030004000300000001000000000000000400000003000000" - + "0100000000000000020000000000000004000000030000000100000000000000" - + "0100010000000000040000000300000003010000000000000300010000000000" - + "040000000400000080bb00000000000004000100000000000400000004000000" - + "010000000000000005000100000000000c0000000d0000000400000003000000" - + "0200000000000000"; - - private static final String STEREO_48K = - "a00000000f000000030004000300000001000000000000000400000003000000" - + "0100000000000000020000000000000004000000030000000100000000000000" - + "0100010000000000040000000300000003010000000000000300010000000000" - + "040000000400000080bb00000000000004000100000000000400000004000000" - + "02000000000000000500010000000000100000000d0000000400000003000000" - + "0300000004000000"; - - @Test - void buildsTheFormatLibpipewireExpects() { - assertEquals(MONO_48K, hex(SpaPod.audioFormatBytes(48_000, 1))); - assertEquals(STEREO_48K, hex(SpaPod.audioFormatBytes(48_000, 2))); - } - - private static String hex(byte[] bytes) { - return HexFormat.of().formatHex(bytes); - } -} diff --git a/ts3-client/desktop/src/test/java/com/ts3client/hotkey/desktop/RawInputTest.java b/ts3-client/desktop/src/test/java/com/ts3client/hotkey/desktop/RawInputTest.java deleted file mode 100644 index 0ed57e4..0000000 --- a/ts3-client/desktop/src/test/java/com/ts3client/hotkey/desktop/RawInputTest.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.ts3client.hotkey.desktop; - -import com.ts3client.hotkey.HotkeyKey; -import org.junit.jupiter.api.Test; - -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** Decoding of Windows raw input, which needs no Windows to check. */ -class RawInputTest { - - @Test - void plainKeyKeepsItsScanCode() { - // 'A' is scan code 0x1E, no escape. - assertEquals(0x1E, RawInput.scanCode(0x1E, 0, 0x41)); - } - - @Test - void escapedKeysStayDistinctFromTheirUnescapedTwins() { - // Left Ctrl is 1D; right Ctrl is E0 1D, and the two must not collide. - int left = RawInput.scanCode(0x1D, 0, 0xA2); - int right = RawInput.scanCode(0x1D, RawInput.RI_KEY_E0, 0xA3); - assertEquals(0x1D, left); - assertEquals(0xE01D, right); - } - - @Test - void pauseUsesTheOtherEscape() { - assertEquals(0xE11D, RawInput.scanCode(0x1D, RawInput.RI_KEY_E1, 0x13)); - } - - @Test - void fillerHalfOfAnEscapedSequenceIsIgnored() { - assertEquals(-1, RawInput.scanCode(0x2A, RawInput.RI_KEY_E0, 0xFF)); - assertEquals(-1, RawInput.scanCode(0, 0, 0x41)); - } - - @Test - void breakFlagMarksTheRelease() { - assertFalse(RawInput.isRelease(0)); - assertTrue(RawInput.isRelease(RawInput.RI_KEY_BREAK)); - assertTrue(RawInput.isRelease(RawInput.RI_KEY_BREAK | RawInput.RI_KEY_E0)); - } - - @Test - void sideButtonsMapToTheNumbersUsersKnow() { - // X1 down: "Mouse 4" everywhere else in the client, X button 8. - List down = RawInput.buttons(0x0040, (short) 0); - assertEquals(List.of(new RawInput.ButtonEvent(HotkeyKey.mouse(8), true)), down); - assertEquals("Mouse 4", HotkeyKey.mouse(8).fallbackName()); - - List up = RawInput.buttons(0x0200, (short) 0); - assertEquals(List.of(new RawInput.ButtonEvent(HotkeyKey.mouse(9), false)), up); - assertEquals("Mouse 5", HotkeyKey.mouse(9).fallbackName()); - } - - @Test - void primaryButtonsUseTheXNumbering() { - assertEquals(List.of(new RawInput.ButtonEvent(HotkeyKey.mouse(1), true)), - RawInput.buttons(0x0001, (short) 0)); - assertEquals(List.of(new RawInput.ButtonEvent(HotkeyKey.mouse(2), true)), - RawInput.buttons(0x0010, (short) 0)); - assertEquals(List.of(new RawInput.ButtonEvent(HotkeyKey.mouse(3), true)), - RawInput.buttons(0x0004, (short) 0)); - } - - @Test - void oneEventCanCarrySeveralTransitions() { - // Left up and right down in the same report. - assertEquals(List.of(new RawInput.ButtonEvent(HotkeyKey.mouse(1), false), - new RawInput.ButtonEvent(HotkeyKey.mouse(3), true)), - RawInput.buttons(0x0002 | 0x0004, (short) 0)); - } - - @Test - void wheelBecomesATapSoTheEngineSeesBothEdges() { - assertEquals(List.of(new RawInput.ButtonEvent(HotkeyKey.mouse(4), true), - new RawInput.ButtonEvent(HotkeyKey.mouse(4), false)), - RawInput.buttons(0x0400, (short) 120)); - assertEquals(List.of(new RawInput.ButtonEvent(HotkeyKey.mouse(5), true), - new RawInput.ButtonEvent(HotkeyKey.mouse(5), false)), - RawInput.buttons(0x0400, (short) -120)); - } - - @Test - void mouseMovementAloneReportsNothing() { - assertEquals(List.of(), RawInput.buttons(0, (short) 0)); - } -} diff --git a/ts3-client/desktop/src/test/java/com/ts3client/notify/desktop/DBusWireTest.java b/ts3-client/desktop/src/test/java/com/ts3client/notify/desktop/DBusWireTest.java deleted file mode 100644 index a626b59..0000000 --- a/ts3-client/desktop/src/test/java/com/ts3client/notify/desktop/DBusWireTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.ts3client.notify.desktop; - -import org.junit.jupiter.api.Test; - -import java.nio.ByteBuffer; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; - -class DBusWireTest { - - @Test - void methodCallReadsBackAsWritten() { - Map hints = new LinkedHashMap<>(); - hints.put("desktop-entry", "ts3j-client"); - hints.put("suppress-sound", true); - byte[] message = DBusWire.methodCall(7, "org.freedesktop.Notifications", "/org/freedesktop/Notifications", - "org.freedesktop.Notifications", "Notify", "susssasa{sv}i", - "TS3J", 3L, "", "Bob", "Hi ž", List.of("default", "Open"), hints, -1); - - assertEquals(message.length, DBusWire.messageLength(ByteBuffer.wrap(message, 0, DBusWire.FIXED_HEADER))); - DBusWire.Message m = DBusWire.parse(message); - assertEquals(DBusWire.METHOD_CALL, m.type()); - assertEquals(7, m.serial()); - assertEquals("Notify", m.string(DBusWire.FIELD_MEMBER)); - assertEquals("/org/freedesktop/Notifications", m.string(DBusWire.FIELD_PATH)); - assertEquals("TS3J", m.body().get(0)); - assertEquals(3L, m.body().get(1)); - assertEquals("Hi ž", m.body().get(4)); - assertEquals(List.of("default", "Open"), m.body().get(5)); - List entries = (List) m.body().get(6); - assertArrayEquals(new Object[]{"desktop-entry", "ts3j-client"}, (Object[]) entries.get(0)); - assertArrayEquals(new Object[]{"suppress-sound", true}, (Object[]) entries.get(1)); - assertEquals(-1, m.body().get(7)); - } - - @Test - void completeTypesAreDelimited() { - assertEquals(1, DBusWire.typeEnd("su", 0)); - assertEquals(5, DBusWire.typeEnd("a{sv}i", 0)); - assertEquals(5, DBusWire.typeEnd("a(yv)s", 0)); - assertEquals(3, DBusWire.typeEnd("aasu", 1)); - } -} diff --git a/ts3-client/desktop/src/test/java/com/ts3client/recording/LibOpusMultistream.java b/ts3-client/desktop/src/test/java/com/ts3client/recording/LibOpusMultistream.java deleted file mode 100644 index b7ab270..0000000 --- a/ts3-client/desktop/src/test/java/com/ts3client/recording/LibOpusMultistream.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.ts3client.recording; - -import java.lang.foreign.Arena; -import java.lang.foreign.FunctionDescriptor; -import java.lang.foreign.Linker; -import java.lang.foreign.MemorySegment; -import java.lang.foreign.SymbolLookup; -import java.lang.foreign.ValueLayout; -import java.lang.invoke.MethodHandle; - -/** libopus' own multistream decoder, to check our multistream packets against. */ -final class LibOpusMultistream implements AutoCloseable { - - private static final Linker LINKER = Linker.nativeLinker(); - private static final SymbolLookup LIB = SymbolLookup.libraryLookup("libopus.so.0", Arena.global()); - private static final MethodHandle CREATE = LINKER.downcallHandle(LIB.find("opus_multistream_decoder_create").orElseThrow(), - FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, - ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.ADDRESS)); - private static final MethodHandle DECODE = LINKER.downcallHandle(LIB.find("opus_multistream_decode_float").orElseThrow(), - FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.ADDRESS, ValueLayout.JAVA_INT, - ValueLayout.ADDRESS, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT)); - private static final MethodHandle DESTROY = LINKER.downcallHandle(LIB.find("opus_multistream_decoder_destroy").orElseThrow(), - FunctionDescriptor.ofVoid(ValueLayout.ADDRESS)); - - private static final int MAX_FRAME = 5760; - - private final Arena arena = Arena.ofConfined(); - private final MemorySegment decoder; - private final MemorySegment pcm; - private final MemorySegment data = arena.allocate(1 << 20); - final int channels; - - LibOpusMultistream(int channels, int streams, int coupled, byte[] mapping) throws Throwable { - this.channels = channels; - MemorySegment map = arena.allocate(mapping.length); - map.copyFrom(MemorySegment.ofArray(mapping)); - MemorySegment error = arena.allocate(ValueLayout.JAVA_INT); - decoder = (MemorySegment) CREATE.invokeExact(48_000, channels, streams, coupled, map, error); - if (error.get(ValueLayout.JAVA_INT, 0) != 0) throw new IllegalStateException("create: " + error.get(ValueLayout.JAVA_INT, 0)); - pcm = arena.allocate(ValueLayout.JAVA_FLOAT, (long) MAX_FRAME * channels); - } - - /** @return interleaved samples, or throws if libopus rejects the packet */ - float[] decode(byte[] packet) throws Throwable { - MemorySegment.copy(packet, 0, data, ValueLayout.JAVA_BYTE, 0, packet.length); - int n = (int) DECODE.invokeExact(decoder, data, packet.length, pcm, MAX_FRAME, 0); - if (n < 0) throw new IllegalStateException("opus_multistream_decode_float: " + n); - return pcm.asSlice(0, (long) n * channels * 4).toArray(ValueLayout.JAVA_FLOAT); - } - - @Override - public void close() { - try { - DESTROY.invokeExact(decoder); - } catch (Throwable ignored) { - } - arena.close(); - } -} diff --git a/ts3-client/desktop/src/test/java/com/ts3client/recording/VoiceRecorderTest.java b/ts3-client/desktop/src/test/java/com/ts3client/recording/VoiceRecorderTest.java deleted file mode 100644 index 61cf7d7..0000000 --- a/ts3-client/desktop/src/test/java/com/ts3client/recording/VoiceRecorderTest.java +++ /dev/null @@ -1,313 +0,0 @@ -package com.ts3client.recording; - -import com.ts3client.audio.VoiceFormat; -import com.ts3client.audio.desktop.NativeOpusCodec; -import com.ts3client.audio.ogg.SelfDelimitedOpus; -import com.ts3client.audio.opus.OpusEncoder; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardCopyOption; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Recordings decode, through libopus' own multistream decoder, to every speaker where and - * when they spoke. - */ -class VoiceRecorderTest { - - private static final int FRAME = VoiceFormat.FRAME_SIZE; - private static final long FRAME_NANOS = TimeUnit.MILLISECONDS.toNanos(20); - /** Frames the simulated recordings run for. */ - private static final int LENGTH = 250; - - @TempDir - Path dir; - - private final NativeOpusCodec opus = new NativeOpusCodec(); - - /** Who speaks when, in frames, at which pitch. */ - private record Burst(String uid, String nickname, int from, int to, double hz) { - } - - private static final List CONVERSATION = List.of( - new Burst("uidA", "Alice (renamed)", 50, 100, 440), - new Burst("uidB", "Bob", 150, 175, 660), - // After a pause long enough for a fresh encoder. - new Burst("uidA", "Alice (renamed)", 200, 210, 440)); - - @Test - void multitrackPutsEverySpeakerOnTheirOwnChannelFromTheStart() throws Throwable { - Path file = dir.resolve("multi.ogg"); - List files = record(VoiceRecorder.Mode.MULTITRACK, file, Map.of("uidA", "Alice"), CONVERSATION); - assertEquals(List.of(file), files); - - Decoded d = decode(file); - assertEquals(2, d.channels); - assertTrue(d.comments.containsAll(List.of("CHANNEL1_NAME=Alice", "CHANNEL1_UID=uidA", - "CHANNEL2_NAME=Bob", "CHANNEL2_UID=uidB")), d.comments.toString()); - assertEquals(LENGTH * FRAME, d.frames()); - - assertTone(d, 0, 50, 100, 440); - assertSilent(d, 0, 0, 49); - assertSilent(d, 0, 102, 199); - assertTone(d, 0, 200, 210, 440); - assertTone(d, 1, 150, 175, 660); - assertStartsAt(d, 0, 50); - assertStartsAt(d, 0, 200); - assertStartsAt(d, 1, 150); - assertSilent(d, 1, 0, 149); - assertSilent(d, 1, 177, LENGTH); - assertTrue(Files.list(dir).noneMatch(p -> p.getFileName().toString().startsWith(".")), "spool left behind"); - } - - @Test - void mixedPutsEveryoneOnOneMonoTrack() throws Throwable { - Path file = dir.resolve("mixed.ogg"); - record(VoiceRecorder.Mode.MIXED, file, Map.of(), CONVERSATION); - - Decoded d = decode(file); - assertEquals(1, d.channels); - assertEquals(LENGTH * FRAME, d.frames()); - assertTone(d, 0, 50, 100, 440); - assertTone(d, 0, 150, 175, 660); - assertSilent(d, 0, 0, 49); - assertSilent(d, 0, 102, 149); - } - - @Test - void moreSpeakersThanAFileHoldsContinueInTheNextFile() throws Throwable { - List crowd = new ArrayList<>(); - for (int i = 0; i < 300; i++) crowd.add(new Burst("uid" + i, "Client " + i, i % 200, i % 200 + 5, 440)); - crowd.sort((a, b) -> Integer.compare(a.from, b.from)); - Path file = dir.resolve("crowd.ogg"); - List files = record(VoiceRecorder.Mode.MULTITRACK, file, Map.of(), crowd); - assertEquals(List.of(file, dir.resolve("crowd-2.ogg")), files); - - Decoded first = decode(files.get(0)); - Decoded second = decode(files.get(1)); - assertEquals(255, first.channels); - assertEquals(45, second.channels); - assertEquals(LENGTH * FRAME, first.frames()); - assertEquals(LENGTH * FRAME, second.frames()); - // Channels go in the order speakers first spoke. - assertTone(first, 0, 0, 5, 440); - // Two speakers a frame start until frame 100, one after: the 256th first spoke at 155. - assertTone(second, 0, 155, 160, 440); - assertStartsAt(second, 0, 155); - assertSilent(second, 0, 0, 154); - } - - @Test - void multiFramePacketsAreSplitWhereLibopusSplitsThem() throws Throwable { - byte[][] f = new byte[6][]; - try (OpusEncoder encoder = RecordingEncoders.mono(opus, 48_000)) { - for (int i = 0; i < f.length; i++) f[i] = encoder.encode(tone(440 + 50 * i, i)); - } - byte[] padded = code3(f[0], f[1], 3); - byte[] code2 = cat(new byte[]{(byte) ((f[2][0] & 0xfc) | 2), (byte) (f[2].length - 1)}, - Arrays.copyOfRange(f[2], 1, f[2].length), Arrays.copyOfRange(f[3], 1, f[3].length)); - byte[] last = code3(f[4], f[5], 0); - byte[] joined = SelfDelimitedOpus.join(List.of(padded, code2, last)); - - try (LibOpusMultistream decoder = new LibOpusMultistream(3, 3, 0, new byte[]{0, 1, 2})) { - assertEquals(3 * 2 * FRAME, decoder.decode(joined).length); - } - } - - /** Two single-frame packets of one configuration as one VBR code 3 packet. */ - private static byte[] code3(byte[] a, byte[] b, int padding) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - out.write((a[0] & 0xfc) | 3); - out.write(0x80 | (padding > 0 ? 0x40 : 0) | 2); - if (padding > 0) out.write(padding); - out.write(a.length - 1); - out.write(a, 1, a.length - 1); - out.write(b, 1, b.length - 1); - out.write(new byte[padding], 0, padding); - return out.toByteArray(); - } - - private static byte[] cat(byte[]... parts) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - for (byte[] p : parts) out.writeBytes(p); - return out.toByteArray(); - } - - // ---- simulation ---- - - private List record(VoiceRecorder.Mode mode, Path file, Map names, List bursts) - throws Exception { - AtomicLong clock = new AtomicLong(1_000_000_000L); - long start = clock.get(); - VoiceRecorder recorder = VoiceRecorder.start(mode, file, opus, names, clock::get); - for (int f = 0; f < LENGTH; f++) { - for (Burst burst : bursts) { - if (f < burst.from || f >= burst.to) continue; - // Played a little late, as audio threads are. - clock.set(start + f * FRAME_NANOS + (f * 7919L % 5) * 1_000_000L); - recorder.offer(burst.uid, burst.nickname, tone(burst.hz, f), 1, FRAME); - } - } - clock.set(start + LENGTH * FRAME_NANOS); - List files = recorder.stop().get(60, TimeUnit.SECONDS); - String dump = System.getProperty("recording.dump"); - if (dump != null) { - for (Path p : files) Files.copy(p, Path.of(dump).resolve(p.getFileName()), StandardCopyOption.REPLACE_EXISTING); - } - return files; - } - - private static float[] tone(double hz, int frame) { - float[] pcm = new float[FRAME]; - for (int i = 0; i < FRAME; i++) { - pcm[i] = (float) (0.5 * Math.sin(2 * Math.PI * hz * ((long) frame * FRAME + i) / VoiceFormat.SAMPLE_RATE)); - } - return pcm; - } - - // ---- checks ---- - - /** A tone of {@code hz} over the frames, give or take the edges. */ - private static void assertTone(Decoded d, int channel, int from, int to, double hz) { - int start = (from + 1) * FRAME; - int end = (to - 1) * FRAME; - double energy = 0; - double sin = 0; - double cos = 0; - for (int i = start; i < end; i++) { - double x = d.sample(i, channel); - double phase = 2 * Math.PI * hz * i / VoiceFormat.SAMPLE_RATE; - sin += x * Math.sin(phase); - cos += x * Math.cos(phase); - energy += x * x; - } - double amplitude = Math.sqrt(sin * sin + cos * cos) * 2 / (end - start); - double rms = Math.sqrt(energy / (end - start)); - assertTrue(amplitude > 0.4, "channel " + channel + " frames " + from + "-" + to + ": amplitude at " + hz + " Hz " + amplitude); - assertTrue(rms > 0.3 && rms < 0.42, "channel " + channel + " frames " + from + "-" + to + ": rms " + rms); - } - - /** Sound sets in right at the frame, not faded in. */ - private static void assertStartsAt(Decoded d, int channel, int frame) { - int onset = frame * FRAME - FRAME; - while (Math.abs(d.sample(onset, channel)) < 0.05) onset++; - assertEquals(frame * FRAME, onset, 48.0, "channel " + channel + " onset"); - } - - private static void assertSilent(Decoded d, int channel, int from, int to) { - double peak = 0; - for (int i = from * FRAME; i < Math.min(to * FRAME, d.frames()); i++) peak = Math.max(peak, Math.abs(d.sample(i, channel))); - assertTrue(peak < 0.01, "channel " + channel + " frames " + from + "-" + to + ": peak " + peak); - } - - // ---- decoding ---- - - private record Decoded(int channels, List comments, float[] pcm) { - int frames() { - return pcm.length / channels; - } - - double sample(int i, int channel) { - return pcm[i * channels + channel]; - } - } - - private static Decoded decode(Path file) throws Throwable { - List packets = new ArrayList<>(); - long granule = readOgg(Files.readAllBytes(file), packets); - - ByteBuffer head = ByteBuffer.wrap(packets.get(0)).order(ByteOrder.LITTLE_ENDIAN); - assertEquals("OpusHead", new String(packets.get(0), 0, 8, StandardCharsets.US_ASCII)); - int channels = head.get(9) & 0xff; - int preSkip = head.getShort(10) & 0xffff; - int family = head.get(18) & 0xff; - int streams = 1; - int coupled = 0; - byte[] mapping = {0}; - if (family != 0) { - assertEquals(255, family); - streams = head.get(19) & 0xff; - coupled = head.get(20) & 0xff; - mapping = Arrays.copyOfRange(packets.get(0), 21, 21 + channels); - } - - ByteBuffer tags = ByteBuffer.wrap(packets.get(1)).order(ByteOrder.LITTLE_ENDIAN); - tags.position(8); - int vendor = tags.getInt(); - tags.position(tags.position() + vendor); - int count = tags.getInt(); - List comments = new ArrayList<>(); - for (int i = 0; i < count; i++) { - byte[] s = new byte[tags.getInt()]; - tags.get(s); - comments.add(new String(s, StandardCharsets.UTF_8)); - } - - float[] pcm = new float[0]; - int length = 0; - try (LibOpusMultistream decoder = new LibOpusMultistream(channels, streams, coupled, mapping)) { - for (byte[] packet : packets.subList(2, packets.size())) { - float[] out = decoder.decode(packet); - if (length + out.length > pcm.length) pcm = Arrays.copyOf(pcm, Math.max(pcm.length * 2, length + out.length)); - System.arraycopy(out, 0, pcm, length, out.length); - length += out.length; - } - } - assertTrue(granule * channels <= length, "granule past the audio"); - return new Decoded(channels, comments, Arrays.copyOfRange(pcm, preSkip * channels, (int) granule * channels)); - } - - /** Reads every packet, checking the pages' framing; returns the last page's granule position. */ - private static long readOgg(byte[] file, List packets) { - ByteBuffer in = ByteBuffer.wrap(file).order(ByteOrder.LITTLE_ENDIAN); - ByteArrayOutputStream packet = new ByteArrayOutputStream(); - long granule = -1; - int expectedSequence = 0; - boolean sawLast = false; - while (in.hasRemaining()) { - int start = in.position(); - assertEquals(0x5367674f, in.getInt(), "page sync"); - in.get(); - int flags = in.get() & 0xff; - granule = in.getLong(); - in.getInt(); - assertEquals(expectedSequence++, in.getInt(), "page sequence"); - in.getInt(); - assertEquals(packet.size() > 0, (flags & 1) != 0, "continuation flag"); - assertEquals(start == 0, (flags & 2) != 0, "first page flag"); - sawLast = (flags & 4) != 0; - int segments = in.get() & 0xff; - byte[] lacing = new byte[segments]; - in.get(lacing); - for (byte l : lacing) { - int size = l & 0xff; - byte[] data = new byte[size]; - in.get(data); - packet.writeBytes(data); - if (size < 255) { - packets.add(packet.toByteArray()); - packet.reset(); - } - } - } - assertTrue(sawLast, "last page flag"); - return granule; - } -} diff --git a/ts3-client/desktop/src/test/java/com/ts3client/sound/OggOpusFileTest.java b/ts3-client/desktop/src/test/java/com/ts3client/sound/OggOpusFileTest.java deleted file mode 100644 index a080f63..0000000 --- a/ts3-client/desktop/src/test/java/com/ts3client/sound/OggOpusFileTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.ts3client.sound; - -import com.ts3client.audio.desktop.NativeOpusCodec; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import java.io.File; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.file.Files; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** A pack converted to Opus plays back as the sound it was, found under its old name. */ -class OggOpusFileTest { - - @TempDir - File dir; - - @Test - void convertedPackPlaysTheSameSound() throws IOException { - File source = new File(dir, "wav/pack"); - Files.createDirectories(source.toPath()); - Files.writeString(new File(source, "settings.ini").toPath(), - "[info]\nname = Test\n[soundfiles]\nCONNECTION_CONNECTED = play(\"tone.wav\")\n"); - int rate = 44_100; - float[] tone = new float[rate / 2 + 123]; - for (int i = 0; i < tone.length; i++) tone[i] = (float) (0.5 * Math.sin(2 * Math.PI * 440 * i / rate)); - writeWave(new File(source, "tone.wav"), tone, rate); - - File target = new File(dir, "opus"); - NativeOpusCodec opus = new NativeOpusCodec(); - SoundPackConverter.convert(new File(dir, "wav"), target, opus); - - SoundPack pack = SoundPack.load(new File(target, "pack")); - assertNotNull(pack); - File file = pack.file("tone.wav"); - assertEquals("tone.opus", file.getName()); - - float[] expected = WaveFile.readMono(new File(source, "tone.wav")).at48k(); - float[] decoded = OggOpusFile.readMono(file, opus); - assertEquals(expected.length, decoded.length); - double dot = 0, a = 0, b = 0; - for (int i = 0; i < decoded.length; i++) { - dot += expected[i] * decoded[i]; - a += expected[i] * expected[i]; - b += decoded[i] * decoded[i]; - } - double correlation = dot / Math.sqrt(a * b); - assertTrue(correlation > 0.99, "correlation " + correlation); - } - - private static void writeWave(File file, float[] samples, int rate) throws IOException { - ByteBuffer b = ByteBuffer.allocate(44 + samples.length * 2).order(ByteOrder.LITTLE_ENDIAN); - b.put("RIFF".getBytes()).putInt(36 + samples.length * 2).put("WAVE".getBytes()); - b.put("fmt ".getBytes()).putInt(16).putShort((short) 1).putShort((short) 1) - .putInt(rate).putInt(rate * 2).putShort((short) 2).putShort((short) 16); - b.put("data".getBytes()).putInt(samples.length * 2); - for (float s : samples) b.putShort((short) Math.round(s * 32767)); - Files.write(file.toPath(), b.array()); - } -} diff --git a/ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/audio/desktop/pipewire/SpaPodTest.java b/ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/audio/desktop/pipewire/SpaPodTest.java new file mode 100644 index 0000000..be01e31 --- /dev/null +++ b/ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/audio/desktop/pipewire/SpaPodTest.java @@ -0,0 +1,44 @@ +package eu.lixko.ts3j.client.audio.desktop.pipewire; + +import org.junit.jupiter.api.Test; + +import java.util.HexFormat; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Pins {@link SpaPod} to the bytes libpipewire itself produces. + * + *

    The expected values are the output of {@code spa_format_audio_raw_build()} (pipewire + * 1.4, {@code SPA_AUDIO_FORMAT_S16_LE} at 48 kHz), captured from a C program linked + * against the real library. Since the POD layout is what the server parses, a mismatch + * here is a stream that will fail to negotiate. + */ +class SpaPodTest { + + private static final String MONO_48K = + "a00000000f000000030004000300000001000000000000000400000003000000" + + "0100000000000000020000000000000004000000030000000100000000000000" + + "0100010000000000040000000300000003010000000000000300010000000000" + + "040000000400000080bb00000000000004000100000000000400000004000000" + + "010000000000000005000100000000000c0000000d0000000400000003000000" + + "0200000000000000"; + + private static final String STEREO_48K = + "a00000000f000000030004000300000001000000000000000400000003000000" + + "0100000000000000020000000000000004000000030000000100000000000000" + + "0100010000000000040000000300000003010000000000000300010000000000" + + "040000000400000080bb00000000000004000100000000000400000004000000" + + "02000000000000000500010000000000100000000d0000000400000003000000" + + "0300000004000000"; + + @Test + void buildsTheFormatLibpipewireExpects() { + assertEquals(MONO_48K, hex(SpaPod.audioFormatBytes(48_000, 1))); + assertEquals(STEREO_48K, hex(SpaPod.audioFormatBytes(48_000, 2))); + } + + private static String hex(byte[] bytes) { + return HexFormat.of().formatHex(bytes); + } +} diff --git a/ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/hotkey/desktop/RawInputTest.java b/ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/hotkey/desktop/RawInputTest.java new file mode 100644 index 0000000..91c0a47 --- /dev/null +++ b/ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/hotkey/desktop/RawInputTest.java @@ -0,0 +1,92 @@ +package eu.lixko.ts3j.client.hotkey.desktop; + +import eu.lixko.ts3j.client.hotkey.HotkeyKey; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** Decoding of Windows raw input, which needs no Windows to check. */ +class RawInputTest { + + @Test + void plainKeyKeepsItsScanCode() { + // 'A' is scan code 0x1E, no escape. + assertEquals(0x1E, RawInput.scanCode(0x1E, 0, 0x41)); + } + + @Test + void escapedKeysStayDistinctFromTheirUnescapedTwins() { + // Left Ctrl is 1D; right Ctrl is E0 1D, and the two must not collide. + int left = RawInput.scanCode(0x1D, 0, 0xA2); + int right = RawInput.scanCode(0x1D, RawInput.RI_KEY_E0, 0xA3); + assertEquals(0x1D, left); + assertEquals(0xE01D, right); + } + + @Test + void pauseUsesTheOtherEscape() { + assertEquals(0xE11D, RawInput.scanCode(0x1D, RawInput.RI_KEY_E1, 0x13)); + } + + @Test + void fillerHalfOfAnEscapedSequenceIsIgnored() { + assertEquals(-1, RawInput.scanCode(0x2A, RawInput.RI_KEY_E0, 0xFF)); + assertEquals(-1, RawInput.scanCode(0, 0, 0x41)); + } + + @Test + void breakFlagMarksTheRelease() { + assertFalse(RawInput.isRelease(0)); + assertTrue(RawInput.isRelease(RawInput.RI_KEY_BREAK)); + assertTrue(RawInput.isRelease(RawInput.RI_KEY_BREAK | RawInput.RI_KEY_E0)); + } + + @Test + void sideButtonsMapToTheNumbersUsersKnow() { + // X1 down: "Mouse 4" everywhere else in the client, X button 8. + List down = RawInput.buttons(0x0040, (short) 0); + assertEquals(List.of(new RawInput.ButtonEvent(HotkeyKey.mouse(8), true)), down); + assertEquals("Mouse 4", HotkeyKey.mouse(8).fallbackName()); + + List up = RawInput.buttons(0x0200, (short) 0); + assertEquals(List.of(new RawInput.ButtonEvent(HotkeyKey.mouse(9), false)), up); + assertEquals("Mouse 5", HotkeyKey.mouse(9).fallbackName()); + } + + @Test + void primaryButtonsUseTheXNumbering() { + assertEquals(List.of(new RawInput.ButtonEvent(HotkeyKey.mouse(1), true)), + RawInput.buttons(0x0001, (short) 0)); + assertEquals(List.of(new RawInput.ButtonEvent(HotkeyKey.mouse(2), true)), + RawInput.buttons(0x0010, (short) 0)); + assertEquals(List.of(new RawInput.ButtonEvent(HotkeyKey.mouse(3), true)), + RawInput.buttons(0x0004, (short) 0)); + } + + @Test + void oneEventCanCarrySeveralTransitions() { + // Left up and right down in the same report. + assertEquals(List.of(new RawInput.ButtonEvent(HotkeyKey.mouse(1), false), + new RawInput.ButtonEvent(HotkeyKey.mouse(3), true)), + RawInput.buttons(0x0002 | 0x0004, (short) 0)); + } + + @Test + void wheelBecomesATapSoTheEngineSeesBothEdges() { + assertEquals(List.of(new RawInput.ButtonEvent(HotkeyKey.mouse(4), true), + new RawInput.ButtonEvent(HotkeyKey.mouse(4), false)), + RawInput.buttons(0x0400, (short) 120)); + assertEquals(List.of(new RawInput.ButtonEvent(HotkeyKey.mouse(5), true), + new RawInput.ButtonEvent(HotkeyKey.mouse(5), false)), + RawInput.buttons(0x0400, (short) -120)); + } + + @Test + void mouseMovementAloneReportsNothing() { + assertEquals(List.of(), RawInput.buttons(0, (short) 0)); + } +} diff --git a/ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/notify/desktop/DBusWireTest.java b/ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/notify/desktop/DBusWireTest.java new file mode 100644 index 0000000..1f84eed --- /dev/null +++ b/ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/notify/desktop/DBusWireTest.java @@ -0,0 +1,47 @@ +package eu.lixko.ts3j.client.notify.desktop; + +import org.junit.jupiter.api.Test; + +import java.nio.ByteBuffer; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class DBusWireTest { + + @Test + void methodCallReadsBackAsWritten() { + Map hints = new LinkedHashMap<>(); + hints.put("desktop-entry", "ts3j-client"); + hints.put("suppress-sound", true); + byte[] message = DBusWire.methodCall(7, "org.freedesktop.Notifications", "/org/freedesktop/Notifications", + "org.freedesktop.Notifications", "Notify", "susssasa{sv}i", + "TS3J", 3L, "", "Bob", "Hi ž", List.of("default", "Open"), hints, -1); + + assertEquals(message.length, DBusWire.messageLength(ByteBuffer.wrap(message, 0, DBusWire.FIXED_HEADER))); + DBusWire.Message m = DBusWire.parse(message); + assertEquals(DBusWire.METHOD_CALL, m.type()); + assertEquals(7, m.serial()); + assertEquals("Notify", m.string(DBusWire.FIELD_MEMBER)); + assertEquals("/org/freedesktop/Notifications", m.string(DBusWire.FIELD_PATH)); + assertEquals("TS3J", m.body().get(0)); + assertEquals(3L, m.body().get(1)); + assertEquals("Hi ž", m.body().get(4)); + assertEquals(List.of("default", "Open"), m.body().get(5)); + List entries = (List) m.body().get(6); + assertArrayEquals(new Object[]{"desktop-entry", "ts3j-client"}, (Object[]) entries.get(0)); + assertArrayEquals(new Object[]{"suppress-sound", true}, (Object[]) entries.get(1)); + assertEquals(-1, m.body().get(7)); + } + + @Test + void completeTypesAreDelimited() { + assertEquals(1, DBusWire.typeEnd("su", 0)); + assertEquals(5, DBusWire.typeEnd("a{sv}i", 0)); + assertEquals(5, DBusWire.typeEnd("a(yv)s", 0)); + assertEquals(3, DBusWire.typeEnd("aasu", 1)); + } +} diff --git a/ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/recording/LibOpusMultistream.java b/ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/recording/LibOpusMultistream.java new file mode 100644 index 0000000..99def3b --- /dev/null +++ b/ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/recording/LibOpusMultistream.java @@ -0,0 +1,59 @@ +package eu.lixko.ts3j.client.recording; + +import java.lang.foreign.Arena; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.Linker; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.SymbolLookup; +import java.lang.foreign.ValueLayout; +import java.lang.invoke.MethodHandle; + +/** libopus' own multistream decoder, to check our multistream packets against. */ +final class LibOpusMultistream implements AutoCloseable { + + private static final Linker LINKER = Linker.nativeLinker(); + private static final SymbolLookup LIB = SymbolLookup.libraryLookup("libopus.so.0", Arena.global()); + private static final MethodHandle CREATE = LINKER.downcallHandle(LIB.find("opus_multistream_decoder_create").orElseThrow(), + FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, + ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.ADDRESS)); + private static final MethodHandle DECODE = LINKER.downcallHandle(LIB.find("opus_multistream_decode_float").orElseThrow(), + FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.ADDRESS, ValueLayout.JAVA_INT, + ValueLayout.ADDRESS, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT)); + private static final MethodHandle DESTROY = LINKER.downcallHandle(LIB.find("opus_multistream_decoder_destroy").orElseThrow(), + FunctionDescriptor.ofVoid(ValueLayout.ADDRESS)); + + private static final int MAX_FRAME = 5760; + + private final Arena arena = Arena.ofConfined(); + private final MemorySegment decoder; + private final MemorySegment pcm; + private final MemorySegment data = arena.allocate(1 << 20); + final int channels; + + LibOpusMultistream(int channels, int streams, int coupled, byte[] mapping) throws Throwable { + this.channels = channels; + MemorySegment map = arena.allocate(mapping.length); + map.copyFrom(MemorySegment.ofArray(mapping)); + MemorySegment error = arena.allocate(ValueLayout.JAVA_INT); + decoder = (MemorySegment) CREATE.invokeExact(48_000, channels, streams, coupled, map, error); + if (error.get(ValueLayout.JAVA_INT, 0) != 0) throw new IllegalStateException("create: " + error.get(ValueLayout.JAVA_INT, 0)); + pcm = arena.allocate(ValueLayout.JAVA_FLOAT, (long) MAX_FRAME * channels); + } + + /** @return interleaved samples, or throws if libopus rejects the packet */ + float[] decode(byte[] packet) throws Throwable { + MemorySegment.copy(packet, 0, data, ValueLayout.JAVA_BYTE, 0, packet.length); + int n = (int) DECODE.invokeExact(decoder, data, packet.length, pcm, MAX_FRAME, 0); + if (n < 0) throw new IllegalStateException("opus_multistream_decode_float: " + n); + return pcm.asSlice(0, (long) n * channels * 4).toArray(ValueLayout.JAVA_FLOAT); + } + + @Override + public void close() { + try { + DESTROY.invokeExact(decoder); + } catch (Throwable ignored) { + } + arena.close(); + } +} diff --git a/ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/recording/VoiceRecorderTest.java b/ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/recording/VoiceRecorderTest.java new file mode 100644 index 0000000..df65182 --- /dev/null +++ b/ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/recording/VoiceRecorderTest.java @@ -0,0 +1,313 @@ +package eu.lixko.ts3j.client.recording; + +import eu.lixko.ts3j.client.audio.VoiceFormat; +import eu.lixko.ts3j.client.audio.desktop.NativeOpusCodec; +import eu.lixko.ts3j.client.audio.ogg.SelfDelimitedOpus; +import eu.lixko.ts3j.client.audio.opus.OpusEncoder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Recordings decode, through libopus' own multistream decoder, to every speaker where and + * when they spoke. + */ +class VoiceRecorderTest { + + private static final int FRAME = VoiceFormat.FRAME_SIZE; + private static final long FRAME_NANOS = TimeUnit.MILLISECONDS.toNanos(20); + /** Frames the simulated recordings run for. */ + private static final int LENGTH = 250; + + @TempDir + Path dir; + + private final NativeOpusCodec opus = new NativeOpusCodec(); + + /** Who speaks when, in frames, at which pitch. */ + private record Burst(String uid, String nickname, int from, int to, double hz) { + } + + private static final List CONVERSATION = List.of( + new Burst("uidA", "Alice (renamed)", 50, 100, 440), + new Burst("uidB", "Bob", 150, 175, 660), + // After a pause long enough for a fresh encoder. + new Burst("uidA", "Alice (renamed)", 200, 210, 440)); + + @Test + void multitrackPutsEverySpeakerOnTheirOwnChannelFromTheStart() throws Throwable { + Path file = dir.resolve("multi.ogg"); + List files = record(VoiceRecorder.Mode.MULTITRACK, file, Map.of("uidA", "Alice"), CONVERSATION); + assertEquals(List.of(file), files); + + Decoded d = decode(file); + assertEquals(2, d.channels); + assertTrue(d.comments.containsAll(List.of("CHANNEL1_NAME=Alice", "CHANNEL1_UID=uidA", + "CHANNEL2_NAME=Bob", "CHANNEL2_UID=uidB")), d.comments.toString()); + assertEquals(LENGTH * FRAME, d.frames()); + + assertTone(d, 0, 50, 100, 440); + assertSilent(d, 0, 0, 49); + assertSilent(d, 0, 102, 199); + assertTone(d, 0, 200, 210, 440); + assertTone(d, 1, 150, 175, 660); + assertStartsAt(d, 0, 50); + assertStartsAt(d, 0, 200); + assertStartsAt(d, 1, 150); + assertSilent(d, 1, 0, 149); + assertSilent(d, 1, 177, LENGTH); + assertTrue(Files.list(dir).noneMatch(p -> p.getFileName().toString().startsWith(".")), "spool left behind"); + } + + @Test + void mixedPutsEveryoneOnOneMonoTrack() throws Throwable { + Path file = dir.resolve("mixed.ogg"); + record(VoiceRecorder.Mode.MIXED, file, Map.of(), CONVERSATION); + + Decoded d = decode(file); + assertEquals(1, d.channels); + assertEquals(LENGTH * FRAME, d.frames()); + assertTone(d, 0, 50, 100, 440); + assertTone(d, 0, 150, 175, 660); + assertSilent(d, 0, 0, 49); + assertSilent(d, 0, 102, 149); + } + + @Test + void moreSpeakersThanAFileHoldsContinueInTheNextFile() throws Throwable { + List crowd = new ArrayList<>(); + for (int i = 0; i < 300; i++) crowd.add(new Burst("uid" + i, "Client " + i, i % 200, i % 200 + 5, 440)); + crowd.sort((a, b) -> Integer.compare(a.from, b.from)); + Path file = dir.resolve("crowd.ogg"); + List files = record(VoiceRecorder.Mode.MULTITRACK, file, Map.of(), crowd); + assertEquals(List.of(file, dir.resolve("crowd-2.ogg")), files); + + Decoded first = decode(files.get(0)); + Decoded second = decode(files.get(1)); + assertEquals(255, first.channels); + assertEquals(45, second.channels); + assertEquals(LENGTH * FRAME, first.frames()); + assertEquals(LENGTH * FRAME, second.frames()); + // Channels go in the order speakers first spoke. + assertTone(first, 0, 0, 5, 440); + // Two speakers a frame start until frame 100, one after: the 256th first spoke at 155. + assertTone(second, 0, 155, 160, 440); + assertStartsAt(second, 0, 155); + assertSilent(second, 0, 0, 154); + } + + @Test + void multiFramePacketsAreSplitWhereLibopusSplitsThem() throws Throwable { + byte[][] f = new byte[6][]; + try (OpusEncoder encoder = RecordingEncoders.mono(opus, 48_000)) { + for (int i = 0; i < f.length; i++) f[i] = encoder.encode(tone(440 + 50 * i, i)); + } + byte[] padded = code3(f[0], f[1], 3); + byte[] code2 = cat(new byte[]{(byte) ((f[2][0] & 0xfc) | 2), (byte) (f[2].length - 1)}, + Arrays.copyOfRange(f[2], 1, f[2].length), Arrays.copyOfRange(f[3], 1, f[3].length)); + byte[] last = code3(f[4], f[5], 0); + byte[] joined = SelfDelimitedOpus.join(List.of(padded, code2, last)); + + try (LibOpusMultistream decoder = new LibOpusMultistream(3, 3, 0, new byte[]{0, 1, 2})) { + assertEquals(3 * 2 * FRAME, decoder.decode(joined).length); + } + } + + /** Two single-frame packets of one configuration as one VBR code 3 packet. */ + private static byte[] code3(byte[] a, byte[] b, int padding) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + out.write((a[0] & 0xfc) | 3); + out.write(0x80 | (padding > 0 ? 0x40 : 0) | 2); + if (padding > 0) out.write(padding); + out.write(a.length - 1); + out.write(a, 1, a.length - 1); + out.write(b, 1, b.length - 1); + out.write(new byte[padding], 0, padding); + return out.toByteArray(); + } + + private static byte[] cat(byte[]... parts) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (byte[] p : parts) out.writeBytes(p); + return out.toByteArray(); + } + + // ---- simulation ---- + + private List record(VoiceRecorder.Mode mode, Path file, Map names, List bursts) + throws Exception { + AtomicLong clock = new AtomicLong(1_000_000_000L); + long start = clock.get(); + VoiceRecorder recorder = VoiceRecorder.start(mode, file, opus, names, clock::get); + for (int f = 0; f < LENGTH; f++) { + for (Burst burst : bursts) { + if (f < burst.from || f >= burst.to) continue; + // Played a little late, as audio threads are. + clock.set(start + f * FRAME_NANOS + (f * 7919L % 5) * 1_000_000L); + recorder.offer(burst.uid, burst.nickname, tone(burst.hz, f), 1, FRAME); + } + } + clock.set(start + LENGTH * FRAME_NANOS); + List files = recorder.stop().get(60, TimeUnit.SECONDS); + String dump = System.getProperty("recording.dump"); + if (dump != null) { + for (Path p : files) Files.copy(p, Path.of(dump).resolve(p.getFileName()), StandardCopyOption.REPLACE_EXISTING); + } + return files; + } + + private static float[] tone(double hz, int frame) { + float[] pcm = new float[FRAME]; + for (int i = 0; i < FRAME; i++) { + pcm[i] = (float) (0.5 * Math.sin(2 * Math.PI * hz * ((long) frame * FRAME + i) / VoiceFormat.SAMPLE_RATE)); + } + return pcm; + } + + // ---- checks ---- + + /** A tone of {@code hz} over the frames, give or take the edges. */ + private static void assertTone(Decoded d, int channel, int from, int to, double hz) { + int start = (from + 1) * FRAME; + int end = (to - 1) * FRAME; + double energy = 0; + double sin = 0; + double cos = 0; + for (int i = start; i < end; i++) { + double x = d.sample(i, channel); + double phase = 2 * Math.PI * hz * i / VoiceFormat.SAMPLE_RATE; + sin += x * Math.sin(phase); + cos += x * Math.cos(phase); + energy += x * x; + } + double amplitude = Math.sqrt(sin * sin + cos * cos) * 2 / (end - start); + double rms = Math.sqrt(energy / (end - start)); + assertTrue(amplitude > 0.4, "channel " + channel + " frames " + from + "-" + to + ": amplitude at " + hz + " Hz " + amplitude); + assertTrue(rms > 0.3 && rms < 0.42, "channel " + channel + " frames " + from + "-" + to + ": rms " + rms); + } + + /** Sound sets in right at the frame, not faded in. */ + private static void assertStartsAt(Decoded d, int channel, int frame) { + int onset = frame * FRAME - FRAME; + while (Math.abs(d.sample(onset, channel)) < 0.05) onset++; + assertEquals(frame * FRAME, onset, 48.0, "channel " + channel + " onset"); + } + + private static void assertSilent(Decoded d, int channel, int from, int to) { + double peak = 0; + for (int i = from * FRAME; i < Math.min(to * FRAME, d.frames()); i++) peak = Math.max(peak, Math.abs(d.sample(i, channel))); + assertTrue(peak < 0.01, "channel " + channel + " frames " + from + "-" + to + ": peak " + peak); + } + + // ---- decoding ---- + + private record Decoded(int channels, List comments, float[] pcm) { + int frames() { + return pcm.length / channels; + } + + double sample(int i, int channel) { + return pcm[i * channels + channel]; + } + } + + private static Decoded decode(Path file) throws Throwable { + List packets = new ArrayList<>(); + long granule = readOgg(Files.readAllBytes(file), packets); + + ByteBuffer head = ByteBuffer.wrap(packets.get(0)).order(ByteOrder.LITTLE_ENDIAN); + assertEquals("OpusHead", new String(packets.get(0), 0, 8, StandardCharsets.US_ASCII)); + int channels = head.get(9) & 0xff; + int preSkip = head.getShort(10) & 0xffff; + int family = head.get(18) & 0xff; + int streams = 1; + int coupled = 0; + byte[] mapping = {0}; + if (family != 0) { + assertEquals(255, family); + streams = head.get(19) & 0xff; + coupled = head.get(20) & 0xff; + mapping = Arrays.copyOfRange(packets.get(0), 21, 21 + channels); + } + + ByteBuffer tags = ByteBuffer.wrap(packets.get(1)).order(ByteOrder.LITTLE_ENDIAN); + tags.position(8); + int vendor = tags.getInt(); + tags.position(tags.position() + vendor); + int count = tags.getInt(); + List comments = new ArrayList<>(); + for (int i = 0; i < count; i++) { + byte[] s = new byte[tags.getInt()]; + tags.get(s); + comments.add(new String(s, StandardCharsets.UTF_8)); + } + + float[] pcm = new float[0]; + int length = 0; + try (LibOpusMultistream decoder = new LibOpusMultistream(channels, streams, coupled, mapping)) { + for (byte[] packet : packets.subList(2, packets.size())) { + float[] out = decoder.decode(packet); + if (length + out.length > pcm.length) pcm = Arrays.copyOf(pcm, Math.max(pcm.length * 2, length + out.length)); + System.arraycopy(out, 0, pcm, length, out.length); + length += out.length; + } + } + assertTrue(granule * channels <= length, "granule past the audio"); + return new Decoded(channels, comments, Arrays.copyOfRange(pcm, preSkip * channels, (int) granule * channels)); + } + + /** Reads every packet, checking the pages' framing; returns the last page's granule position. */ + private static long readOgg(byte[] file, List packets) { + ByteBuffer in = ByteBuffer.wrap(file).order(ByteOrder.LITTLE_ENDIAN); + ByteArrayOutputStream packet = new ByteArrayOutputStream(); + long granule = -1; + int expectedSequence = 0; + boolean sawLast = false; + while (in.hasRemaining()) { + int start = in.position(); + assertEquals(0x5367674f, in.getInt(), "page sync"); + in.get(); + int flags = in.get() & 0xff; + granule = in.getLong(); + in.getInt(); + assertEquals(expectedSequence++, in.getInt(), "page sequence"); + in.getInt(); + assertEquals(packet.size() > 0, (flags & 1) != 0, "continuation flag"); + assertEquals(start == 0, (flags & 2) != 0, "first page flag"); + sawLast = (flags & 4) != 0; + int segments = in.get() & 0xff; + byte[] lacing = new byte[segments]; + in.get(lacing); + for (byte l : lacing) { + int size = l & 0xff; + byte[] data = new byte[size]; + in.get(data); + packet.writeBytes(data); + if (size < 255) { + packets.add(packet.toByteArray()); + packet.reset(); + } + } + } + assertTrue(sawLast, "last page flag"); + return granule; + } +} diff --git a/ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/sound/OggOpusFileTest.java b/ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/sound/OggOpusFileTest.java new file mode 100644 index 0000000..5cfd9f9 --- /dev/null +++ b/ts3-client/desktop/src/test/java/eu/lixko/ts3j/client/sound/OggOpusFileTest.java @@ -0,0 +1,65 @@ +package eu.lixko.ts3j.client.sound; + +import eu.lixko.ts3j.client.audio.desktop.NativeOpusCodec; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.File; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.file.Files; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** A pack converted to Opus plays back as the sound it was, found under its old name. */ +class OggOpusFileTest { + + @TempDir + File dir; + + @Test + void convertedPackPlaysTheSameSound() throws IOException { + File source = new File(dir, "wav/pack"); + Files.createDirectories(source.toPath()); + Files.writeString(new File(source, "settings.ini").toPath(), + "[info]\nname = Test\n[soundfiles]\nCONNECTION_CONNECTED = play(\"tone.wav\")\n"); + int rate = 44_100; + float[] tone = new float[rate / 2 + 123]; + for (int i = 0; i < tone.length; i++) tone[i] = (float) (0.5 * Math.sin(2 * Math.PI * 440 * i / rate)); + writeWave(new File(source, "tone.wav"), tone, rate); + + File target = new File(dir, "opus"); + NativeOpusCodec opus = new NativeOpusCodec(); + SoundPackConverter.convert(new File(dir, "wav"), target, opus); + + SoundPack pack = SoundPack.load(new File(target, "pack")); + assertNotNull(pack); + File file = pack.file("tone.wav"); + assertEquals("tone.opus", file.getName()); + + float[] expected = WaveFile.readMono(new File(source, "tone.wav")).at48k(); + float[] decoded = OggOpusFile.readMono(file, opus); + assertEquals(expected.length, decoded.length); + double dot = 0, a = 0, b = 0; + for (int i = 0; i < decoded.length; i++) { + dot += expected[i] * decoded[i]; + a += expected[i] * expected[i]; + b += decoded[i] * decoded[i]; + } + double correlation = dot / Math.sqrt(a * b); + assertTrue(correlation > 0.99, "correlation " + correlation); + } + + private static void writeWave(File file, float[] samples, int rate) throws IOException { + ByteBuffer b = ByteBuffer.allocate(44 + samples.length * 2).order(ByteOrder.LITTLE_ENDIAN); + b.put("RIFF".getBytes()).putInt(36 + samples.length * 2).put("WAVE".getBytes()); + b.put("fmt ".getBytes()).putInt(16).putShort((short) 1).putShort((short) 1) + .putInt(rate).putInt(rate * 2).putShort((short) 2).putShort((short) 16); + b.put("data".getBytes()).putInt(samples.length * 2); + for (float s : samples) b.putShort((short) Math.round(s * 32767)); + Files.write(file.toPath(), b.array()); + } +} diff --git a/ts3-client/docs/myteamspeak/CRYPTO_RE_SALT.md b/ts3-client/docs/myteamspeak/CRYPTO_RE_SALT.md index 5b92ef2..b533ebf 100644 --- a/ts3-client/docs/myteamspeak/CRYPTO_RE_SALT.md +++ b/ts3-client/docs/myteamspeak/CRYPTO_RE_SALT.md @@ -97,8 +97,8 @@ encrypt/decrypt `+0x48/+0x58`, and the little-endian CTR helper at `0xabad00`. ### Java implementation The verified constructions are implemented without an additional crypto dependency in -`core/src/main/java/com/ts3client/myts/MyTsCrypto.java` (decryption only, as the client only imports). -Captured-vector tests live in `core/src/test/java/com/ts3client/myts/MyTsCryptoTest.java`. +`core/src/main/java/eu/lixko/ts3j/client/myts/MyTsCrypto.java` (decryption only, as the client only imports). +Captured-vector tests live in `core/src/test/java/eu/lixko/ts3j/client/myts/MyTsCryptoTest.java`. The original goals were: @@ -373,6 +373,6 @@ These addresses are for `re-android/resources/lib/x86_64/libteamspeak_client.so` desktop library. The transport, protobuf codec, login, download, encryption, and low-level `synchronizeItems` call are -recovered. The client implements the read-only pull (`com.ts3client.myts`, see IMPLEMENTATION.md); +recovered. The client implements the read-only pull (`eu.lixko.ts3j.client.myts`, see IMPLEMENTATION.md); two-way sync would still need the high-level reconciliation state machine, collision policy, and a safe deletion fixture. diff --git a/ts3-client/docs/myteamspeak/IMPLEMENTATION.md b/ts3-client/docs/myteamspeak/IMPLEMENTATION.md index 578653f..fc348a4 100644 --- a/ts3-client/docs/myteamspeak/IMPLEMENTATION.md +++ b/ts3-client/docs/myteamspeak/IMPLEMENTATION.md @@ -4,7 +4,7 @@ What is implemented, and what two-way sync would still need. ## Sign-in and read-only import (done) -`core/src/main/java/com/ts3client/myts/` — pure Java, no Swing/Android dependency, and no JDK API +`core/src/main/java/eu/lixko/ts3j/client/myts/` — pure Java, no Swing/Android dependency, and no JDK API that Android 13 lacks (hence `HttpURLConnection`, not `java.net.http`). - `MyTeamSpeakLogin` — the account the client stays signed in to. Like the official client's diff --git a/ts3-client/docs/myteamspeak/PROTOCOL.md b/ts3-client/docs/myteamspeak/PROTOCOL.md index ce88a6e..6de0a9c 100644 --- a/ts3-client/docs/myteamspeak/PROTOCOL.md +++ b/ts3-client/docs/myteamspeak/PROTOCOL.md @@ -77,5 +77,5 @@ Password login, key unwrap, item encryption/integrity framing, two-phase compari manipulation flags are recovered. The remaining uncertainties are narrower: where ordinary edits rotate `sync_version_uuid`, the exact lifecycle of `last_known_version`, the official collision winner/merge policy, and instruction-level confirmation of the deletion-detail builder. Recovery-key import is also -not yet recovered. The read-only pull is implemented in `com.ts3client.myts` (see IMPLEMENTATION.md); destructive upload +not yet recovered. The read-only pull is implemented in `eu.lixko.ts3j.client.myts` (see IMPLEMENTATION.md); destructive upload should remain gated until the deletion mapping has a fixture or controlled integration test. diff --git a/ts3-client/pom.xml b/ts3-client/pom.xml index ea5889e..c7f643f 100644 --- a/ts3-client/pom.xml +++ b/ts3-client/pom.xml @@ -4,12 +4,12 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.ts3client + eu.lixko.ts3j.client ts3-client-parent 0.1.0 pom - TS3J Client (parent) + TeamSpook TS3j (parent) Desktop TeamSpeak 3 client built on the ts3j protocol library @@ -65,12 +65,12 @@ ${flatlaf.version} - com.ts3client + eu.lixko.ts3j.client ts3-client-core ${project.version} - com.ts3client + eu.lixko.ts3j.client ts3-client-desktop ${project.version} diff --git a/ts3-client/swing/pom.xml b/ts3-client/swing/pom.xml index e35142d..2a4ab49 100644 --- a/ts3-client/swing/pom.xml +++ b/ts3-client/swing/pom.xml @@ -5,26 +5,26 @@ 4.0.0 - com.ts3client + eu.lixko.ts3j.client ts3-client-parent 0.1.0 ts3-client-swing - TS3J Client Swing Frontend + TeamSpook TS3j Swing Frontend Swing desktop UI - com.ts3client.Main + eu.lixko.ts3j.client.Main - com.ts3client + eu.lixko.ts3j.client ts3-client-core - com.ts3client + eu.lixko.ts3j.client ts3-client-desktop @@ -82,7 +82,7 @@ - com.ts3client:* + eu.lixko.ts3j.client:* ** @@ -129,7 +129,7 @@ - com.ts3client.Main + eu.lixko.ts3j.client.Main ALL-UNNAMED java.desktop/sun.awt.X11 @@ -149,7 +149,7 @@ exec-maven-plugin 3.1.0 - com.ts3client.Main + eu.lixko.ts3j.client.Main diff --git a/ts3-client/swing/src/main/java/com/ts3client/Main.java b/ts3-client/swing/src/main/java/com/ts3client/Main.java deleted file mode 100644 index 0cdabfb..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/Main.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.ts3client; - -import com.ts3client.config.Settings; -import com.ts3client.session.ServerLink; -import com.ts3client.ui.DesktopEntry; -import com.ts3client.ui.DisplayScale; -import com.ts3client.ui.IconTheme; -import com.ts3client.ui.InstanceChannel; -import com.ts3client.ui.LookAndFeelManager; -import com.ts3client.ui.MainFrame; -import com.ts3client.ui.WindowClass; - -import javax.swing.SwingUtilities; -import java.util.Arrays; - -/** - * Application entry point. Loads settings, installs the look-and-feel and shows the - * main window on the Swing event dispatch thread. - */ -public final class Main { - - public static void main(String[] args) { - // ts3j is verbose by default; keep the console quiet unless asked for its protocol log - // (-Dts3j.debug=true, written to stderr). - try { - com.github.manevolent.ts3j.util.Ts3Debugging.setEnabled(Boolean.getBoolean("ts3j.debug")); - } catch (Throwable ignored) { - } - - // A link a browser opened goes to the instance already running, if there is one. - final String link = Arrays.stream(args).filter(ServerLink::isLink).findFirst().orElse(null); - if (link != null && InstanceChannel.send(link)) return; - - final Settings settings = Settings.load(); - DisplayScale.configure(settings.uiScale); - WindowClass.apply(); - - SwingUtilities.invokeLater(() -> { - LookAndFeelManager.install(settings.appearance); - IconTheme.get().reload(settings); - DesktopEntry.install(); - MainFrame frame = new MainFrame(settings); - frame.setVisible(true); - InstanceChannel.listen(href -> SwingUtilities.invokeLater(() -> frame.openLink(href))); - if (link != null) frame.openLink(link); - }); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ApplicationPanel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ApplicationPanel.java deleted file mode 100644 index a5ef683..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ApplicationPanel.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.config.Settings; - -import javax.swing.JCheckBox; -import java.awt.GridBagConstraints; - -/** Options page for general behaviour: the muted-microphone warning and the reported client version. */ -final class ApplicationPanel extends FormPanel { - - private final Settings settings; - private final JCheckBox mutedWarning; - private final ClientVersionPanel clientVersion; - - ApplicationPanel(Settings settings) { - this.settings = settings; - GridBagConstraints c = gbc(); - - mutedWarning = new JCheckBox("Warn when talking while microphone is muted", settings.mutedTalkWarning); - clientVersion = new ClientVersionPanel(settings); - - int row = 0; - addSection(this, c, row++, "Misc"); - addWide(this, c, row++, mutedWarning); - addSection(this, c, row++, "Client Version"); - addWide(this, c, row++, clientVersion); - addFiller(this, c, row); - } - - /** Copies the page into the settings; the caller saves them. */ - void apply() { - settings.mutedTalkWarning = mutedWarning.isSelected(); - clientVersion.apply(); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/AttachmentTransferHandler.java b/ts3-client/swing/src/main/java/com/ts3client/ui/AttachmentTransferHandler.java deleted file mode 100644 index bc462ee..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/AttachmentTransferHandler.java +++ /dev/null @@ -1,128 +0,0 @@ -package com.ts3client.ui; - -import javax.swing.JComponent; -import javax.swing.TransferHandler; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.datatransfer.Clipboard; -import java.awt.datatransfer.DataFlavor; -import java.awt.datatransfer.Transferable; -import java.awt.datatransfer.UnsupportedFlavorException; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -/** - * Takes files and pictures dropped or pasted onto a chat view as files to share, and leaves - * everything else (text, client links) to the component's own handler. - */ -final class AttachmentTransferHandler extends TransferHandler { - - interface Sink { - /** @return whether the files were taken */ - boolean files(List files); - - boolean image(BufferedImage image); - } - - /** How file managers that Java does not translate hand over files. */ - private static final DataFlavor URI_LIST = flavor("text/uri-list;class=java.lang.String"); - - private final TransferHandler delegate; - private final Sink sink; - - AttachmentTransferHandler(TransferHandler delegate, Sink sink) { - this.delegate = delegate; - this.sink = sink; - } - - @Override - public boolean canImport(TransferSupport support) { - if (isFiles(support.getDataFlavors()) || isPicture(support.getDataFlavors())) return true; - return delegate != null && delegate.canImport(support); - } - - @Override - public boolean importData(TransferSupport support) { - DataFlavor[] flavors = support.getDataFlavors(); - Transferable t = support.getTransferable(); - try { - if (isFiles(flavors)) { - List files = files(t); - if (!files.isEmpty()) return sink.files(files); - } else if (isPicture(flavors)) { - return sink.image(buffered((Image) t.getTransferData(DataFlavor.imageFlavor))); - } - } catch (UnsupportedFlavorException | IOException e) { - return false; - } - return delegate != null && delegate.importData(support); - } - - @Override - public int getSourceActions(JComponent c) { - return delegate == null ? NONE : delegate.getSourceActions(c); - } - - @Override - public void exportToClipboard(JComponent comp, Clipboard clip, int action) { - if (delegate != null) delegate.exportToClipboard(comp, clip, action); - } - - private static boolean isFiles(DataFlavor[] flavors) { - for (DataFlavor f : flavors) { - if (f.equals(DataFlavor.javaFileListFlavor) || f.equals(URI_LIST)) return true; - } - return false; - } - - /** A picture alone: one that comes with text is text that also offers a rendering of itself. */ - private static boolean isPicture(DataFlavor[] flavors) { - boolean image = false; - for (DataFlavor f : flavors) { - if (f.equals(DataFlavor.imageFlavor)) image = true; - else if (f.equals(DataFlavor.stringFlavor)) return false; - } - return image; - } - - @SuppressWarnings("unchecked") - private static List files(Transferable t) throws UnsupportedFlavorException, IOException { - if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { - return new ArrayList<>((List) t.getTransferData(DataFlavor.javaFileListFlavor)); - } - List files = new ArrayList<>(); - for (String line : ((String) t.getTransferData(URI_LIST)).split("\r?\n")) { - line = line.trim(); - if (line.isEmpty() || line.startsWith("#")) continue; - try { - URI uri = URI.create(line); - if (!"file".equals(uri.getScheme())) return List.of(); - files.add(new File(uri)); - } catch (IllegalArgumentException e) { - return List.of(); - } - } - return files; - } - - private static BufferedImage buffered(Image image) { - if (image instanceof BufferedImage b) return b; - BufferedImage b = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB); - Graphics2D g = b.createGraphics(); - g.drawImage(image, 0, 0, null); - g.dispose(); - return b; - } - - private static DataFlavor flavor(String mime) { - try { - return new DataFlavor(mime); - } catch (ClassNotFoundException e) { - throw new IllegalStateException(e); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/AudioDevices.java b/ts3-client/swing/src/main/java/com/ts3client/ui/AudioDevices.java deleted file mode 100644 index fd23112..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/AudioDevices.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.audio.AudioDevice; - -import javax.swing.JComboBox; -import java.util.List; - -/** The device pickers of the Playback and Capture pages. */ -final class AudioDevices { - - private static final String HINT = "Named devices are PipeWire's, and are routed through it " - + "(so per-application volume and rerouting keep working).
    " - + "ALSA: entries talk to the sound card directly, taking it exclusively."; - - private AudioDevices() { - } - - /** A picker over {@code devices} with {@code selectedId} chosen, or the first (default) one. */ - static JComboBox combo(List devices, String selectedId) { - JComboBox combo = new JComboBox<>(devices.toArray(new AudioDevice[0])); - combo.setToolTipText(HINT); - if (combo.getItemCount() == 0) return combo; - combo.setSelectedIndex(0); - if (selectedId != null && !selectedId.isEmpty()) { - for (int i = 0; i < combo.getItemCount(); i++) { - if (selectedId.equals(combo.getItemAt(i).id())) { - combo.setSelectedIndex(i); - break; - } - } - } - return combo; - } - - static String selectedId(JComboBox combo) { - AudioDevice d = (AudioDevice) combo.getSelectedItem(); - return d == null ? "" : d.id(); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/AvatarActions.java b/ts3-client/swing/src/main/java/com/ts3client/ui/AvatarActions.java deleted file mode 100644 index b615108..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/AvatarActions.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.net.ClientEntry; -import com.ts3client.net.TeamspeakConnection; -import com.ts3client.net.avatar.Avatar; - -import javax.swing.JFileChooser; -import javax.swing.JOptionPane; -import javax.swing.SwingUtilities; -import javax.swing.filechooser.FileNameExtensionFilter; -import java.awt.Component; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; - -/** Sets, takes and deletes our avatar on one server, reporting failures in a dialog. */ -final class AvatarActions { - - /** Where the last avatar was picked from, for every server alike. */ - private static File lastDirectory; - - private final Component owner; - private final TeamspeakConnection conn; - - AvatarActions(Component owner, TeamspeakConnection conn) { - this.owner = owner; - this.conn = conn; - } - - /** Asks for an image and uploads it as our avatar. */ - void choose() { - if (!conn.isConnected()) return; - JFileChooser chooser = new JFileChooser(lastDirectory); - chooser.setDialogTitle("Select your avatar"); - chooser.setFileFilter(new FileNameExtensionFilter("Images", "png", "jpg", "jpeg", "gif", "bmp")); - if (chooser.showOpenDialog(owner) != JFileChooser.APPROVE_OPTION) return; - File file = chooser.getSelectedFile(); - lastDirectory = file.getParentFile(); - conn.setAvatar(file, error -> fail("Error uploading avatar: ", error)); - } - - /** Uploads someone else's avatar as ours. */ - void steal(Avatar avatar) { - if (!conn.isConnected()) return; - File file; - try { - file = Files.createTempFile("avatar", "." + avatar.format().extension).toFile(); - Files.write(file.toPath(), avatar.data()); - } catch (IOException e) { - fail("Error uploading avatar: ", e.getMessage()); - return; - } - conn.setAvatar(file, error -> { - file.delete(); - fail("Error uploading avatar: ", error); - }); - } - - void delete() { - if (!conn.isConnected()) return; - conn.removeAvatar(error -> fail("Error deleting avatar: ", error)); - } - - /** Deletes another client's avatar for everyone. */ - void deleteOf(ClientEntry client) { - if (!conn.isConnected()) return; - conn.removeAvatarOf(client, error -> fail("Error deleting avatar: ", error)); - } - - /** Shows {@code error}, if there is one; callable from any thread. */ - private void fail(String what, String error) { - if (error == null) return; - SwingUtilities.invokeLater(() -> - JOptionPane.showMessageDialog(owner, what + error, "Error", JOptionPane.ERROR_MESSAGE)); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/AvatarHtml.java b/ts3-client/swing/src/main/java/com/ts3client/ui/AvatarHtml.java deleted file mode 100644 index 6cb76e8..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/AvatarHtml.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.net.avatar.Avatar; - -import javax.imageio.ImageIO; -import javax.imageio.ImageReader; -import javax.imageio.stream.ImageInputStream; -import java.awt.Dimension; -import java.io.ByteArrayInputStream; -import java.util.Iterator; - -/** - * Renders an avatar as an HTML {@code } for the info views. Swing's HTML renderer - * loads images by URL and plays animated GIFs on its own, so the tag simply points at - * the repository's on-disk copy, drawn at the interface scale and fitted to a box while - * keeping its aspect ratio. - */ -final class AvatarHtml { - - /** The largest box an avatar is drawn in, as in the official client's info frame. */ - static final int MAX_SIZE = 200; - - private AvatarHtml() { - } - - /** @return the tag, or an empty string if the avatar cannot be shown */ - static String imgTag(Avatar avatar, int maxSize) { - if (avatar == null || avatar.file() == null) return ""; - Dimension natural = dimensions(avatar.data()); - Dimension size = fit(natural == null ? null : UIScale.scale(natural), maxSize); - String dims = size == null ? "" : " width='" + size.width + "' height='" + size.height + "'"; - return ""; - } - - /** Reads only the image header, which is cheap even for a large animation. */ - static Dimension dimensions(byte[] data) { - try (ImageInputStream in = ImageIO.createImageInputStream(new ByteArrayInputStream(data))) { - Iterator readers = ImageIO.getImageReaders(in); - if (!readers.hasNext()) return null; - ImageReader reader = readers.next(); - try { - reader.setInput(in); - return new Dimension(reader.getWidth(0), reader.getHeight(0)); - } finally { - reader.dispose(); - } - } catch (Exception e) { - return null; - } - } - - /** Scales {@code size} down (never up) to fit a square box of {@code max}. */ - static Dimension fit(Dimension size, int max) { - if (size == null || size.width <= 0 || size.height <= 0) return null; - if (size.width <= max && size.height <= max) return size; - double scale = Math.min((double) max / size.width, (double) max / size.height); - return new Dimension(Math.max(1, (int) Math.round(size.width * scale)), - Math.max(1, (int) Math.round(size.height * scale))); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/AwayMessagesDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/AwayMessagesDialog.java deleted file mode 100644 index 8e54da6..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/AwayMessagesDialog.java +++ /dev/null @@ -1,149 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.config.AwayMessages; - -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.ListSelectionModel; -import javax.swing.table.AbstractTableModel; -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.Frame; - -/** - * Editor for the away-message presets: a plain list of entries that are renamed - * by double-clicking them, plus Add and Remove. - * - *

    Backed by a one-column table because that is what gives Swing's list look - * inline editing for free. Every change is written straight through to the - * {@link AwayMessages} store. - */ -public final class AwayMessagesDialog extends JDialog { - - private final AwayMessages messages; - private final Runnable onChanged; - private final Model model = new Model(); - private final JTable table = new JTable(model); - - public AwayMessagesDialog(Frame owner, AwayMessages messages, Runnable onChanged) { - super(owner, "Away Message Presets", true); - this.messages = messages; - this.onChanged = onChanged; - - table.setTableHeader(null); - table.setShowGrid(false); - table.setFillsViewportHeight(true); - table.setRowHeight(Math.max(UIScale.scale(20), table.getRowHeight())); - table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - // Single click selects, double click starts editing — like a renameable list. - table.putClientProperty("JTable.autoStartsEdit", Boolean.FALSE); - - JScrollPane scroll = new JScrollPane(table); - scroll.setBorder(new ScaledEmptyBorder(8, 8, 4, 8)); - - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(scroll, BorderLayout.CENTER); - getContentPane().add(buildButtons(), BorderLayout.SOUTH); - - Dialogs.closeOnEscape(this, this::closeDialog); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - setSize(UIScale.scale(new Dimension(360, 300))); - setLocationRelativeTo(owner); - } - - private JPanel buildButtons() { - JPanel buttons = new JPanel(); - buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS)); - buttons.setBorder(new ScaledEmptyBorder(0, 8, 8, 8)); - addButton(buttons, "Add", this::addEntry); - addButton(buttons, "Remove", this::removeSelected); - buttons.add(Box.createHorizontalGlue()); - addButton(buttons, "Close", this::closeDialog); - return buttons; - } - - private void addButton(JPanel panel, String text, Runnable action) { - JButton b = new JButton(text); - b.addActionListener(e -> action.run()); - panel.add(b); - panel.add(Box.createHorizontalStrut(UIScale.scale(4))); - } - - private void addEntry() { - stopEditing(); - messages.add("New away message"); - int row = messages.all().size() - 1; - model.fireTableRowsInserted(row, row); - table.setRowSelectionInterval(row, row); - table.scrollRectToVisible(table.getCellRect(row, 0, true)); - persist(); - table.editCellAt(row, 0); - if (table.getEditorComponent() != null) table.getEditorComponent().requestFocusInWindow(); - } - - private void removeSelected() { - stopEditing(); - int row = table.getSelectedRow(); - if (row < 0) return; - messages.remove(row); - model.fireTableRowsDeleted(row, row); - if (!messages.all().isEmpty()) { - int next = Math.min(row, messages.all().size() - 1); - table.setRowSelectionInterval(next, next); - } - persist(); - } - - private void closeDialog() { - stopEditing(); - dispose(); - } - - /** Flushes a cell that is still being edited so its text is not lost. */ - private void stopEditing() { - if (table.isEditing()) table.getCellEditor().stopCellEditing(); - } - - private void persist() { - messages.save(); - if (onChanged != null) onChanged.run(); - } - - private final class Model extends AbstractTableModel { - - @Override - public int getRowCount() { - return messages.all().size(); - } - - @Override - public int getColumnCount() { - return 1; - } - - @Override - public Object getValueAt(int row, int column) { - return messages.all().get(row); - } - - @Override - public boolean isCellEditable(int row, int column) { - return true; - } - - @Override - public void setValueAt(Object value, int row, int column) { - String text = value == null ? "" : value.toString().trim(); - if (text.isEmpty()) return; // an emptied entry keeps its old text - messages.set(row, text); - persist(); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/BanAddDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/BanAddDialog.java deleted file mode 100644 index 5cea0f7..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/BanAddDialog.java +++ /dev/null @@ -1,257 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.config.BanReasonPresets; -import com.ts3client.net.ban.BanEntry; -import com.ts3client.net.ban.BanPattern; -import com.ts3client.net.ban.BanRule; - -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Component; -import java.awt.Frame; - -/** - * The ban list's "Add Ban" / "Edit Ban" dialog, laid out like the official client's: - * an IP and a nickname pattern with a choice of how to read them, a unique - * identifier, a myTeamSpeak id, the reason (with saved presets) and the duration. - * - *

    OK stays disabled until the ban has at least one thing to match and its patterns - * are valid expressions; a pattern the server would reject is flagged in red. - */ -final class BanAddDialog extends JDialog { - - private static final String NO_PRESET = "None"; - private static final Color INVALID_BG = new Color(0xC0, 0x00, 0x00); - - private final BanReasonPresets presets; - private final Color fieldBg; - private final Color fieldFg; - - private final JTextField ipField = new JTextField(30); - private final JTextField nameField = new JTextField(30); - private final JComboBox patternBox = new JComboBox<>(BanPattern.values()); - private final JTextField uidField = new JTextField(30); - private final JTextField mytsidField = new JTextField(30); - private final JComboBox presetBox = new JComboBox<>(); - private final JTextField reasonField = ReasonDialog.reasonField(BanRule.REASON_LIMIT); - private final BanDurationPicker duration; - private final JButton ok = new JButton("OK"); - - private BanRule result; - - /** - * @param existing the ban being edited, or {@code null} to add a new one - * @param maxSeconds the longest ban the server lets us hand out, or 0 for no limit - */ - BanAddDialog(Frame owner, BanReasonPresets presets, BanEntry existing, long maxSeconds) { - super(owner, existing == null ? "Add Ban" : "Edit Ban", true); - this.presets = presets; - this.duration = new BanDurationPicker(maxSeconds); - fieldBg = ipField.getBackground(); - fieldFg = ipField.getForeground(); - - patternBox.setRenderer(new PatternRenderer()); - patternBox.addActionListener(e -> checkValid()); - for (JTextField f : new JTextField[] {ipField, nameField, uidField, mytsidField}) { - f.setAlignmentX(Component.LEFT_ALIGNMENT); - ReasonDialog.fixHeight(f); - onEdit(f, this::checkValid); - } - duration.onChange(this::checkValid); - reasonField.addActionListener(e -> { - if (ok.isEnabled()) accept(); - }); - - JPanel form = new JPanel(); - form.setLayout(new BoxLayout(form, BoxLayout.Y_AXIS)); - form.setBorder(new ScaledEmptyBorder(12, 12, 8, 12)); - form.add(ReasonDialog.label("IP:")); - form.add(ipField); - form.add(Box.createVerticalStrut(UIScale.scale(8))); - form.add(ReasonDialog.label("Name:")); - form.add(nameField); - form.add(Box.createVerticalStrut(UIScale.scale(8))); - form.add(patternRow()); - form.add(Box.createVerticalStrut(UIScale.scale(8))); - form.add(ReasonDialog.label("Unique ID:")); - form.add(uidField); - form.add(Box.createVerticalStrut(UIScale.scale(8))); - form.add(ReasonDialog.label("myTeamSpeak ID:")); - form.add(mytsidField); - form.add(Box.createVerticalStrut(UIScale.scale(12))); - form.add(reasonRow()); - form.add(reasonField); - form.add(Box.createVerticalStrut(UIScale.scale(8))); - form.add(ReasonDialog.label("Duration:")); - form.add(duration); - - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(form, BorderLayout.CENTER); - getContentPane().add(buttons(), BorderLayout.SOUTH); - - if (existing != null) load(existing); - rebuildPresets(); - checkValid(); - - ReasonDialog.focusWhenShown(ipField); - Dialogs.closeOnEscape(this); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - pack(); - setResizable(false); - setLocationRelativeTo(owner); - } - - // ---- construction ---- - - private JPanel patternRow() { - JPanel row = new JPanel(); - row.setLayout(new BoxLayout(row, BoxLayout.X_AXIS)); - row.setAlignmentX(Component.LEFT_ALIGNMENT); - row.add(new JLabel("Interpret IP/Name as:")); - row.add(Box.createHorizontalStrut(UIScale.scale(8))); - row.add(patternBox); - row.add(Box.createHorizontalGlue()); - ReasonDialog.fixHeight(row); - return row; - } - - private JPanel reasonRow() { - JButton save = new JButton("Save preset"); - save.addActionListener(e -> savePreset()); - presetBox.addActionListener(e -> { - int i = presetBox.getSelectedIndex(); - if (i > 0) reasonField.setText(presetBox.getItemAt(i)); - }); - - JPanel row = new JPanel(); - row.setLayout(new BoxLayout(row, BoxLayout.X_AXIS)); - row.setAlignmentX(Component.LEFT_ALIGNMENT); - row.setBorder(new ScaledEmptyBorder(0, 0, 4, 0)); - row.add(new JLabel("Reason:")); - row.add(Box.createHorizontalGlue()); - row.add(new JLabel("Preset:")); - row.add(Box.createHorizontalStrut(UIScale.scale(6))); - row.add(presetBox); - row.add(Box.createHorizontalStrut(UIScale.scale(6))); - row.add(save); - ReasonDialog.fixHeight(row); - return row; - } - - private JPanel buttons() { - JPanel panel = new JPanel(new BorderLayout()); - JPanel right = new JPanel(); - JButton cancel = new JButton("Cancel"); - ok.addActionListener(e -> accept()); - cancel.addActionListener(e -> dispose()); - right.add(ok); - right.add(cancel); - panel.add(right, BorderLayout.EAST); - getRootPane().setDefaultButton(ok); - return panel; - } - - // ---- behaviour ---- - - /** Shows an existing ban the way it was most likely typed in. */ - private void load(BanEntry ban) { - BanPattern.Decoded decoded = BanPattern.decode(ban.ip, ban.name); - patternBox.setSelectedItem(decoded.pattern); - ipField.setText(decoded.ip); - nameField.setText(decoded.name); - uidField.setText(ban.uid); - mytsidField.setText(ban.mytsid); - reasonField.setText(ban.reason); - duration.setSeconds(ban.durationSeconds); - } - - private BanPattern pattern() { - return (BanPattern) patternBox.getSelectedItem(); - } - - private BanRule rule() { - return new BanRule(pattern().ipToRegex(ipField.getText()), pattern().nameToRegex(nameField.getText()), - uidField.getText(), mytsidField.getText(), duration.getSeconds(), reasonField.getText()); - } - - private void checkValid() { - BanRule rule = rule(); - boolean ipOk = BanPattern.isValidRegex(rule.ipRegex); - boolean nameOk = BanPattern.isValidRegex(rule.nameRegex); - flag(ipField, ipOk); - flag(nameField, nameOk); - ok.setEnabled(rule.hasTarget() && ipOk && nameOk); - } - - private void flag(JTextField field, boolean valid) { - field.setBackground(valid ? fieldBg : INVALID_BG); - field.setForeground(valid ? fieldFg : Color.WHITE); - } - - private void accept() { - result = rule(); - dispose(); - } - - private void savePreset() { - String reason = reasonField.getText().trim(); - if (reason.isEmpty()) return; - presets.add(reason); - presets.save(); - rebuildPresets(); - presetBox.setSelectedIndex(1); - } - - private void rebuildPresets() { - presetBox.removeAllItems(); - presetBox.addItem(NO_PRESET); - for (String preset : presets.all()) presetBox.addItem(preset); - presetBox.setSelectedIndex(0); - } - - private static void onEdit(JTextField field, Runnable listener) { - field.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void insertUpdate(DocumentEvent e) { - listener.run(); - } - - @Override - public void removeUpdate(DocumentEvent e) { - listener.run(); - } - - @Override - public void changedUpdate(DocumentEvent e) { - listener.run(); - } - }); - } - - /** The ban as confirmed with OK, or {@code null} when the dialog was cancelled. */ - BanRule getRule() { - return result; - } - - private static final class PatternRenderer extends javax.swing.DefaultListCellRenderer { - @Override - public Component getListCellRendererComponent(javax.swing.JList list, Object value, int index, - boolean selected, boolean focused) { - super.getListCellRendererComponent(list, value, index, selected, focused); - if (value instanceof BanPattern) setText(((BanPattern) value).label()); - return this; - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/BanDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/BanDialog.java deleted file mode 100644 index 6b7a688..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/BanDialog.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.net.ban.BanRule; - -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JPanel; -import javax.swing.JTextField; -import java.awt.BorderLayout; -import java.awt.Frame; - -/** - * Asks for a ban's reason and duration, like the official client's ban dialog: - * either a number of seconds, minutes, hours or days, or permanent. - */ -final class BanDialog extends JDialog { - - private final JTextField reasonField = ReasonDialog.reasonField(BanRule.REASON_LIMIT); - private final BanDurationPicker duration; - - private boolean confirmed; - - /** - * @param maxSeconds the longest ban the server lets us hand out, or 0 for no limit - */ - BanDialog(Frame owner, String nickname, long maxSeconds) { - super(owner, "Ban Client", true); - duration = new BanDurationPicker(maxSeconds); - - JPanel form = new JPanel(); - form.setLayout(new BoxLayout(form, BoxLayout.Y_AXIS)); - form.setBorder(new ScaledEmptyBorder(12, 12, 8, 12)); - form.add(ReasonDialog.label("Ban " + nickname + " from the server.")); - form.add(Box.createVerticalStrut(UIScale.scale(8))); - form.add(ReasonDialog.label("Reason:")); - form.add(reasonField); - form.add(Box.createVerticalStrut(UIScale.scale(8))); - form.add(ReasonDialog.label("Duration:")); - form.add(duration); - - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(form, BorderLayout.CENTER); - getContentPane().add(buttons(), BorderLayout.SOUTH); - - ReasonDialog.focusWhenShown(reasonField); - Dialogs.closeOnEscape(this); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - pack(); - setResizable(false); - setLocationRelativeTo(owner); - } - - private JPanel buttons() { - JPanel panel = new JPanel(new BorderLayout()); - JPanel right = new JPanel(); - JButton ok = new JButton("Ban"); - JButton cancel = new JButton("Cancel"); - ok.addActionListener(e -> { - confirmed = true; - dispose(); - }); - cancel.addActionListener(e -> dispose()); - right.add(ok); - right.add(cancel); - panel.add(right, BorderLayout.EAST); - getRootPane().setDefaultButton(ok); - return panel; - } - - boolean isConfirmed() { - return confirmed; - } - - String getReason() { - return reasonField.getText().trim(); - } - - /** The ban's length in seconds, or 0 for a permanent ban. */ - long getSeconds() { - return duration.getSeconds(); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/BanDurationPicker.java b/ts3-client/swing/src/main/java/com/ts3client/ui/BanDurationPicker.java deleted file mode 100644 index d7bf6c8..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/BanDurationPicker.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.net.ban.BanUnit; - -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.DefaultListCellRenderer; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JSpinner; -import javax.swing.SpinnerNumberModel; -import java.awt.Component; - -/** - * A ban's length as the official client asks for it: an amount of seconds, minutes, - * hours or days, or "permanent", plus a button that jumps to the longest ban the - * server lets us hand out ({@code i_client_ban_max_bantime}). - */ -final class BanDurationPicker extends JPanel { - - private final JSpinner amount = new JSpinner(new SpinnerNumberModel(30, 1, 999_999_999, 1)); - private final JComboBox unit = new JComboBox<>(BanUnit.values()); - private final JButton max = new JButton("Max"); - - /** - * @param maxSeconds the longest ban the server allows, or 0 when there is no limit - */ - BanDurationPicker(long maxSeconds) { - setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); - setAlignmentX(Component.LEFT_ALIGNMENT); - setOpaque(false); - - unit.setSelectedItem(BanUnit.MINUTES); - unit.setRenderer(new DefaultListCellRenderer() { - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, - boolean selected, boolean focused) { - return super.getListCellRendererComponent(list, ((BanUnit) value).label(), index, selected, focused); - } - }); - unit.addActionListener(e -> amount.setEnabled(!isPermanent())); - max.setToolTipText("Set duration to maximum value"); - max.addActionListener(e -> setSeconds(maxSeconds)); - - add(amount); - add(Box.createHorizontalStrut(UIScale.scale(4))); - add(unit); - add(Box.createHorizontalStrut(UIScale.scale(4))); - add(max); - add(Box.createHorizontalGlue()); - ReasonDialog.fixHeight(this); - } - - boolean isPermanent() { - return unit() == BanUnit.PERMANENT; - } - - private BanUnit unit() { - return (BanUnit) unit.getSelectedItem(); - } - - /** The ban's length in seconds, or 0 for a permanent ban. */ - long getSeconds() { - return unit().toSeconds(((Number) amount.getValue()).longValue()); - } - - /** Shows a length in the largest unit that divides it evenly; 0 is permanent. */ - void setSeconds(long seconds) { - BanUnit fit = BanUnit.largestFor(seconds); - unit.setSelectedItem(fit); - if (fit != BanUnit.PERMANENT) amount.setValue((int) Math.min(fit.amountOf(seconds), 999_999_999)); - } - - /** Called back whenever the length changes, however it changes. */ - void onChange(Runnable listener) { - amount.addChangeListener(e -> listener.run()); - unit.addActionListener(e -> listener.run()); - } - - JSpinner amountField() { - return amount; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/BanListDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/BanListDialog.java deleted file mode 100644 index f17c459..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/BanListDialog.java +++ /dev/null @@ -1,646 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.config.BanReasonPresets; -import com.ts3client.config.Settings; -import com.ts3client.net.TeamspeakConnection; -import com.ts3client.net.ban.BanEntry; -import com.ts3client.net.ban.BanRule; - -import javax.swing.AbstractAction; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JCheckBoxMenuItem; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.KeyStroke; -import javax.swing.ListSelectionModel; -import javax.swing.RowFilter; -import javax.swing.SwingUtilities; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.table.AbstractTableModel; -import javax.swing.table.DefaultTableCellRenderer; -import javax.swing.table.JTableHeader; -import javax.swing.table.TableColumn; -import javax.swing.table.TableColumnModel; -import javax.swing.table.TableRowSorter; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Frame; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.event.ActionEvent; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.time.Instant; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * The server's ban list, as the official client's Tools > Ban List window: Add, - * Remove and Edit above a searchable table, Reload and the own-ban filters below it. - * Which columns show is chosen from the header's context menu and remembered. - * - *

    One per server tab and modeless, so it can stay open while the server is used; - * the tab closes it when the connection goes away. - */ -final class BanListDialog extends JDialog { - - private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - - /** The table's columns, in the official order; the split-out target columns start hidden. */ - private enum Column { - TARGETS("Name/IP/UID/myTSID", 280, true), - NAME("Name", 120, false), - IP("IP", 120, false), - UID("UID", 200, false), - MYTSID("myTSID", 200, false), - REASON("Reason", 160, true), - CREATOR("Creator", 100, true), - CREATED("Created", 140, true), - EXPIRES("Expires", 140, true), - ENFORCED("Enforced", 70, true); - - final String title; - final int width; - final boolean shownByDefault; - - Column(String title, int width, boolean shownByDefault) { - this.title = title; - this.width = width; - this.shownByDefault = shownByDefault; - } - } - - private final Frame owner; - private final TeamspeakConnection conn; - private final Settings settings; - private final BanReasonPresets presets; - - private final BanTableModel tableModel = new BanTableModel(); - private final JTable table = new BanTable(); - private final TableRowSorter sorter = new TableRowSorter<>(tableModel); - /** Every column the table can show, in model order, whether currently shown or not. */ - private final List allColumns = new ArrayList<>(); - private final Set visibleColumns = EnumSet.noneOf(Column.class); - - private final JButton addButton = new JButton("Add", Icons.of("ADD")); - private final JButton removeButton = new JButton("Remove", Icons.of("DELETE")); - private final JButton editButton = new JButton("Edit", Icons.of("EDIT")); - private final SearchField searchField = new SearchField(); - private final JCheckBox onlyOwn = new JCheckBox("Show only own bans"); - private final JCheckBox highlightOwn = new JCheckBox("Highlight own bans"); - private final JLabel status = new JLabel(" "); - - private boolean loading; - - BanListDialog(Frame owner, TeamspeakConnection conn, Settings settings, BanReasonPresets presets) { - super(owner, "Ban List", false); - this.owner = owner; - this.conn = conn; - this.settings = settings; - this.presets = presets; - - JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(6))); - content.setBackground(Theme.windowBg()); - content.setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); - content.add(buildToolbar(), BorderLayout.NORTH); - content.add(buildTable(), BorderLayout.CENTER); - content.add(buildBottom(), BorderLayout.SOUTH); - setContentPane(content); - bindKeys(); - - serverNameChanged(); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - setPreferredSize(UIScale.scale(new Dimension(920, 460))); - pack(); - setLocationRelativeTo(owner); - reload(); - } - - // ---- construction ---- - - private JPanel buildToolbar() { - JPanel bar = new JPanel(); - bar.setLayout(new BoxLayout(bar, BoxLayout.X_AXIS)); - bar.setOpaque(false); - - addButton.setToolTipText("Add new ban
    (Ctrl+N)"); - removeButton.setToolTipText("Remove selected bans
    (Delete)"); - editButton.setToolTipText("Edit selected ban
    (Return)"); - searchField.setToolTipText("Search bans by text
    (Ctrl+F)"); - addButton.addActionListener(e -> addBan()); - removeButton.addActionListener(e -> removeBans()); - editButton.addActionListener(e -> editBan()); - searchField.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void insertUpdate(DocumentEvent e) { - applyFilter(); - } - - @Override - public void removeUpdate(DocumentEvent e) { - applyFilter(); - } - - @Override - public void changedUpdate(DocumentEvent e) { - applyFilter(); - } - }); - searchField.setMaximumSize(new Dimension(Integer.MAX_VALUE, searchField.getPreferredSize().height)); - - bar.add(addButton); - bar.add(Box.createHorizontalStrut(UIScale.scale(6))); - bar.add(removeButton); - bar.add(Box.createHorizontalStrut(UIScale.scale(6))); - bar.add(editButton); - bar.add(Box.createHorizontalStrut(UIScale.scale(16))); - bar.add(searchField); - return bar; - } - - private JScrollPane buildTable() { - table.setFont(Theme.uiFont()); - table.setRowHeight(UIScale.scale(20)); - table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - table.setFillsViewportHeight(true); - table.setAutoCreateColumnsFromModel(false); - table.setRowSorter(sorter); - table.getSelectionModel().addListSelectionListener(e -> updateButtons()); - table.setComponentPopupMenu(tablePopup()); - table.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2 - && table.rowAtPoint(e.getPoint()) >= 0) { - editBan(); - } - } - }); - - BanCellRenderer renderer = new BanCellRenderer(); - for (Column c : Column.values()) { - TableColumn column = new TableColumn(c.ordinal(), c.width); - column.setHeaderValue(c.title); - column.setCellRenderer(renderer); - allColumns.add(column); - } - visibleColumns.addAll(savedColumns()); - applyColumns(); - - JTableHeader header = table.getTableHeader(); - header.setReorderingAllowed(true); - header.addMouseListener(new MouseAdapter() { - @Override - public void mousePressed(MouseEvent e) { - if (e.isPopupTrigger()) headerPopup().show(header, e.getX(), e.getY()); - } - - @Override - public void mouseReleased(MouseEvent e) { - if (e.isPopupTrigger()) headerPopup().show(header, e.getX(), e.getY()); - } - }); - - JScrollPane scroll = new JScrollPane(table); - scroll.getViewport().setBackground(Theme.treeBg()); - return scroll; - } - - private JPanel buildBottom() { - JButton reload = new JButton("Reload", Icons.of("REFRESH")); - reload.addActionListener(e -> reload()); - onlyOwn.setToolTipText("Show only bans created by you"); - onlyOwn.setOpaque(false); - onlyOwn.addActionListener(e -> applyFilter()); - highlightOwn.setToolTipText("Mark bans created by you as bold"); - highlightOwn.setOpaque(false); - highlightOwn.setSelected(settings.banHighlightOwn); - highlightOwn.addActionListener(e -> { - settings.banHighlightOwn = highlightOwn.isSelected(); - settings.save(); - table.repaint(); - }); - - JPanel options = new JPanel(); - options.setLayout(new BoxLayout(options, BoxLayout.X_AXIS)); - options.setOpaque(false); - options.add(reload); - options.add(Box.createHorizontalStrut(UIScale.scale(12))); - options.add(onlyOwn); - options.add(Box.createHorizontalStrut(UIScale.scale(12))); - options.add(highlightOwn); - options.add(Box.createHorizontalGlue()); - - JButton close = new JButton("Close"); - close.addActionListener(e -> dispose()); - JPanel closeRow = new JPanel(new BorderLayout()); - closeRow.setOpaque(false); - closeRow.add(close, BorderLayout.EAST); - - JPanel bottom = new JPanel(new BorderLayout(0, UIScale.scale(8))); - bottom.setOpaque(false); - bottom.add(status, BorderLayout.NORTH); - bottom.add(options, BorderLayout.CENTER); - bottom.add(closeRow, BorderLayout.SOUTH); - status.setForeground(Theme.chatEvent()); - return bottom; - } - - private JPopupMenu tablePopup() { - JPopupMenu menu = new JPopupMenu(); - menu.add(item("Add", "ADD", this::addBan)); - menu.add(item("Remove", "DELETE", this::removeBans)); - menu.add(item("Edit", "EDIT", this::editBan)); - menu.addSeparator(); - menu.add(item("Reload", "REFRESH", this::reload)); - return menu; - } - - private static JMenuItem item(String text, String icon, Runnable action) { - JMenuItem item = new JMenuItem(text, Icons.of(icon)); - item.addActionListener(e -> action.run()); - return item; - } - - private JPopupMenu headerPopup() { - JPopupMenu menu = new JPopupMenu(); - for (Column c : Column.values()) { - JCheckBoxMenuItem item = new JCheckBoxMenuItem(c.title, visibleColumns.contains(c)); - // the last column stays, or there would be nothing left to right-click on - item.setEnabled(!item.isSelected() || visibleColumns.size() > 1); - item.addActionListener(e -> { - if (item.isSelected()) visibleColumns.add(c); - else visibleColumns.remove(c); - applyColumns(); - saveColumns(); - }); - menu.add(item); - } - return menu; - } - - private void bindKeys() { - bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control N"), this::addBan); - bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control F"), - searchField::requestFocusInWindow); - bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control W"), this::dispose); - bind(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), - this::removeBans); - bind(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), - this::editBan); - Dialogs.closeOnEscape(this); - } - - private static void bind(JComponent target, int condition, KeyStroke key, Runnable action) { - String name = "ts3-banlist-" + key; - target.getInputMap(condition).put(key, name); - target.getActionMap().put(name, new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - action.run(); - } - }); - } - - // ---- columns ---- - - private Set savedColumns() { - Set columns = EnumSet.noneOf(Column.class); - for (String name : settings.banListColumns.split(",")) { - try { - if (!name.isBlank()) columns.add(Column.valueOf(name.trim())); - } catch (IllegalArgumentException ignored) { - // a column from another version; skipped - } - } - if (columns.isEmpty()) { - for (Column c : Column.values()) if (c.shownByDefault) columns.add(c); - } - return columns; - } - - private void saveColumns() { - settings.banListColumns = visibleColumns.stream().map(Enum::name).collect(Collectors.joining(",")); - settings.save(); - } - - /** Rebuilds the column model so it holds exactly the visible columns, in model order. */ - private void applyColumns() { - TableColumnModel columns = table.getColumnModel(); - while (columns.getColumnCount() > 0) columns.removeColumn(columns.getColumn(0)); - for (TableColumn column : allColumns) { - if (visibleColumns.contains(Column.values()[column.getModelIndex()])) columns.addColumn(column); - } - } - - // ---- data ---- - - /** Follows the server's name, as the official window's "Ban List - " title does. */ - void serverNameChanged() { - String name = conn.getModel().getServerName(); - setTitle(name == null || name.isBlank() ? "Ban List" : "Ban List - " + name); - } - - /** The connection is gone; a ban list without a server is meaningless. */ - void connectionLost() { - dispose(); - } - - private void reload() { - if (loading) return; - loading = true; - status.setText("Loading…"); - conn.requestBanList((bans, error) -> SwingUtilities.invokeLater(() -> { - loading = false; - if (!isDisplayable()) return; - if (error != null) { - tableModel.setBans(List.of()); - status.setText(isPermissionError(error) - ? "You have insufficient permissions to view the ban list." - : "Failed to request ban list: " + error); - updateButtons(); - return; - } - tableModel.setBans(bans); - status.setText(bans.size() == 1 ? "1 ban" : bans.size() + " bans"); - updateButtons(); - })); - } - - private static boolean isPermissionError(String message) { - String m = message.toLowerCase(Locale.ROOT); - return m.contains("insufficient") || m.contains("permission"); - } - - private void applyFilter() { - String needle = searchField.getText().trim().toLowerCase(Locale.ROOT); - boolean own = onlyOwn.isSelected(); - String self = conn.getSelfUniqueId(); - sorter.setRowFilter(new RowFilter<>() { - @Override - public boolean include(Entry entry) { - BanEntry ban = tableModel.get(entry.getIdentifier()); - if (own && !ban.createdBy(self)) return false; - if (needle.isEmpty()) return true; - for (Column c : Column.values()) { - if (tableModel.text(ban, c).toLowerCase(Locale.ROOT).contains(needle)) return true; - } - return false; - } - }); - } - - private List selectedBans() { - List selected = new ArrayList<>(); - for (int row : table.getSelectedRows()) selected.add(tableModel.get(table.convertRowIndexToModel(row))); - return selected; - } - - // ---- permissions ---- - - private boolean can(String permission) { - return conn.getModel().permits(permission); - } - - private boolean canDelete(List bans) { - return conn.getModel().canDeleteBans(bans, conn.getSelfUniqueId()); - } - - private void updateButtons() { - List selected = selectedBans(); - addButton.setEnabled(can("b_client_ban_create")); - removeButton.setEnabled(!selected.isEmpty() && canDelete(selected)); - editButton.setEnabled(selected.size() == 1 && conn.getModel().canEditBan(selected.get(0), conn.getSelfUniqueId())); - } - - // ---- actions ---- - - private long maxBanSeconds() { - return conn.getModel().maxBanSeconds(); - } - - private void addBan() { - if (!addButton.isEnabled()) return; - BanAddDialog dialog = new BanAddDialog(owner, presets, null, maxBanSeconds()); - dialog.setVisible(true); - BanRule rule = dialog.getRule(); - if (rule == null) return; - conn.addBan(rule, error -> afterChange(error, "Error adding ban: ", - () -> JOptionPane.showMessageDialog(this, "Your ban was successfully added.", "Ban List", - JOptionPane.INFORMATION_MESSAGE))); - } - - private void editBan() { - if (!editButton.isEnabled()) return; - BanEntry ban = selectedBans().get(0); - BanAddDialog dialog = new BanAddDialog(owner, presets, ban, maxBanSeconds()); - dialog.setVisible(true); - BanRule rule = dialog.getRule(); - if (rule == null) return; - conn.replaceBan(ban.id, rule, error -> afterChange(error, "Error editing ban: ", null)); - } - - private void removeBans() { - if (!removeButton.isEnabled()) return; - List bans = selectedBans(); - int answer = JOptionPane.showConfirmDialog(this, "Do you really want to delete the selected ban(s)?", - "Delete bans", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); - if (answer != JOptionPane.YES_OPTION) return; - List ids = bans.stream().map(b -> b.id).collect(Collectors.toList()); - conn.deleteBans(ids, error -> afterChange(error, "Error deleting ban: ", null)); - } - - /** Reports a failed change, or re-reads the list so the table shows what the server now holds. */ - private void afterChange(String error, String errorPrefix, Runnable onSuccess) { - SwingUtilities.invokeLater(() -> { - if (!isDisplayable()) return; - if (error != null) { - JOptionPane.showMessageDialog(this, errorPrefix + error, "Ban List", JOptionPane.ERROR_MESSAGE); - } else if (onSuccess != null) { - onSuccess.run(); - } - reload(); - }); - } - - // ---- table ---- - - private final class BanTableModel extends AbstractTableModel { - - private List bans = List.of(); - - void setBans(List bans) { - this.bans = new ArrayList<>(bans); - fireTableDataChanged(); - } - - BanEntry get(int row) { - return bans.get(row); - } - - @Override - public int getRowCount() { - return bans.size(); - } - - @Override - public int getColumnCount() { - return Column.values().length; - } - - @Override - public String getColumnName(int column) { - return Column.values()[column].title; - } - - @Override - public Class getColumnClass(int column) { - switch (Column.values()[column]) { - case CREATED: - case EXPIRES: - return Long.class; - case ENFORCED: - return Integer.class; - default: - return String.class; - } - } - - /** Sortable values: the date columns sort by time, with "infinite" last. */ - @Override - public Object getValueAt(int row, int column) { - BanEntry ban = bans.get(row); - switch (Column.values()[column]) { - case CREATED: - return ban.createdEpochSeconds; - case EXPIRES: - return ban.isPermanent() ? Long.MAX_VALUE : ban.expiresEpochSeconds(); - case ENFORCED: - return ban.enforcements; - default: - return text(ban, Column.values()[column]); - } - } - - /** What a cell shows (and what the search field matches). */ - String text(BanEntry ban, Column column) { - switch (column) { - case TARGETS: - return ban.targets(); - case NAME: - return ban.name; - case IP: - return ban.ip; - case UID: - return ban.uid; - case MYTSID: - return ban.mytsid; - case REASON: - return ban.reason; - case CREATOR: - return ban.invokerName; - case CREATED: - return date(ban.createdEpochSeconds); - case EXPIRES: - return ban.isPermanent() ? "infinite" : date(ban.expiresEpochSeconds()); - case ENFORCED: - return Integer.toString(ban.enforcements); - default: - return ""; - } - } - } - - private static String date(long epochSeconds) { - if (epochSeconds <= 0) return ""; - return DATE.format(Instant.ofEpochSecond(epochSeconds).atZone(ZoneId.systemDefault())); - } - - /** Shows the displayed text for every column and bolds our own bans when asked to. */ - private final class BanCellRenderer extends DefaultTableCellRenderer { - @Override - public Component getTableCellRendererComponent(JTable t, Object value, boolean selected, - boolean focused, int row, int column) { - BanEntry ban = tableModel.get(t.convertRowIndexToModel(row)); - Column c = Column.values()[t.convertColumnIndexToModel(column)]; - super.getTableCellRendererComponent(t, tableModel.text(ban, c), selected, focused, row, column); - boolean bold = highlightOwn.isSelected() && ban.createdBy(conn.getSelfUniqueId()); - setFont(bold ? Theme.uiBold() : Theme.uiFont()); - setHorizontalAlignment(c == Column.ENFORCED ? RIGHT : LEFT); - return this; - } - } - - /** A table whose rows carry the official client's tooltip of a ban's details. */ - private final class BanTable extends JTable { - BanTable() { - super(tableModel); - } - - @Override - public String getToolTipText(MouseEvent e) { - int row = rowAtPoint(e.getPoint()); - if (row < 0) return null; - BanEntry ban = tableModel.get(convertRowIndexToModel(row)); - return "" - + tooltipRow("Last name", ban.lastNickname) - + tooltipRow("Creator", ban.invokerName) - + tooltipRow("Created", date(ban.createdEpochSeconds)) - + tooltipRow("Expires", ban.isPermanent() ? "infinite" : date(ban.expiresEpochSeconds())) - + tooltipRow("Enforced", Integer.toString(ban.enforcements)) - + "
    "; - } - } - - private static String tooltipRow(String label, String value) { - return "" + label + ":" + escape(value) - + ""; - } - - private static String escape(String s) { - return s.replace("&", "&").replace("<", "<").replace(">", ">"); - } - - /** A text field that shows "Search" while it is empty. */ - private static final class SearchField extends javax.swing.JTextField { - SearchField() { - super(20); - } - - @Override - protected void paintComponent(Graphics g) { - super.paintComponent(g); - if (!getText().isEmpty()) return; - Graphics2D g2 = (Graphics2D) g.create(); - g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - g2.setColor(Theme.chatEvent()); - g2.setFont(getFont().deriveFont(Font.ITALIC)); - int y = (getHeight() + g2.getFontMetrics().getAscent() - g2.getFontMetrics().getDescent()) / 2; - g2.drawString("Search", getInsets().left + UIScale.scale(2), y); - g2.dispose(); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/BookmarksDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/BookmarksDialog.java deleted file mode 100644 index b761516..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/BookmarksDialog.java +++ /dev/null @@ -1,318 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.config.Bookmark; -import com.ts3client.config.Bookmarks; -import com.ts3client.config.IdentityStore; -import com.ts3client.config.Settings; -import com.ts3client.teamspeak.TeamSpeakImporter; -import com.ts3client.teamspeak.TeamSpeakSettingsDb; - -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.DefaultListCellRenderer; -import javax.swing.DefaultListModel; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JPasswordField; -import javax.swing.JScrollPane; -import javax.swing.JSplitPane; -import javax.swing.JTextField; -import javax.swing.ListSelectionModel; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Frame; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.io.File; -import java.util.function.Consumer; - -/** - * Manage saved servers. Two columns: the bookmark list on the left, the - * selected bookmark's settings on the right. Edits are applied to the selected - * bookmark as soon as the selection changes or the dialog is closed. - */ -public final class BookmarksDialog extends JDialog { - - private final Bookmarks bookmarks; - private final IdentityStore identities; - private final Settings settings; - private final Consumer onConnect; - private final Runnable onChanged; - private final DefaultListModel listModel = new DefaultListModel<>(); - private final JList list = new JList<>(listModel); - - private final JTextField label = new JTextField(); - private final JTextField address = new JTextField(); - private final JTextField port = new JTextField(); - private final JTextField nick = new JTextField(); - private final JPasswordField password = new JPasswordField(); - private final JTextField channel = new JTextField(); - private final JPasswordField channelPassword = new JPasswordField(); - private final JCheckBox connectOnStartup = new JCheckBox("Connect on startup"); - private final IdentityChooser identity; - - private final JPanel details; - - /** Bookmark the form currently shows, so edits can be flushed back into it. */ - private Bookmark editing; - - public BookmarksDialog(Frame owner, Bookmarks bookmarks, IdentityStore identities, Settings settings, - Consumer onConnect, Runnable onChanged) { - super(owner, "Manage Bookmarks", true); - this.bookmarks = bookmarks; - this.identities = identities; - this.settings = settings; - this.onConnect = onConnect; - this.onChanged = onChanged; - this.identity = new IdentityChooser(identities, true, ""); - - list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - list.setVisibleRowCount(12); - list.setCellRenderer(new DefaultListCellRenderer() { - @Override - public Component getListCellRendererComponent(JList l, Object value, int index, - boolean selected, boolean focused) { - super.getListCellRendererComponent(l, value, index, selected, focused); - ImageIcon icon = GroupIcons.cached(((Bookmark) value).iconId); - setIcon(icon != null ? icon : Icons.of("SERVER_GREEN")); - return this; - } - }); - list.addListSelectionListener(e -> { - if (!e.getValueIsAdjusting()) onSelectionChanged(); - }); - - details = buildDetails(); - - JScrollPane listScroll = new JScrollPane(list); - listScroll.setPreferredSize(UIScale.scale(new Dimension(180, 320))); - - JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, listScroll, details); - split.setBorder(new ScaledEmptyBorder(8, 8, 4, 8)); - split.setResizeWeight(0.3); - split.setContinuousLayout(true); - - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(split, BorderLayout.CENTER); - getContentPane().add(buildButtons(), BorderLayout.SOUTH); - - reload(); - if (!listModel.isEmpty()) list.setSelectedIndex(0); - else showBookmark(null); - - Dialogs.closeOnEscape(this, this::closeDialog); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - addWindowListener(new java.awt.event.WindowAdapter() { - @Override - public void windowClosing(java.awt.event.WindowEvent e) { - commit(); - persist(); - } - }); - setSize(UIScale.scale(new Dimension(640, 400))); - setLocationRelativeTo(owner); - } - - // ---- UI construction ---- - - private JPanel buildDetails() { - JPanel panel = new JPanel(new GridBagLayout()); - panel.setBorder(new ScaledEmptyBorder(0, 8, 0, 0)); - - channel.setToolTipText("Channel path, e.g. \"Lobby/Games\", or a channel id. " - + "Leave empty for the server's default channel."); - connectOnStartup.setToolTipText("Connect to this server automatically when the client starts. " - + "Several bookmarks may be flagged; each opens its own tab."); - - int row = 0; - addRow(panel, row++, "Label:", label); - addRow(panel, row++, "Address:", address); - addRow(panel, row++, "Port:", port); - addRow(panel, row++, "Nickname:", nick); - addRow(panel, row++, "Password:", password); - addRow(panel, row++, "Default channel:", channel); - addRow(panel, row++, "Channel password:", channelPassword); - addRow(panel, row++, "Identity:", identity); - addRow(panel, row++, "", connectOnStartup); - - GridBagConstraints filler = new GridBagConstraints(); - filler.gridx = 0; - filler.gridy = row; - filler.weighty = 1; - filler.fill = GridBagConstraints.VERTICAL; - panel.add(Box.createVerticalGlue(), filler); - return panel; - } - - private void addRow(JPanel panel, int row, String text, java.awt.Component field) { - GridBagConstraints c = new GridBagConstraints(); - c.gridy = row; - c.insets = UIScale.scale(new Insets(2, 0, 2, 4)); - c.anchor = GridBagConstraints.WEST; - c.gridx = 0; - panel.add(new JLabel(text), c); - c.gridx = 1; - c.weightx = 1; - c.fill = GridBagConstraints.HORIZONTAL; - panel.add(field, c); - } - - private JPanel buildButtons() { - JPanel buttons = new JPanel(); - buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS)); - buttons.setBorder(new ScaledEmptyBorder(0, 8, 8, 8)); - addButton(buttons, "Add", this::addBookmark); - addButton(buttons, "Remove", this::removeSelected); - if (TeamSpeakSettingsDb.locate() != null) { - addButton(buttons, "Import from TeamSpeak 3…", this::importFromTeamSpeak) - .setToolTipText("Add the bookmarks of the TeamSpeak 3 client installed on this computer, " - + "along with the identities they connect with"); - } - buttons.add(Box.createHorizontalGlue()); - addButton(buttons, "Connect", this::connectSelected); - addButton(buttons, "Close", this::closeDialog); - return buttons; - } - - private JButton addButton(JPanel panel, String text, Runnable action) { - JButton b = new JButton(text); - b.addActionListener(e -> action.run()); - panel.add(b); - panel.add(Box.createHorizontalStrut(UIScale.scale(4))); - return b; - } - - // ---- Form <-> model ---- - - private void onSelectionChanged() { - commit(); - showBookmark(list.getSelectedValue()); - } - - private void showBookmark(Bookmark b) { - editing = b; - setEnabledRecursively(details, b != null); - label.setText(b == null ? "" : nullToEmpty(b.label)); - address.setText(b == null ? "" : nullToEmpty(b.address)); - port.setText(b == null ? "" : Integer.toString(b.port)); - nick.setText(b == null ? "" : nullToEmpty(b.nickname)); - password.setText(b == null ? "" : nullToEmpty(b.password)); - channel.setText(b == null ? "" : nullToEmpty(b.channel)); - channelPassword.setText(b == null ? "" : nullToEmpty(b.channelPassword)); - connectOnStartup.setSelected(b != null && b.connectOnStartup); - identity.setSelectedIdentityId(b == null ? "" : nullToEmpty(b.identityId)); - } - - /** Writes the form back into the bookmark it was loaded from. */ - private void commit() { - if (editing == null) return; - editing.label = label.getText().trim(); - editing.address = address.getText().trim(); - try { - editing.port = Integer.parseInt(port.getText().trim()); - } catch (NumberFormatException e) { - editing.port = 9987; - } - editing.nickname = nick.getText().trim(); - editing.password = new String(password.getPassword()); - editing.channel = channel.getText().trim(); - editing.channelPassword = new String(channelPassword.getPassword()); - editing.identityId = identity.getSelectedIdentityId(); - editing.connectOnStartup = connectOnStartup.isSelected(); - list.repaint(); - } - - // ---- Actions ---- - - private void addBookmark() { - commit(); - Bookmark b = new Bookmark("New bookmark", "", 9987, - System.getProperty("user.name", "TS3J User"), ""); - bookmarks.add(b); - reload(); - list.setSelectedValue(b, true); - persist(); - label.requestFocusInWindow(); - } - - private void removeSelected() { - int idx = list.getSelectedIndex(); - if (idx < 0) return; - editing = null; // dropped, nothing to flush back - bookmarks.remove(idx); - reload(); - if (!listModel.isEmpty()) list.setSelectedIndex(Math.min(idx, listModel.size() - 1)); - else showBookmark(null); - persist(); - } - - private void importFromTeamSpeak() { - File db = TeamSpeakSettingsDb.locate(); - if (db == null) return; - commit(); - try { - TeamSpeakImporter.Result result = new TeamSpeakImporter(identities, bookmarks, settings).importBookmarks(db); - identity.reload(); - reload(); - if (result.bookmarksAdded() > 0) list.setSelectedIndex(listModel.size() - result.bookmarksAdded()); - persist(); - JOptionPane.showMessageDialog(this, result.bookmarks() + " bookmark(s) read from " + db - + "\n" + result.bookmarksAdded() + " new, " + result.bookmarksKnown() + " already present; " - + result.identitiesAdded() + " identit" + (result.identitiesAdded() == 1 ? "y" : "ies") + " imported.", - "Import from TeamSpeak 3", JOptionPane.INFORMATION_MESSAGE); - } catch (Exception e) { - JOptionPane.showMessageDialog(this, "Could not read " + db + ":\n" + e.getMessage(), - "Import from TeamSpeak 3", JOptionPane.ERROR_MESSAGE); - } - } - - private void connectSelected() { - commit(); - Bookmark b = list.getSelectedValue(); - if (b == null) return; - if (b.address == null || b.address.isBlank()) { - JOptionPane.showMessageDialog(this, "Address is required."); - return; - } - persist(); - onConnect.accept(b); - dispose(); - } - - private void closeDialog() { - commit(); - persist(); - dispose(); - } - - private void reload() { - listModel.clear(); - for (Bookmark b : bookmarks.all()) listModel.addElement(b); - } - - private void persist() { - bookmarks.save(); - if (onChanged != null) onChanged.run(); - } - - private static void setEnabledRecursively(java.awt.Container container, boolean enabled) { - for (java.awt.Component c : container.getComponents()) { - c.setEnabled(enabled); - if (c instanceof java.awt.Container child) setEnabledRecursively(child, enabled); - } - } - - private static String nullToEmpty(String s) { - return s == null ? "" : s; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/CapturePanel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/CapturePanel.java deleted file mode 100644 index a41e9bd..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/CapturePanel.java +++ /dev/null @@ -1,129 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.audio.AudioBackend; -import com.ts3client.audio.AudioDevice; -import com.ts3client.audio.VoiceInput; -import com.ts3client.config.Settings; - -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JSlider; -import java.awt.GridBagConstraints; -import java.util.function.Consumer; -import java.util.function.Supplier; - -/** - * Options page for everything on the way from the microphone to the server: the capture - * device and gain, how transmission is activated (with the microphone test), the - * pre-processing. Changes preview live on the connected microphone and the test alike. - */ -final class CapturePanel extends FormPanel { - - private static final String[] DENOISE_STEPS = {"Off", "6 dB", "12 dB", "18 dB", "21 dB"}; - - private final VoiceInput liveMic; - private final VoiceActivationSection activation; - - private final JComboBox inputCombo; - private final JSlider inputGain; - private final JSlider denoise; - private final JCheckBox typingCheck; - private final JCheckBox agcCheck; - private final JSlider agcBoost; - - CapturePanel(Settings settings, AudioBackend audio, VoiceInput liveMic, HotkeyService hotkeys, - HotkeysPanel hotkeysPanel, Supplier audioSnapshot) { - this.liveMic = liveMic; - this.activation = new VoiceActivationSection(settings, audio, liveMic, hotkeys, hotkeysPanel, audioSnapshot); - GridBagConstraints c = gbc(); - - inputCombo = AudioDevices.combo(audio.io().inputDevices(), settings.inputDevice); - limitWidth(inputCombo, FIELD_WIDTH); - inputCombo.addActionListener(e -> activation.restartTest()); - - inputGain = new JSlider(0, 200, (int) Math.round(settings.inputVolume * 100)); - JLabel gainLabel = new JLabel(inputGain.getValue() + "%"); - inputGain.addChangeListener(e -> { - gainLabel.setText(inputGain.getValue() + "%"); - applyLive(m -> m.setInputGain(inputGain.getValue() / 100.0)); - }); - - // Off, then TS3's four denoiser_level steps. - denoise = new JSlider(0, DENOISE_STEPS.length - 1, - settings.denoise ? Math.max(0, Math.min(3, settings.denoiserLevel)) + 1 : 0); - denoise.setMajorTickSpacing(1); - denoise.setPaintTicks(true); - denoise.setSnapToTicks(true); - JLabel denoiseLabel = new JLabel(DENOISE_STEPS[denoise.getValue()]); - typingCheck = new JCheckBox("Typing attenuation", settings.typingAttenuation); - agcCheck = new JCheckBox("Automatic gain control", settings.agc); - agcBoost = new JSlider(0, Settings.MAX_AGC_BOOST_DB, settings.agcBoostDb); - agcBoost.setMajorTickSpacing(5); - agcBoost.setPaintTicks(true); - limitWidth(agcBoost, SLIDER_WIDTH); - agcBoost.setToolTipText("Lets AGC bring up a quiet or distant voice further, " - + "at the cost of up to this many dB more background noise (0–20 dB)."); - - int row = 0; - addSection(this, c, row++, "Device"); - addRow(this, c, row++, new JLabel("Capture device:"), inputCombo); - addRow(this, c, row++, new JLabel("Microphone gain:"), sliderWithLabel(inputGain, gainLabel)); - addSection(this, c, row++, "Activation"); - row = activation.layOut(this, c, row); - addSection(this, c, row++, "Digital Signal Processing"); - addRow(this, c, row++, new JLabel("Remove background noise:"), sliderWithLabel(denoise, denoiseLabel)); - addWide(this, c, row++, typingCheck); - addWide(this, c, row++, agcCheck); - addRow(this, c, row++, new JLabel("Boost quiet speech:"), agcBoost); - addFiller(this, c, row); - - Runnable syncProcessing = () -> { - agcBoost.setEnabled(agcCheck.isSelected()); - applyLive(m -> { - applyDenoise(m); - m.setTypingAttenuation(typingCheck.isSelected()); - m.setAgc(agcCheck.isSelected()); - }); - }; - typingCheck.addActionListener(e -> syncProcessing.run()); - agcCheck.addActionListener(e -> syncProcessing.run()); - denoise.addChangeListener(e -> { - denoiseLabel.setText(DENOISE_STEPS[denoise.getValue()]); - applyLive(this::applyDenoise); - }); - agcBoost.addChangeListener(e -> applyLive(m -> m.setAgcBoost(agcBoost.getValue()))); - syncProcessing.run(); - } - - /** Copies the page into {@code target}, without touching anything else. */ - void writeInto(Settings target) { - target.inputDevice = AudioDevices.selectedId(inputCombo); - target.inputVolume = inputGain.getValue() / 100.0; - target.denoise = denoise.getValue() > 0; - if (target.denoise) target.denoiserLevel = denoise.getValue() - 1; - target.typingAttenuation = typingCheck.isSelected(); - target.agc = agcCheck.isSelected(); - target.agcBoostDb = agcBoost.getValue(); - activation.writeInto(target); - } - - private void applyDenoise(VoiceInput mic) { - mic.setNoiseSuppression(denoise.getValue() > 0); - if (denoise.getValue() > 0) mic.setDenoiserLevel(denoise.getValue() - 1); - } - - /** Applies a live change to the connected microphone and to the microphone test alike. */ - void applyLive(Consumer change) { - if (liveMic != null) change.accept(liveMic); - activation.configureTest(change); - } - - void setTestOutputDevice(String deviceId) { - activation.setTestOutputDevice(deviceId); - } - - void stopTest() { - activation.stopTest(); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ChannelAdvancedPanel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ChannelAdvancedPanel.java deleted file mode 100644 index 56ffd54..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ChannelAdvancedPanel.java +++ /dev/null @@ -1,199 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.net.ChannelSettings; - -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.ButtonGroup; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JSpinner; -import javax.swing.JTextField; -import javax.swing.SpinnerNumberModel; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; - -/** - * The channel editor's "Advanced" tab: the phonetic name, the delete delay of a temporary - * channel, voice encryption, and the two client limits. - */ -final class ChannelAdvancedPanel extends JPanel implements ChannelDialog.Tab { - - private final JTextField phoneticName = new JTextField(); - private final JSpinner deleteDelay = - Spinners.compact(new JSpinner(new SpinnerNumberModel(0, 0, ChannelSettings.MAX_DELETE_DELAY, 1))); - private final JButton deleteDelayMax = new JButton("max"); - private final JCheckBox encrypted = new JCheckBox("Voice Data encrypted"); - - private final JRadioButton maxUsersUnlimited = new JRadioButton("Unlimited"); - private final JRadioButton maxUsersLimited = new JRadioButton("Limited"); - private final JSpinner maxUsers = Spinners.compact(new JSpinner(new SpinnerNumberModel(16, 0, 65535, 1))); - - private final JRadioButton familyInherited = new JRadioButton("Inherited"); - private final JRadioButton familyUnlimited = new JRadioButton("Unlimited"); - private final JRadioButton familyLimited = new JRadioButton("Limited"); - private final JSpinner familyMaxUsers = - Spinners.compact(new JSpinner(new SpinnerNumberModel(16, 0, 65535, 1))); - - ChannelAdvancedPanel() { - setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); - setBorder(new ScaledEmptyBorder(8, 8, 8, 8)); - - phoneticName.setToolTipText("Set phonetic nickname used for this channel by text-to-speech."); - deleteDelay.setToolTipText("

    Delay in seconds after temporary channels are deleted" - + " after the last user left the channel.

    "); - deleteDelayMax.setToolTipText("Set delete delay to maximum value"); - deleteDelayMax.addActionListener(a -> deleteDelay.setValue(ChannelSettings.MAX_DELETE_DELAY)); - encrypted.setToolTipText("Voice data in this channel will be encrypted."); - - ButtonGroup users = new ButtonGroup(); - users.add(maxUsersUnlimited); - users.add(maxUsersLimited); - maxUsersUnlimited.setToolTipText("Unlimited number of clients can join this channel."); - maxUsersLimited.setToolTipText("Limit number of clients in this channel."); - maxUsersUnlimited.addActionListener(a -> syncLimits()); - maxUsersLimited.addActionListener(a -> syncLimits()); - - ButtonGroup family = new ButtonGroup(); - family.add(familyInherited); - family.add(familyUnlimited); - family.add(familyLimited); - familyInherited.setToolTipText("Inherit the client limit by parent channel."); - familyUnlimited.setToolTipText("The channel subtree can be joined by unlimited number of clients."); - familyLimited.setToolTipText("Limit the number of clients in the channel subtree."); - for (JRadioButton radio : new JRadioButton[]{familyInherited, familyUnlimited, familyLimited}) { - radio.addActionListener(a -> syncLimits()); - } - - JPanel other = otherSettings(); - other.setAlignmentX(0f); - fixHeight(other); - add(other); - add(Box.createVerticalStrut(UIScale.scale(6))); - - JPanel limits = new JPanel(); - limits.setLayout(new BoxLayout(limits, BoxLayout.X_AXIS)); - limits.add(limitBox("Max Users", new JRadioButton[]{maxUsersUnlimited, maxUsersLimited}, maxUsers)); - limits.add(Box.createHorizontalStrut(UIScale.scale(8))); - limits.add(limitBox("Family Max Users", - new JRadioButton[]{familyInherited, familyUnlimited, familyLimited}, familyMaxUsers)); - limits.setAlignmentX(0f); - fixHeight(limits); - add(limits); - add(Box.createVerticalGlue()); - } - - /** The delete delay only means anything for a channel that disappears on its own. */ - void setChannelType(ChannelSettings.Type type) { - boolean temporary = type == ChannelSettings.Type.TEMPORARY; - deleteDelay.setEnabled(temporary); - deleteDelayMax.setEnabled(temporary); - } - - @Override - public void read(ChannelSettings settings) { - phoneticName.setText(settings.phoneticName); - deleteDelay.setValue(Math.min(ChannelSettings.MAX_DELETE_DELAY, Math.max(0, settings.deleteDelay))); - encrypted.setSelected(settings.encrypted); - - if (settings.maxClientsUnlimited) maxUsersUnlimited.setSelected(true); - else maxUsersLimited.setSelected(true); - maxUsers.setValue(settings.maxClients); - - if (settings.familyInherited) familyInherited.setSelected(true); - else if (settings.familyUnlimited) familyUnlimited.setSelected(true); - else familyLimited.setSelected(true); - familyMaxUsers.setValue(settings.maxFamilyClients); - - setChannelType(settings.type); - syncLimits(); - } - - @Override - public void write(ChannelSettings settings) { - settings.phoneticName = phoneticName.getText(); - settings.deleteDelay = (Integer) deleteDelay.getValue(); - settings.encrypted = encrypted.isSelected(); - settings.maxClientsUnlimited = maxUsersUnlimited.isSelected(); - settings.maxClients = (Integer) maxUsers.getValue(); - settings.familyInherited = familyInherited.isSelected(); - settings.familyUnlimited = familyUnlimited.isSelected(); - settings.maxFamilyClients = (Integer) familyMaxUsers.getValue(); - } - - private void syncLimits() { - maxUsers.setEnabled(maxUsersLimited.isSelected()); - familyMaxUsers.setEnabled(familyLimited.isSelected()); - } - - private JPanel otherSettings() { - JPanel panel = new JPanel(new GridBagLayout()); - panel.setBorder(BorderFactory.createTitledBorder("Other Settings")); - GridBagConstraints c = new GridBagConstraints(); - c.insets = UIScale.scale(new Insets(3, 4, 3, 4)); - c.anchor = GridBagConstraints.WEST; - c.fill = GridBagConstraints.HORIZONTAL; - - c.gridx = 0; - c.gridy = 0; - panel.add(new JLabel("Phonetic Name:"), c); - c.gridx = 1; - c.weightx = 1; - panel.add(phoneticName, c); - - c.gridx = 0; - c.gridy = 1; - c.weightx = 0; - panel.add(new JLabel("Delete delay:"), c); - JPanel delay = new JPanel(new FlowLayout(FlowLayout.LEFT, UIScale.scale(4), 0)); - delay.add(deleteDelay); - delay.add(deleteDelayMax); - c.gridx = 1; - c.weightx = 1; - panel.add(delay, c); - - c.gridx = 1; - c.gridy = 2; - panel.add(encrypted, c); - return panel; - } - - /** - * A limit box: its choices stacked, with the count beside the last of them — - * "Limited", the only choice it belongs to. - */ - private JPanel limitBox(String title, JRadioButton[] choices, JSpinner spinner) { - JPanel box = new JPanel(); - box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS)); - box.setBorder(BorderFactory.createTitledBorder(title)); - for (int i = 0; i < choices.length; i++) { - JRadioButton radio = choices[i]; - radio.setAlignmentX(0f); - if (i < choices.length - 1) { - box.add(radio); - continue; - } - JPanel row = new JPanel(new FlowLayout(FlowLayout.LEFT, UIScale.scale(6), 0)); - row.setAlignmentX(0f); - row.add(radio); - row.add(spinner); - box.add(row); - } - box.add(Box.createVerticalGlue()); - return box; - } - - /** Keeps a section at its natural height, so the free space collects at the bottom. */ - private static void fixHeight(JPanel panel) { - panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, panel.getPreferredSize().height)); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ChannelAudioPanel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ChannelAudioPanel.java deleted file mode 100644 index 83b96f6..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ChannelAudioPanel.java +++ /dev/null @@ -1,153 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.net.ChannelCodec; -import com.ts3client.net.ChannelSettings; - -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.ButtonGroup; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JSlider; -import java.awt.BorderLayout; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; - -/** - * The channel editor's "Audio" tab: the codec preset, or the codec and quality picked by - * hand, with the bandwidth one talking client then costs. - */ -final class ChannelAudioPanel extends JPanel implements ChannelDialog.Tab { - - private final JRadioButton voiceMobile = new JRadioButton("Voice Mobile"); - private final JRadioButton voiceDesktop = new JRadioButton("Voice Desktop"); - private final JRadioButton music = new JRadioButton("Music"); - private final JRadioButton custom = new JRadioButton("Custom"); - private final JComboBox codec = new JComboBox<>(ChannelCodec.NAMES); - private final JSlider quality = new JSlider(0, 10, 6); - private final JLabel qualityValue = new JLabel("6"); - private final JLabel bandwidth = new JLabel(); - private final JPanel customSettings = new JPanel(new GridBagLayout()); - - ChannelAudioPanel() { - super(new BorderLayout(UIScale.scale(8), UIScale.scale(8))); - setBorder(new ScaledEmptyBorder(8, 8, 8, 8)); - - ButtonGroup presets = new ButtonGroup(); - presets.add(voiceMobile); - presets.add(voiceDesktop); - presets.add(music); - presets.add(custom); - voiceMobile.addActionListener(a -> applyPreset(ChannelCodec.Preset.VOICE_MOBILE)); - voiceDesktop.addActionListener(a -> applyPreset(ChannelCodec.Preset.VOICE_DESKTOP)); - music.addActionListener(a -> applyPreset(ChannelCodec.Preset.MUSIC)); - custom.addActionListener(a -> setCustomEnabled(true)); - - codec.addActionListener(a -> updateBandwidth()); - quality.setMajorTickSpacing(1); - quality.setPaintTicks(true); - quality.setSnapToTicks(true); - quality.addChangeListener(e -> updateBandwidth()); - - add(presetBox(), BorderLayout.WEST); - add(customBox(), BorderLayout.CENTER); - add(bandwidthRow(), BorderLayout.SOUTH); - } - - @Override - public void read(ChannelSettings settings) { - codec.setSelectedIndex(ChannelCodec.clampCodec(settings.codec)); - quality.setValue(Math.max(0, Math.min(ChannelCodec.MAX_QUALITY, settings.codecQuality))); - ChannelCodec.Preset preset = ChannelCodec.Preset.of(settings.codec, settings.codecQuality); - if (preset == null) custom.setSelected(true); - else switch (preset) { - case VOICE_MOBILE -> voiceMobile.setSelected(true); - case VOICE_DESKTOP -> voiceDesktop.setSelected(true); - case MUSIC -> music.setSelected(true); - } - setCustomEnabled(custom.isSelected()); - updateBandwidth(); - } - - @Override - public void write(ChannelSettings settings) { - settings.codec = codec.getSelectedIndex(); - settings.codecQuality = quality.getValue(); - } - - private void applyPreset(ChannelCodec.Preset preset) { - codec.setSelectedIndex(preset.codec); - quality.setValue(preset.quality); - setCustomEnabled(false); - updateBandwidth(); - } - - private void setCustomEnabled(boolean enabled) { - customSettings.setEnabled(enabled); - for (java.awt.Component child : customSettings.getComponents()) child.setEnabled(enabled); - } - - private void updateBandwidth() { - qualityValue.setText(Integer.toString(quality.getValue())); - bandwidth.setText(ChannelCodec.bandwidthText(codec.getSelectedIndex(), quality.getValue())); - } - - private JPanel presetBox() { - JPanel box = new JPanel(); - box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS)); - box.setBorder(BorderFactory.createTitledBorder("Presets")); - for (JRadioButton radio : new JRadioButton[]{voiceMobile, voiceDesktop, music, custom}) { - radio.setAlignmentX(0f); - box.add(radio); - } - box.add(Box.createVerticalGlue()); - return box; - } - - private JPanel customBox() { - customSettings.setBorder(BorderFactory.createTitledBorder("Custom Settings")); - GridBagConstraints c = new GridBagConstraints(); - c.insets = UIScale.scale(new Insets(4, 4, 4, 4)); - c.anchor = GridBagConstraints.WEST; - c.fill = GridBagConstraints.HORIZONTAL; - - c.gridx = 0; - c.gridy = 0; - customSettings.add(new JLabel("Codec:"), c); - c.gridx = 1; - c.weightx = 1; - c.gridwidth = 2; - customSettings.add(codec, c); - - c.gridwidth = 1; - c.gridx = 0; - c.gridy = 1; - c.weightx = 0; - customSettings.add(new JLabel("Quality:"), c); - c.gridx = 1; - c.weightx = 1; - customSettings.add(quality, c); - c.gridx = 2; - c.weightx = 0; - customSettings.add(qualityValue, c); - - c.gridx = 0; - c.gridy = 2; - c.weighty = 1; - customSettings.add(Box.createVerticalGlue(), c); - return customSettings; - } - - private JPanel bandwidthRow() { - JPanel row = new JPanel(new BorderLayout(UIScale.scale(6), 0)); - row.add(new JLabel("Bandwidth usage:"), BorderLayout.WEST); - row.add(bandwidth, BorderLayout.CENTER); - return row; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ChannelDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ChannelDialog.java deleted file mode 100644 index 293c147..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ChannelDialog.java +++ /dev/null @@ -1,434 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.net.ChannelNode; -import com.ts3client.net.ChannelSettings; -import com.ts3client.net.TeamspeakConnection; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JPasswordField; -import javax.swing.JPopupMenu; -import javax.swing.JScrollPane; -import javax.swing.JTabbedPane; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.SwingUtilities; -import javax.swing.Timer; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.Window; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.List; -import java.util.Map; - -/** - * TeamSpeak's channel editor: the channel's name, icon, password, topic and description - * above four tabs holding everything else. The official client uses the same dialog to - * create a channel and to edit one, and so does this. - * - *

    When editing, the channel's properties are not in the tree model — the tree only - * carries what the server pushes for display — so the dialog opens empty and fills itself - * from a {@code channelinfo}, with its own permissions arriving separately. Saving sends - * only what was actually changed, because a {@code channeledit} carrying one property the - * client may not modify is refused as a whole. - * - *

    When creating, there is nothing to read: the dialog starts from the defaults its - * caller chose and sends a {@code channelcreate} carrying whatever deviates from a plain - * new channel, for the same reason. - */ -final class ChannelDialog extends JDialog { - - /** A tab that maps a part of the channel's settings onto its controls. */ - interface Tab { - void read(ChannelSettings settings); - - void write(ChannelSettings settings); - } - - /** How long, and how often, to keep looking for a channel icon that is still downloading. */ - private static final int ICON_RETRY_MS = 500; - private static final int ICON_RETRIES = 20; - - /** What the password field shows for an existing password, which is never readable. */ - private static final String PASSWORD_PLACEHOLDER = "••••••••"; - - private static final String NAME_TOOLTIP = "Name of this channel displayed in the tree." - + "" - + "" - + "" - + "" - + "" - + "" - + "" - + "" - + "" - + "
    Syntax: \"[?Spacer#]Text\"
    Where \"?\" stands for an alignment" - + " (r=right, c=center, l=left),
    \"*\" will repeat the text to fill the whole line.
    Change \"#\" to get a unique channel name.
    [lSpacer0] a left aligned text
    [cSpacer1] a centered text
    [rSpacer2] a right aligned text
    Use one of the three-character-blocks as text for a" - + " special spacer: \"---\", \"...\", \"-.-\", \"___\", \"-..\"
    "; - - private final TeamspeakConnection conn; - private final GroupIcons groupIcons; - /** The channel being edited, or {@code null} when a new one is being created. */ - private final ChannelNode channel; - /** Where a new channel goes; 0 is the top level. Unused when editing. */ - private final int parentId; - - private final JTextField name = new JTextField(); - private final JPasswordField password = new JPasswordField(); - private final JTextField topic = new JTextField(); - private final JTextArea description = new JTextArea(5, 40); - private final JButton iconButton = new JButton(); - private final JButton ok = new JButton("OK"); - - private final ChannelStandardPanel standardPanel; - private final ChannelAudioPanel audioPanel = new ChannelAudioPanel(); - private final ChannelPermissionsPanel permissionsPanel = new ChannelPermissionsPanel(); - private final ChannelAdvancedPanel advancedPanel = new ChannelAdvancedPanel(); - - /** The tabs backed by {@link ChannelSettings}; the permissions tab has its own source. */ - private final List settingsTabs; - - /** The channel as the server last described it; the baseline every change is measured against. */ - private ChannelSettings original; - private long iconId; - private boolean passwordEdited; - - /** The editor for an existing channel. */ - static ChannelDialog toEdit(Window owner, TeamspeakConnection conn, GroupIcons groupIcons, - ChannelNode channel) { - return new ChannelDialog(owner, conn, groupIcons, "Edit Channel: " + channel.name, - channel, channel.parentId, null); - } - - /** - * The editor for a channel that does not exist yet. - * - * @param parentId the channel it goes below, 0 being the top level - * @param defaults what the dialog opens with, e.g. the channel type its caller prefers - */ - static ChannelDialog toCreate(Window owner, TeamspeakConnection conn, GroupIcons groupIcons, - String title, int parentId, ChannelSettings defaults) { - return new ChannelDialog(owner, conn, groupIcons, title, null, parentId, defaults); - } - - private ChannelDialog(Window owner, TeamspeakConnection conn, GroupIcons groupIcons, String title, - ChannelNode channel, int parentId, ChannelSettings defaults) { - super(owner, title, ModalityType.APPLICATION_MODAL); - this.conn = conn; - this.groupIcons = groupIcons; - this.channel = channel; - this.parentId = parentId; - this.standardPanel = new ChannelStandardPanel(channel != null - ? conn.getModel().siblingsOf(channel.id) : conn.getModel().childrenOf(parentId)); - - standardPanel.onTypeChanged(advancedPanel::setChannelType); - settingsTabs = List.of(standardPanel, audioPanel, advancedPanel); - - JTabbedPane tabs = new JTabbedPane(); - tabs.addTab("Standard", standardPanel); - tabs.addTab("Audio", audioPanel); - tabs.addTab("Permissions", permissionsPanel); - tabs.addTab("Advanced", advancedPanel); - - // The tabs need no more than their natural height, so they sit at the bottom - // with the buttons and every spare pixel goes to the description instead. - JPanel bottom = new JPanel(new BorderLayout(0, UIScale.scale(6))); - bottom.add(tabs, BorderLayout.CENTER); - bottom.add(buttons(), BorderLayout.SOUTH); - - getContentPane().setLayout(new BorderLayout(0, UIScale.scale(6))); - getContentPane().add(header(), BorderLayout.CENTER); - getContentPane().add(bottom, BorderLayout.SOUTH); - - setEnabledForLoading(false); - Dialogs.closeOnEscape(this); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - setSize(UIScale.scale(new Dimension(560, 620))); - setMinimumSize(UIScale.scale(new Dimension(480, 520))); - setLocationRelativeTo(owner); - - if (channel != null) load(); - else prepareNew(defaults); - } - - // ---- layout ---- - - private JPanel header() { - JPanel panel = new JPanel(new GridBagLayout()); - panel.setBorder(new ScaledEmptyBorder(8, 8, 0, 8)); - GridBagConstraints c = new GridBagConstraints(); - c.insets = UIScale.scale(new Insets(3, 4, 3, 4)); - c.anchor = GridBagConstraints.WEST; - c.fill = GridBagConstraints.HORIZONTAL; - - name.setToolTipText(NAME_TOOLTIP); - password.setToolTipText("Optional password for this channel."); - topic.setToolTipText("Optional topic for this channel, displayed in the info area on the right."); - password.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void insertUpdate(DocumentEvent e) { - passwordEdited = true; - } - - @Override - public void removeUpdate(DocumentEvent e) { - passwordEdited = true; - } - - @Override - public void changedUpdate(DocumentEvent e) { - passwordEdited = true; - } - }); - - c.gridx = 0; - c.gridy = 0; - panel.add(new JLabel("Name:"), c); - c.gridx = 1; - c.weightx = 1; - panel.add(name, c); - c.gridx = 2; - c.weightx = 0; - panel.add(iconField(), c); - - c.gridx = 0; - c.gridy = 1; - panel.add(new JLabel("Password:"), c); - c.gridx = 1; - c.gridwidth = 2; - c.weightx = 1; - panel.add(password, c); - - c.gridwidth = 1; - c.gridx = 0; - c.gridy = 2; - c.weightx = 0; - panel.add(new JLabel("Topic:"), c); - c.gridx = 1; - c.gridwidth = 2; - c.weightx = 1; - panel.add(topic, c); - - c.gridwidth = 1; - c.gridx = 0; - c.gridy = 3; - c.weightx = 0; - panel.add(new JLabel("Description:"), c); - JButton popOut = new JButton("Edit…"); - popOut.setToolTipText("Tear off description editor"); - popOut.addActionListener(a -> editDescription()); - c.gridx = 1; - c.gridwidth = 2; - c.fill = GridBagConstraints.NONE; - panel.add(popOut, c); - - description.setLineWrap(true); - description.setWrapStyleWord(true); - c.gridx = 0; - c.gridy = 4; - c.gridwidth = 3; - c.weightx = 1; - c.weighty = 1; - c.fill = GridBagConstraints.BOTH; - panel.add(new JScrollPane(description), c); - return panel; - } - - private JPanel iconField() { - iconButton.setToolTipText("Set channel icon."); - iconButton.setPreferredSize(UIScale.scale(new Dimension(26, 24))); - iconButton.setMargin(new Insets(1, 1, 1, 1)); - iconButton.addActionListener(a -> chooseIcon()); - iconButton.addMouseListener(new MouseAdapter() { - @Override - public void mousePressed(MouseEvent e) { - if (e.isPopupTrigger()) showIconMenu(e); - } - - @Override - public void mouseReleased(MouseEvent e) { - if (e.isPopupTrigger()) showIconMenu(e); - } - }); - JPanel row = new JPanel(new BorderLayout(UIScale.scale(4), 0)); - row.add(new JLabel("Icon:"), BorderLayout.WEST); - row.add(iconButton, BorderLayout.CENTER); - return row; - } - - private JPanel buttons() { - JButton cancel = new JButton("Cancel"); - ok.addActionListener(a -> save()); - cancel.addActionListener(a -> dispose()); - JPanel panel = new JPanel(new BorderLayout()); - panel.setBorder(new ScaledEmptyBorder(0, 8, 8, 8)); - JPanel right = new JPanel(); - right.add(ok); - right.add(cancel); - panel.add(right, BorderLayout.EAST); - getRootPane().setDefaultButton(ok); - return panel; - } - - // ---- loading ---- - - private void load() { - conn.requestChannelSettings(channel.id, (settings, error) -> SwingUtilities.invokeLater(() -> { - if (error != null) { - JOptionPane.showMessageDialog(this, "Could not read the channel: " + error, - "Error", JOptionPane.ERROR_MESSAGE); - dispose(); - return; - } - apply(settings); - })); - conn.requestChannelPermissions(channel.id, (permissions, error) -> SwingUtilities.invokeLater(() -> { - if (error != null) permissionsPanel.showUnavailable("No permission to view channel permissions."); - else permissionsPanel.read(permissions); - })); - } - - /** - * Opens the dialog on a channel that does not exist yet. Its permissions start empty - * and editable — they are applied to the channel once the server has created it. - */ - private void prepareNew(ChannelSettings defaults) { - permissionsPanel.read(Map.of()); - apply(defaults); - name.selectAll(); - } - - private void apply(ChannelSettings settings) { - original = settings; - name.setText(settings.name); - topic.setText(settings.topic); - description.setText(settings.description); - description.setCaretPosition(0); - if (settings.hasPassword) password.setText(PASSWORD_PLACEHOLDER); - passwordEdited = false; - setIconId(settings.iconId); - for (Tab tab : settingsTabs) tab.read(settings); - setEnabledForLoading(true); - name.requestFocusInWindow(); - } - - private void setEnabledForLoading(boolean loaded) { - ok.setEnabled(loaded); - name.setEnabled(loaded); - password.setEnabled(loaded); - topic.setEnabled(loaded); - description.setEnabled(loaded); - iconButton.setEnabled(loaded); - } - - // ---- icon ---- - - private void setIconId(long id) { - setIconId(id, ICON_RETRIES); - } - - /** - * @param retries how many more times to look for an icon that is still downloading; - * one that never arrives (deleted, or not ours to read) simply stays blank - */ - private void setIconId(long id, int retries) { - iconId = id; - ImageIcon icon = groupIcons.icon(id); - iconButton.setIcon(icon); - if (icon != null || id == 0 || retries <= 0) return; - Timer retry = new Timer(ICON_RETRY_MS, null); - retry.setRepeats(false); - retry.addActionListener(e -> { - if (iconId == id) setIconId(id, retries - 1); - }); - retry.start(); - } - - private void chooseIcon() { - IconChooserDialog chooser = new IconChooserDialog(this, conn, groupIcons); - chooser.setVisible(true); - if (chooser.isAccepted()) setIconId(chooser.getIconId()); - } - - private void showIconMenu(MouseEvent e) { - JPopupMenu menu = new JPopupMenu(); - JMenuItem edit = new JMenuItem("Edit Icon"); - edit.addActionListener(a -> chooseIcon()); - JMenuItem remove = new JMenuItem("Remove Icon"); - remove.setEnabled(iconId != 0); - remove.addActionListener(a -> setIconId(0)); - menu.add(edit); - menu.add(remove); - menu.show(e.getComponent(), e.getX(), e.getY()); - } - - // ---- description ---- - - private void editDescription() { - DescriptionEditorDialog editor = new DescriptionEditorDialog(this, description.getText()); - editor.setVisible(true); - if (editor.isAccepted()) description.setText(editor.getDescription()); - } - - // ---- saving ---- - - private void save() { - if (original == null) return; - ChannelSettings edited = original.copy(); - edited.name = name.getText().trim(); - edited.topic = topic.getText(); - edited.description = description.getText(); - edited.password = passwordEdited ? new String(password.getPassword()) : null; - edited.iconId = iconId; - for (Tab tab : settingsTabs) tab.write(edited); - - if (edited.name.isEmpty()) { - JOptionPane.showMessageDialog(this, "The channel needs a name.", - "Error", JOptionPane.ERROR_MESSAGE); - return; - } - - if (channel == null) { - ok.setEnabled(false); - conn.createChannel(parentId, edited.creationParameters(), permissionsPanel.changed(), - (channelId, error) -> SwingUtilities.invokeLater( - () -> finish(error, "Could not create the channel: "))); - return; - } - - Map changes = edited.changesFrom(original); - Map setPermissions = permissionsPanel.changed(); - List clearedPermissions = permissionsPanel.cleared(); - if (changes.isEmpty() && setPermissions.isEmpty() && clearedPermissions.isEmpty()) { - dispose(); - return; - } - - ok.setEnabled(false); - conn.applyChannelEdit(channel.id, changes, setPermissions, clearedPermissions, - error -> SwingUtilities.invokeLater(() -> finish(error, "Could not save the channel: "))); - } - - /** Closes the dialog, or reports why the server would not have it and lets the user retry. */ - private void finish(String error, String errorPrefix) { - if (error == null) { - dispose(); - return; - } - ok.setEnabled(true); - JOptionPane.showMessageDialog(this, errorPrefix + error, "Error", JOptionPane.ERROR_MESSAGE); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ChannelMenu.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ChannelMenu.java deleted file mode 100644 index 6db883d..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ChannelMenu.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.net.ChannelNode; -import com.ts3client.net.ChannelSettings; - -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; - -/** - * The context menu for a channel, shared by the server tree and channel links - * in the chat log. - */ -final class ChannelMenu { - - private ChannelMenu() { - } - - static JPopupMenu build(ChannelNode channel, ServerTreePanel.Actions actions) { - JPopupMenu menu = new JPopupMenu(); - JMenuItem join = new JMenuItem("Join channel", Icons.of("CHANNEL_SWITCH")); - join.addActionListener(a -> actions.joinChannel(channel.id)); - menu.add(join); - menu.addSeparator(); - // Both start out temporary: a channel made from another channel's menu is - // usually a throwaway one, and a permanent channel is a deliberate choice. - JMenuItem create = new JMenuItem("Create Channel", Icons.of("CHANNEL_CREATE")); - create.addActionListener(a -> actions.createChannel(null, ChannelSettings.Type.TEMPORARY)); - menu.add(create); - JMenuItem createSub = new JMenuItem("Create Sub-Channel", Icons.of("CHANNEL_CREATE_SUB")); - createSub.addActionListener(a -> actions.createChannel(channel, ChannelSettings.Type.TEMPORARY)); - menu.add(createSub); - JMenuItem edit = new JMenuItem("Edit Channel", Icons.of("CHANNEL_EDIT")); - edit.addActionListener(a -> actions.editChannel(channel)); - menu.add(edit); - JMenuItem delete = new JMenuItem("Delete Channel", Icons.of("CHANNEL_DELETE")); - delete.addActionListener(a -> actions.deleteChannel(channel)); - menu.add(delete); - menu.addSeparator(); - addSubscriptionItems(menu, channel, actions); - JMenuItem files = new JMenuItem("Browse files", Icons.of("FILETRANSFER")); - files.addActionListener(a -> actions.browseFiles(channel)); - menu.add(files); - return menu; - } - - /** - * The subscription entries, offered the way the official client does: the channel - * itself toggles, and the family entries appear only where they would do something. - */ - private static void addSubscriptionItems(JPopupMenu menu, ChannelNode channel, - ServerTreePanel.Actions actions) { - if (channel.subscribed) { - add(menu, "Unsubscribe from Channel", - () -> actions.setChannelSubscribed(channel, false, false), - "UNSUBSCRIBE_FROM_CHANNEL"); - } else { - add(menu, "Subscribe to Channel", - () -> actions.setChannelSubscribed(channel, false, true), - "SUBSCRIBE_TO_CHANNEL"); - } - if (!channel.children.isEmpty()) { - if (!channel.allSubscribed()) { - add(menu, "Subscribe to Channel Family", - () -> actions.setChannelSubscribed(channel, true, true), - "SUBSCRIBE_TO_CHANNEL_FAMILY", "SUBSCRIBE_TO_ALL_CHANNELS"); - } - if (channel.anySubscribed()) { - add(menu, "Unsubscribe from Channel Family", - () -> actions.setChannelSubscribed(channel, true, false), - "UNSUBSCRIBE_FROM_CHANNEL_FAMILY", "UNSUBSCRIBE_FROM_ALL_CHANNELS"); - } - } - menu.addSeparator(); - } - - /** Adds an item, icon-less when the pack has none of the given keys. */ - private static void add(JPopupMenu menu, String text, Runnable action, String... iconKeys) { - JMenuItem item = new JMenuItem(text, Icons.ofAny(iconKeys)); - item.addActionListener(a -> action.run()); - menu.add(item); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ChannelPermissionsPanel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ChannelPermissionsPanel.java deleted file mode 100644 index 00e978b..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ChannelPermissionsPanel.java +++ /dev/null @@ -1,151 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; - -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSpinner; -import javax.swing.SpinnerNumberModel; -import java.awt.Color; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * The channel editor's "Permissions" tab: the needed-power permissions set on the channel - * itself, which is the subset of channel permissions TeamSpeak surfaces here. - * - *

    These are not channel properties but permissions, so they are read with - * {@code channelpermlist} and written with {@code channeladdperm}. A power left at zero is - * not a permission the channel carries: clearing a spinner back to zero removes the - * permission again so the channel inherits it, which is how the official client behaves. - */ -final class ChannelPermissionsPanel extends JPanel { - - /** The regular powers, in the order the official dialog lists them. */ - private static final String[][] REGULAR = { - {"i_channel_needed_join_power", "Join:"}, - {"i_channel_needed_subscribe_power", "Subscribe:"}, - {"i_channel_needed_description_view_power", "Desc. View:"}, - {"i_channel_needed_modify_power", "Modify:"}, - {"i_channel_needed_delete_power", "Delete:"}}; - - private static final String[][] FILE_TRANSFER = { - {"i_ft_needed_file_browse_power", "Browse:"}, - {"i_ft_needed_file_upload_power", "Upload:"}, - {"i_ft_needed_file_download_power", "Download:"}, - {"i_ft_needed_file_rename_power", "Rename:"}, - {"i_ft_needed_directory_create_power", "Dir. Create:"}}; - - private final Map spinners = new LinkedHashMap<>(); - /** The values the server reported, to tell an edited power from an untouched one. */ - private final Map original = new LinkedHashMap<>(); - private final JLabel status = new JLabel(" "); - - ChannelPermissionsPanel() { - setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); - setBorder(new ScaledEmptyBorder(8, 8, 8, 8)); - - JPanel groups = new JPanel(); - groups.setLayout(new BoxLayout(groups, BoxLayout.X_AXIS)); - groups.add(group("Regular Needed Powers", REGULAR)); - groups.add(Box.createHorizontalStrut(UIScale.scale(8))); - groups.add(group("File Transfer Needed Powers", FILE_TRANSFER)); - groups.setAlignmentX(0f); - add(groups); - - status.setAlignmentX(0f); - status.setBorder(new ScaledEmptyBorder(6, 2, 0, 2)); - add(status); - add(Box.createVerticalGlue()); - setEditable(false); - } - - /** Fills the spinners from a {@code channelpermlist} result and enables editing. */ - void read(Map permissions) { - original.clear(); - for (Map.Entry entry : spinners.entrySet()) { - int value = permissions.getOrDefault(entry.getKey(), 0); - original.put(entry.getKey(), value); - entry.getValue().setValue(value); - } - setEditable(true); - setStatus(" ", false); - } - - /** Greys the tab out with a reason, e.g. when the server refuses to show the permissions. */ - void showUnavailable(String message) { - setEditable(false); - setStatus(message, true); - } - - /** The permissions whose power was changed to a non-zero value. */ - Map changed() { - Map changed = new LinkedHashMap<>(); - for (Map.Entry entry : spinners.entrySet()) { - int value = (Integer) entry.getValue().getValue(); - if (value != 0 && value != original.getOrDefault(entry.getKey(), 0)) { - changed.put(entry.getKey(), value); - } - } - return changed; - } - - /** The permissions cleared back to zero, which are removed from the channel. */ - List cleared() { - List cleared = new ArrayList<>(); - for (Map.Entry entry : spinners.entrySet()) { - int value = (Integer) entry.getValue().getValue(); - if (value == 0 && original.getOrDefault(entry.getKey(), 0) != 0) cleared.add(entry.getKey()); - } - return cleared; - } - - void setStatus(String message, boolean error) { - status.setText(message == null || message.isEmpty() ? " " : message); - status.setForeground(error ? Color.RED.darker() : Theme.chatSystem()); - } - - private void setEditable(boolean editable) { - for (JSpinner spinner : spinners.values()) spinner.setEnabled(editable); - } - - private JPanel group(String title, String[][] permissions) { - JPanel panel = new JPanel(new GridBagLayout()); - panel.setBorder(BorderFactory.createTitledBorder(title)); - GridBagConstraints c = new GridBagConstraints(); - c.insets = UIScale.scale(new Insets(3, 4, 3, 4)); - c.anchor = GridBagConstraints.WEST; - c.fill = GridBagConstraints.HORIZONTAL; - int row = 0; - for (String[] permission : permissions) { - JSpinner spinner = Spinners.compact(new JSpinner(new SpinnerNumberModel(0, 0, 9999, 1))); - spinners.put(permission[0], spinner); - c.gridx = 0; - c.gridy = row; - c.weightx = 0; - panel.add(new JLabel(permission[1]), c); - c.gridx = 1; - c.weightx = 1; - c.fill = GridBagConstraints.NONE; - panel.add(spinner, c); - c.fill = GridBagConstraints.HORIZONTAL; - row++; - } - // Keeps the rows at the top of the group instead of centred in whatever height - // the tab happens to give it. - c.gridx = 0; - c.gridy = row; - c.weighty = 1; - panel.add(Box.createGlue(), c); - return panel; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ChannelStandardPanel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ChannelStandardPanel.java deleted file mode 100644 index 8a09d60..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ChannelStandardPanel.java +++ /dev/null @@ -1,197 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.net.ChannelNode; -import com.ts3client.net.ChannelSettings; - -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.ButtonGroup; -import javax.swing.DefaultComboBoxModel; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JSeparator; -import javax.swing.JSpinner; -import javax.swing.SpinnerNumberModel; -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.util.List; -import java.util.function.Consumer; - -/** - * The channel editor's "Standard" tab: how long the channel lives, whether it is the - * server's default one, where it sorts among its siblings, and its moderation setting. - */ -final class ChannelStandardPanel extends JPanel implements ChannelDialog.Tab { - - private final JRadioButton temporary = new JRadioButton("Temporary"); - private final JRadioButton semiPermanent = new JRadioButton("Semi-Permanent"); - private final JRadioButton permanent = new JRadioButton("Permanent"); - private final JCheckBox defaultChannel = new JCheckBox("Default Channel"); - private final JComboBox sortAfter = new JComboBox<>(); - private final JSpinner talkPower = new JSpinner(new SpinnerNumberModel(0, 0, 9999, 1)); - - private Consumer typeListener; - - /** - * @param siblings the channels this one shares a parent with, in tree order and - * excluding the channel being edited - */ - ChannelStandardPanel(List siblings) { - super(new BorderLayout(UIScale.scale(8), UIScale.scale(8))); - setBorder(new ScaledEmptyBorder(8, 8, 8, 8)); - - temporary.setToolTipText("Channel will be deleted when the last user left."); - semiPermanent.setToolTipText("Channel exists until server is restarted."); - permanent.setToolTipText("Channel will exist until manually deleted."); - ButtonGroup types = new ButtonGroup(); - types.add(temporary); - types.add(semiPermanent); - types.add(permanent); - for (JRadioButton radio : new JRadioButton[]{temporary, semiPermanent, permanent}) { - radio.addActionListener(a -> fireTypeChanged()); - } - - defaultChannel.setToolTipText("The default channel is the place where new clients join on login." - + "
    There can be only one default channel for the whole server."); - - DefaultComboBoxModel order = new DefaultComboBoxModel<>(); - order.addElement(new SortEntry(0, "(first)")); - for (ChannelNode sibling : siblings) order.addElement(new SortEntry(sibling.id, sibling.name)); - sortAfter.setModel(order); - sortAfter.setToolTipText("Channel will be sorted below this channel."); - sortAfter.setPreferredSize(new Dimension(UIScale.scale(200), sortAfter.getPreferredSize().height)); - Spinners.compact(talkPower); - - add(typeBox(), BorderLayout.WEST); - add(rightColumn(), BorderLayout.CENTER); - } - - /** Notified whenever the channel type changes, so the delete delay can follow it. */ - void onTypeChanged(Consumer listener) { - this.typeListener = listener; - } - - @Override - public void read(ChannelSettings settings) { - switch (settings.type) { - case TEMPORARY: - temporary.setSelected(true); - break; - case SEMI_PERMANENT: - semiPermanent.setSelected(true); - break; - default: - permanent.setSelected(true); - break; - } - defaultChannel.setSelected(settings.defaultChannel); - // The default channel cannot simply stop being one; another has to take over. - defaultChannel.setEnabled(!settings.defaultChannel); - select(settings.order); - talkPower.setValue(settings.neededTalkPower); - fireTypeChanged(); - } - - @Override - public void write(ChannelSettings settings) { - settings.type = selectedType(); - settings.defaultChannel = defaultChannel.isSelected(); - SortEntry entry = (SortEntry) sortAfter.getSelectedItem(); - settings.order = entry == null ? 0 : entry.channelId; - settings.neededTalkPower = (Integer) talkPower.getValue(); - } - - private ChannelSettings.Type selectedType() { - if (temporary.isSelected()) return ChannelSettings.Type.TEMPORARY; - if (semiPermanent.isSelected()) return ChannelSettings.Type.SEMI_PERMANENT; - return ChannelSettings.Type.PERMANENT; - } - - private void fireTypeChanged() { - if (typeListener != null) typeListener.accept(selectedType()); - } - - private void select(int channelId) { - for (int i = 0; i < sortAfter.getItemCount(); i++) { - if (sortAfter.getItemAt(i).channelId == channelId) { - sortAfter.setSelectedIndex(i); - return; - } - } - sortAfter.setSelectedIndex(0); - } - - private JPanel typeBox() { - JPanel box = new JPanel(); - box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS)); - box.setBorder(BorderFactory.createTitledBorder("Channel Type")); - for (JRadioButton radio : new JRadioButton[]{temporary, semiPermanent, permanent}) { - radio.setAlignmentX(0f); - box.add(radio); - } - JSeparator line = new JSeparator(); - line.setAlignmentX(0f); - line.setMaximumSize(new Dimension(Integer.MAX_VALUE, UIScale.scale(8))); - box.add(Box.createVerticalStrut(UIScale.scale(4))); - box.add(line); - box.add(Box.createVerticalStrut(UIScale.scale(4))); - defaultChannel.setAlignmentX(0f); - box.add(defaultChannel); - box.add(Box.createVerticalGlue()); - return box; - } - - private JPanel rightColumn() { - JPanel sort = new JPanel(new BorderLayout()); - sort.setBorder(BorderFactory.createTitledBorder("Sort This Channel After:")); - sort.add(sortAfter, BorderLayout.CENTER); - - JPanel moderation = new JPanel(new FlowLayout(FlowLayout.LEFT, UIScale.scale(6), UIScale.scale(2))); - moderation.setBorder(BorderFactory.createTitledBorder("Moderation")); - JLabel label = new JLabel("Needed Talk Power:"); - label.setToolTipText("Talk Power required to speak in this channel."); - moderation.add(label); - moderation.add(talkPower); - - // Both groups keep their natural height; the filler below soaks up the rest, so - // they sit at the top instead of stretching over the whole tab. - JPanel column = new JPanel(new GridBagLayout()); - GridBagConstraints c = new GridBagConstraints(); - c.gridx = 0; - c.fill = GridBagConstraints.HORIZONTAL; - c.weightx = 1; - c.insets = UIScale.scale(new Insets(0, 0, 6, 0)); - column.add(sort, c); - column.add(moderation, c); - c.weighty = 1; - c.fill = GridBagConstraints.BOTH; - column.add(Box.createGlue(), c); - return column; - } - - /** One entry of the "sort after" list: a sibling channel, or the top of the list. */ - private static final class SortEntry { - final int channelId; - final String label; - - SortEntry(int channelId, String label) { - this.channelId = channelId; - this.label = label; - } - - @Override - public String toString() { - return label; - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ChatAttachmentActions.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ChatAttachmentActions.java deleted file mode 100644 index d29e786..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ChatAttachmentActions.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.myts.ChatAttachment; -import com.ts3client.myts.ChatAttachments; -import com.ts3client.myts.MyTsException; -import com.ts3client.net.ConnectionListener.ChatScope; -import com.ts3client.net.PictureDownloads; -import com.ts3client.session.ServerSession; - -import javax.imageio.ImageIO; -import javax.swing.JFileChooser; -import javax.swing.SwingUtilities; -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.StandardCopyOption; -import java.util.List; -import java.util.function.Function; - -/** - * Shares files in one server's chats through myTeamSpeak, and shows and saves the files - * shared there. Failures land in the chat as system lines. - */ -final class ChatAttachmentActions implements ChatPanel.AttachmentHandler { - - private static final String SIGN_IN = "Sign in to myTeamSpeak to share files"; - private static final String PASTED_NAME = "image.png"; - - /** Where files were last shared from or saved to, for every server alike. */ - private static File lastDirectory; - - private final MainFrame host; - private final ServerSession session; - private final ChatPanel chat; - private final PictureDownloads pictures; - private final Function scopes; - - ChatAttachmentActions(MainFrame host, ServerSession session, ChatPanel chat, PictureDownloads pictures, - Function scopes) { - this.host = host; - this.session = session; - this.chat = chat; - this.pictures = pictures; - this.scopes = scopes; - } - - @Override - public void choose(ChatPanel.Target target, int clientId) { - if (!signedIn()) return; - JFileChooser chooser = new JFileChooser(lastDirectory); - chooser.setMultiSelectionEnabled(true); - chooser.setDialogTitle("Share files"); - if (chooser.showOpenDialog(host) != JFileChooser.APPROVE_OPTION) return; - File[] files = chooser.getSelectedFiles(); - if (files.length > 0) lastDirectory = files[0].getParentFile(); - share(target, clientId, List.of(files)); - } - - @Override - public void share(ChatPanel.Target target, int clientId, List files) { - if (!signedIn()) return; - for (File file : files) { - if (!file.isFile()) continue; - if (file.length() > ChatAttachments.MAX_UPLOAD_BYTES) { - chat.appendSystem(file.getName() + " is over " + (ChatAttachments.MAX_UPLOAD_BYTES >> 20) + " MB."); - continue; - } - try { - session.sendAttachment(scopes.apply(target), clientId, host.attachments(), - new FileInputStream(file), file.length(), file.getName()); - } catch (IOException e) { - chat.appendSystem("Could not share " + file.getName() + ": " + e.getMessage()); - } - } - } - - @Override - public void share(ChatPanel.Target target, int clientId, BufferedImage image) { - if (!signedIn()) return; - ByteArrayOutputStream png = new ByteArrayOutputStream(); - try { - ImageIO.write(image, "png", png); - } catch (IOException e) { - chat.appendSystem("Could not share the picture: " + e.getMessage()); - return; - } - session.sendAttachment(scopes.apply(target), clientId, host.attachments(), - new ByteArrayInputStream(png.toByteArray()), png.size(), PASTED_NAME); - } - - @Override - public void open(String href, boolean picture) { - ChatAttachment.Ref ref = ChatAttachment.Ref.parse(href); - if (ref == null) return; - File shown = picture ? pictures.get(href) : null; - BufferedImage image = shown == null ? null : read(shown); - if (image != null) { - new PictureViewer(host, ref.fileName(), image, () -> save(ref, shown)).setVisible(true); - } else { - save(ref, null); - } - } - - /** Asks where to save the file, then copies it there: from {@code have} when given, else fetched. */ - private void save(ChatAttachment.Ref ref, File have) { - if (have == null && !signedIn()) return; - JFileChooser chooser = new JFileChooser(lastDirectory); - chooser.setDialogTitle("Save " + ref.fileName()); - chooser.setSelectedFile(new File(lastDirectory, ref.fileName())); - if (chooser.showSaveDialog(host) != JFileChooser.APPROVE_OPTION) return; - File target = chooser.getSelectedFile(); - lastDirectory = target.getParentFile(); - ChatAttachments attachments = host.attachments(); - Thread.ofVirtual().name("chat-attachment-save").start(() -> { - try { - if (have != null) { - Files.copy(have.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING); - } else { - Files.write(target.toPath(), attachments.download(ref, ChatAttachments.MAX_UPLOAD_BYTES)); - } - } catch (IOException | MyTsException e) { - SwingUtilities.invokeLater(() -> - chat.appendSystem("Could not save " + ref.fileName() + ": " + e.getMessage())); - } - }); - } - - private boolean signedIn() { - if (host.canShareFiles()) return true; - chat.appendSystem(SIGN_IN + "."); - return false; - } - - private static BufferedImage read(File file) { - try { - return ImageIO.read(file); - } catch (IOException e) { - return null; - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ChatLogsPanel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ChatLogsPanel.java deleted file mode 100644 index f55adc0..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ChatLogsPanel.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.config.AppDirs; -import com.ts3client.config.Settings; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JFileChooser; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; -import java.awt.BorderLayout; -import java.awt.GridBagConstraints; -import java.io.File; - -/** - * Options page for chat logs: whether they are kept, and where. By default they go into the - * TeamSpeak 3 client's own folder, so both clients show the same history. - */ -final class ChatLogsPanel extends FormPanel { - - private final Settings settings; - private final JCheckBox enabled = new JCheckBox("Keep chat logs"); - private final JTextField folder = new JTextField(18); - private final JButton browse = new JButton("Browse…"); - private final JCheckBox pictures = new JCheckBox("Show pictures in descriptions and chat"); - - ChatLogsPanel(Settings settings) { - this.settings = settings; - GridBagConstraints c = gbc(); - - enabled.setSelected(settings.chatLogs); - enabled.setToolTipText("Write every chat to disk and show its history when it opens again"); - enabled.addActionListener(e -> updateEnabled()); - - folder.setText(settings.chatLogDir); - folder.putClientProperty("JTextField.placeholderText", "The TeamSpeak 3 client's folder"); - folder.setToolTipText("Leave empty to share the TeamSpeak 3 client's logs:
    " - + AppDirs.chatLogs() + ""); - limitWidth(folder, FIELD_WIDTH); - browse.addActionListener(e -> browseForFolder()); - JPanel folderRow = new JPanel(new BorderLayout(UIScale.scale(6), 0)); - folderRow.add(folder, BorderLayout.CENTER); - folderRow.add(browse, BorderLayout.EAST); - - JLabel nextConnect = new JLabel("Takes effect on the next connect."); - nextConnect.setEnabled(false); - - pictures.setSelected(settings.descriptionPictures); - pictures.setToolTipText("Off: only links to them, nothing fetched"); - - int row = 0; - addSection(this, c, row++, "Logging"); - addWide(this, c, row++, enabled); - addRow(this, c, row++, new JLabel("Folder:"), folderRow); - c.gridx = 1; - c.gridy = row++; - add(nextConnect, c); - addSection(this, c, row++, "Descriptions"); - addWide(this, c, row++, pictures); - addFiller(this, c, row); - updateEnabled(); - } - - private void updateEnabled() { - folder.setEnabled(enabled.isSelected()); - browse.setEnabled(enabled.isSelected()); - } - - private void browseForFolder() { - JFileChooser chooser = new JFileChooser(); - chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - chooser.setDialogTitle("Folder for chat logs"); - String current = folder.getText().trim(); - chooser.setCurrentDirectory(current.isEmpty() ? AppDirs.chatLogs().toFile() : new File(current)); - if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { - folder.setText(chooser.getSelectedFile().getAbsolutePath()); - } - } - - /** Copies the page into the settings; the caller saves them. */ - void apply() { - settings.chatLogs = enabled.isSelected(); - settings.chatLogDir = folder.getText().trim(); - settings.descriptionPictures = pictures.isSelected(); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ChatPanel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ChatPanel.java deleted file mode 100644 index 5e21931..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ChatPanel.java +++ /dev/null @@ -1,761 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.config.Settings; -import com.ts3client.myts.ChatAttachment; -import com.ts3client.net.PictureDownloads; -import com.ts3client.text.BBCode; -import com.ts3client.text.ChatHtml; -import com.ts3client.text.HtmlText; -import com.ts3client.text.TextQuery; -import com.ts3client.text.TsLink; - -import javax.swing.AbstractAction; -import javax.swing.BorderFactory; -import javax.swing.Icon; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JEditorPane; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollBar; -import javax.swing.JScrollPane; -import javax.swing.JTabbedPane; -import javax.swing.JTextField; -import javax.swing.KeyStroke; -import javax.swing.SwingUtilities; -import javax.swing.event.HyperlinkEvent; -import javax.swing.text.BadLocationException; -import javax.swing.text.Element; -import javax.swing.text.StyleConstants; -import javax.swing.text.html.HTML; -import javax.swing.text.html.HTMLDocument; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Cursor; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.Insets; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseWheelEvent; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.function.Supplier; - -/** - * Chat area with one tab per conversation (server, current channel and one per - * private chat). The tab strip sits between the log and the input line. Logs are - * rendered as HTML: sender names are links that open the client context menu, - * and message bodies go through the {@link BBCode} renderer. - */ -public final class ChatPanel extends JPanel { - - /** Where an outgoing message should go. */ - public enum Target {CHANNEL, SERVER, PRIVATE} - - public interface SendHandler { - /** {@code clientId} is only meaningful for {@link Target#PRIVATE}. */ - void send(Target target, int clientId, String text); - } - - /** Invoked when a client or channel link in the log is clicked. */ - public interface LinkHandler { - void onClientLink(TsLink.Ref ref, Component source, int x, int y); - - void onChannelLink(TsLink.Ref ref, Component source, int x, int y); - - /** The "unread offline messages" log line was clicked. */ - void onOfflineMessagesLink(); - } - - /** Files shared in the chats, which the host sends, fetches and shows. */ - public interface AttachmentHandler { - /** Asks which files to share in the conversation. */ - void choose(Target target, int clientId); - - void share(Target target, int clientId, List files); - - void share(Target target, int clientId, BufferedImage image); - - /** - * A shared file was clicked. - * - * @param picture whether the picture shown for it was, rather than its name - */ - void open(String href, boolean picture); - } - - private final JTabbedPane tabs = new JTabbedPane(JTabbedPane.BOTTOM); - private final JTextField input = new JTextField(); - - /** Tab strip height, so a tab with no icon still lines up with the others. */ - private static final int HEADER_HEIGHT = 20; - /** The largest a shared picture is drawn in the log. */ - private static final int PICTURE_WIDTH = 320; - private static final int PICTURE_HEIGHT = 240; - private static final int PICTURE_WIDTH_STEP = 40; - - private static final String NO_SERVER = "Server"; - private static final String NO_CHANNEL = "Channel"; - - private final Tab serverTab = new Tab(Target.SERVER, 0, NO_SERVER, Icons.server()); - private final Tab channelTab = new Tab(Target.CHANNEL, 0, NO_CHANNEL, Icons.channelChat()); - /** Private chats keyed by the peer's client id. */ - private final Map privateTabs = new LinkedHashMap<>(); - /** Static-content tabs (e.g. a moved-out description), keyed by caller-chosen id. */ - private final Map noteTabs = new LinkedHashMap<>(); - - private final TabDragReorder dragReorder = new TabDragReorder(tabs, this::moveTab); - - private final ChatSearch search = new ChatSearch(new ChatSearch.Host() { - @Override - public JEditorPane selectedLog() { - Tab t = selectedTab(); - return t == null ? null : t.log; - } - - @Override - public void showMatching(TextQuery filter) { - Tab t = selectedTab(); - if (t != null) t.showMatching(filter); - } - }); - - private SendHandler sendHandler; - private LinkHandler linkHandler; - private AttachmentHandler attachmentHandler; - private final TextZoom zoom; - private final PictureDownloads downloads; - private final DescriptionPictures pictures; - /** The server's unique identifier, which shared files are kept under; null while unknown. */ - private final Supplier room; - private final JButton attach = new JButton(Icons.of("UPLOAD")); - private boolean inputEnabled; - private boolean sharingAvailable; - private final Runnable onPicture = () -> SwingUtilities.invokeLater(() -> { - for (Tab t : allTabs()) t.picturesChanged(); - }); - - public ChatPanel(TextZoom zoom, Settings settings, PictureDownloads downloads, Supplier room) { - super(new BorderLayout()); - this.zoom = zoom; - this.downloads = downloads; - this.pictures = new DescriptionPictures(downloads, settings); - this.room = room; - - tabs.setFont(Theme.uiFont()); - tabs.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); - // Half the look and feel's leading padding: these tabs carry a name that is worth - // the width, and their headers bring their own spacing. - tabs.putClientProperty("JTabbedPane.tabInsets", new Insets(4, 6, 4, 12)); - addTab(serverTab, false); - addTab(channelTab, false); - tabs.setSelectedIndex(0); - tabs.addChangeListener(e -> { - Tab t = selectedTab(); - if (t != null) t.setUnread(false); - // A search filters only the tab it is in; the one left behind shows everything again. - for (Tab other : allTabs()) { - if (other != t) other.showMatching(null); - } - search.retarget(); - }); - tabs.addMouseWheelListener(this::onWheel); - dragReorder.attach(tabs); - add(tabs, BorderLayout.CENTER); - add(search.bar(), BorderLayout.NORTH); - String find = "ts3-chat-find"; - getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("control F"), find); - getActionMap().put(find, new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - openFind(); - } - }); - - JPanel bottom = new JPanel(new BorderLayout(UIScale.scale(4), 0)); - bottom.setBorder(new ScaledEmptyBorder(4, 0, 0, 0)); - bottom.add(input, BorderLayout.CENTER); - bottom.add(attach, BorderLayout.EAST); - add(bottom, BorderLayout.SOUTH); - - input.addActionListener(e -> fireSend()); - input.setTransferHandler(attachmentTransfer(input)); - attach.putClientProperty("JButton.buttonType", "toolBarButton"); - attach.setFocusable(false); - attach.addActionListener(e -> { - Tab tab = selectedTab(); - if (attachmentHandler != null && tab != null && tab.target != null) { - attachmentHandler.choose(tab.target, tab.clientId); - } - }); - - setInputEnabled(false); - } - - public void setSendHandler(SendHandler h) { - this.sendHandler = h; - } - - public void setLinkHandler(LinkHandler h) { - this.linkHandler = h; - } - - public void setAttachmentHandler(AttachmentHandler h) { - this.attachmentHandler = h; - } - - /** Whether files can be shared at all, i.e. signed in to myTeamSpeak. */ - public void setSharingAvailable(boolean available) { - edt(() -> { - sharingAvailable = available; - updateAttach(); - }); - } - - @Override - public void addNotify() { - super.addNotify(); - downloads.addListener(onPicture); - } - - @Override - public void removeNotify() { - downloads.removeListener(onPicture); - super.removeNotify(); - } - - /** Opens the find bar on the selected conversation. */ - public void openFind() { - edt(search::open); - } - - /** Appends text to the input line, e.g. a client link dropped onto the chat. */ - public void appendToInput(String text) { - edt(() -> { - String cur = input.getText(); - input.setText(cur.isEmpty() || cur.endsWith(" ") ? cur + text : cur + " " + text); - input.requestFocusInWindow(); - }); - } - - /** Names the server tab after the server we are on; blank falls back to "Server". */ - public void setServerName(String name) { - edt(() -> serverTab.setTitle(name == null || name.isBlank() ? NO_SERVER : name)); - } - - /** Names the channel tab after the channel we are in; blank falls back to "Channel". */ - public void setChannelName(String name) { - edt(() -> channelTab.setTitle(name == null || name.isBlank() ? NO_CHANNEL : name)); - } - - public void setInputEnabled(boolean enabled) { - input.setEnabled(enabled); - inputEnabled = enabled; - updateAttach(); - } - - private void updateAttach() { - attach.setEnabled(inputEnabled && sharingAvailable); - attach.setToolTipText(sharingAvailable ? "Share file" : "Sign in to myTeamSpeak to share files"); - } - - /** Takes dropped and pasted files and pictures as files to share, leaving the rest to {@code c}'s own handling. */ - private AttachmentTransferHandler attachmentTransfer(JComponent c) { - return new AttachmentTransferHandler(c.getTransferHandler(), new AttachmentTransferHandler.Sink() { - @Override - public boolean files(List files) { - Tab tab = selectedTab(); - if (attachmentHandler == null || tab == null || tab.target == null) return false; - attachmentHandler.share(tab.target, tab.clientId, files); - return true; - } - - @Override - public boolean image(BufferedImage image) { - Tab tab = selectedTab(); - if (attachmentHandler == null || tab == null || tab.target == null) return false; - attachmentHandler.share(tab.target, tab.clientId, image); - return true; - } - }); - } - - /** Opens (or focuses) the private chat with {@code clientId}. */ - public void openPrivateChat(int clientId, String nickname) { - openPrivateChat(clientId, "", nickname); - } - - /** Opens (or focuses) the private chat with {@code clientId}. */ - public void openPrivateChat(int clientId, String uniqueId, String nickname) { - edt(() -> { - Tab tab = privateTab(clientId, uniqueId, nickname); - tabs.setSelectedComponent(tab.scroll); - input.requestFocusInWindow(); - }); - } - - public void setServerHistory(List htmlEntries) { - edt(() -> serverTab.setHistory(htmlEntries)); - } - - public void setChannelHistory(List htmlEntries) { - edt(() -> channelTab.setHistory(htmlEntries)); - } - - public void setPrivateHistory(int clientId, String nickname, List htmlEntries) { - edt(() -> privateTab(clientId, "", nickname).setHistory(htmlEntries)); - } - - /** Drops every private chat tab, e.g. after disconnecting. */ - public void closePrivateChats() { - edt(() -> { - for (Tab t : privateTabs.values()) tabs.remove(t.scroll); - privateTabs.clear(); - }); - } - - /** Drops every static-content tab (moved-out descriptions), e.g. after disconnecting. */ - public void closeNoteTabs() { - edt(() -> { - for (Tab t : noteTabs.values()) tabs.remove(t.scroll); - noteTabs.clear(); - }); - } - - /** Closes a single static-content tab by its key, if open; does not run its {@code onClose}. */ - public void closeNoteTab(String key) { - edt(() -> { - Tab tab = noteTabs.remove(key); - if (tab != null) tabs.remove(tab.scroll); - }); - } - - /** - * Opens (or replaces the content of, and focuses) a static-content tab, e.g. a - * channel/client description moved out of the info panel. {@code onClose} runs - * when the tab is closed, so the caller can un-hide the description again. - */ - public void openDescriptionTab(String key, Icon icon, String title, String htmlBody, Runnable onClose) { - edt(() -> { - Tab tab = noteTabs.get(key); - if (tab == null) { - tab = new Tab(key, icon, title, onClose); - noteTabs.put(key, tab); - addTab(tab, true); - } - tab.setStaticContent(htmlBody); - tabs.setSelectedComponent(tab.scroll); - }); - } - - private void fireSend() { - String text = input.getText().trim(); - if (text.isEmpty() || sendHandler == null) return; - Tab tab = selectedTab(); - if (tab == null || tab.target == null) return; - sendHandler.send(tab.target, tab.clientId, text); - input.setText(""); - } - - // ---- append helpers (safe from any thread) ---- - - /** System notices always land in the server tab. */ - public void appendSystem(String text) { - edt(() -> serverTab.append(ChatHtml.system(text))); - } - - /** - * Server-side events (client joins/leaves/moves, group changes, channel edits, …). - * These lines name clients and channels with TeamSpeak's own links, which stay - * clickable here — everything else in them is literal text. - */ - public void appendServerLog(String text) { - edt(() -> serverTab.append(ChatHtml.serverLog(text))); - } - - public void appendServerLogHtml(String html) { - edt(() -> serverTab.append(ChatHtml.logEntry(html))); - } - - public void appendServerMessage(int fromId, String from, String text) { - appendServerMessage(fromId, "", from, text); - } - - public void appendServerMessage(int fromId, String uniqueId, String from, String text) { - edt(() -> serverTab.appendMessage(fromId, uniqueId, from, text)); - } - - public void appendChannelMessage(int fromId, String from, String text) { - appendChannelMessage(fromId, "", from, text); - } - - public void appendChannelMessage(int fromId, String uniqueId, String from, String text) { - edt(() -> channelTab.appendMessage(fromId, uniqueId, from, text)); - } - - /** Appends to the private chat with {@code peerId}, creating the tab if needed. */ - public void appendPrivateMessage(int peerId, String peerName, int fromId, String from, String text) { - appendPrivateMessage(peerId, "", peerName, fromId, "", from, text); - } - - /** Appends to the private chat with {@code peerId}, creating the tab if needed. */ - public void appendPrivateMessage(int peerId, String peerUniqueId, String peerName, - int fromId, String fromUniqueId, String from, String text) { - edt(() -> privateTab(peerId, peerUniqueId, peerName).appendMessage(fromId, fromUniqueId, from, text)); - } - - private Tab privateTab(int clientId, String nickname) { - return privateTab(clientId, "", nickname); - } - - private Tab privateTab(int clientId, String uniqueId, String nickname) { - Tab tab = privateTabs.get(clientId); - if (tab == null) { - tab = new Tab(Target.PRIVATE, clientId, uniqueId, nickname, Icons.privateChat()); - privateTabs.put(clientId, tab); - addTab(tab, true); - } else { - tab.setClientUniqueId(uniqueId); - } - return tab; - } - - private void addTab(Tab tab, boolean closable) { - tabs.addTab(tab.title, tab.scroll); - zoom.attach(tab.log); - tabs.setTabComponentAt(tabs.indexOfComponent(tab.scroll), tab.header(closable)); - } - - private void closeTab(Tab tab) { - if (tab.noteKey != null) { - noteTabs.remove(tab.noteKey); - if (tab.onClose != null) tab.onClose.run(); - } else { - privateTabs.remove(tab.clientId); - } - tabs.remove(tab.scroll); - } - - /** Drags a tab from one position to another, keeping the current selection on screen. */ - private void moveTab(int from, int to) { - if (from < 0 || to < 0 || from >= tabs.getTabCount() || to >= tabs.getTabCount() || from == to) return; - Component content = tabs.getComponentAt(from); - String title = tabs.getTitleAt(from); - Icon icon = tabs.getIconAt(from); - String tip = tabs.getToolTipTextAt(from); - Component header = tabs.getTabComponentAt(from); - boolean wasSelected = tabs.getSelectedIndex() == from; - tabs.removeTabAt(from); - tabs.insertTab(title, icon, content, tip, to); - tabs.setTabComponentAt(to, header); - if (wasSelected) tabs.setSelectedIndex(to); - } - - private void onWheel(MouseWheelEvent e) { - Component content = tabs.getSelectedComponent(); - if (content != null && content.getBounds().contains(e.getPoint())) return; - int steps = e.getWheelRotation(); - if (steps == 0) return; - int target = Math.max(0, Math.min(tabs.getTabCount() - 1, tabs.getSelectedIndex() + steps)); - if (target != tabs.getSelectedIndex()) tabs.setSelectedIndex(target); - e.consume(); - } - - private Tab selectedTab() { - Component c = tabs.getSelectedComponent(); - if (c == serverTab.scroll) return serverTab; - if (c == channelTab.scroll) return channelTab; - for (Tab t : privateTabs.values()) { - if (t.scroll == c) return t; - } - for (Tab t : noteTabs.values()) { - if (t.scroll == c) return t; - } - return null; - } - - private List allTabs() { - List all = new ArrayList<>(); - all.add(serverTab); - all.add(channelTab); - all.addAll(privateTabs.values()); - all.addAll(noteTabs.values()); - return all; - } - - private String room() { - String id = room.get(); - return id == null ? "" : id; - } - - private void edt(Runnable r) { - if (SwingUtilities.isEventDispatchThread()) r.run(); - else SwingUtilities.invokeLater(r); - } - - /** One conversation: its HTML log, its scroll pane and the tab-strip header. */ - private final class Tab { - - final Target target; - final int clientId; - private String clientUniqueId; - private String title; - final JEditorPane log = HtmlStyles.pane("font-family:sans-serif; font-size:11px; margin:" - + HtmlStyles.px(4) + " " + HtmlStyles.px(6) + ";"); - final JScrollPane scroll; - /** Set for a static-content tab (e.g. a moved-out description); null for a conversation. */ - final String noteKey; - final Runnable onClose; - private final Icon icon; - private JLabel titleLabel; - /** Everything this conversation has shown, whether or not a search currently hides it. */ - private final List entries = new ArrayList<>(); - /** Only messages matching this are on screen; {@code null} shows all. */ - private TextQuery filter; - /** The shared pictures the entries show, and how they stood when last drawn. */ - private final List pictureUrls = new ArrayList<>(); - private String pictureState = ""; - private int renderedPictureWidth; - - Tab(Target target, int clientId, String title, Icon icon) { - this(target, clientId, "", title, icon, null, null); - } - - Tab(Target target, int clientId, String clientUniqueId, String title, Icon icon) { - this(target, clientId, clientUniqueId, title, icon, null, null); - } - - /** A static-content tab: no send target, closing it runs {@code onClose}. */ - Tab(String noteKey, Icon icon, String title, Runnable onClose) { - this(null, 0, "", title, icon, noteKey, onClose); - } - - private Tab(Target target, int clientId, String clientUniqueId, String title, - Icon icon, String noteKey, Runnable onClose) { - this.target = target; - this.clientId = clientId; - this.clientUniqueId = clientUniqueId == null ? "" : clientUniqueId; - this.title = title; - this.icon = icon; - this.noteKey = noteKey; - this.onClose = onClose; - - log.setText("

    "); - log.addHyperlinkListener(e -> { - if (e.getEventType() != HyperlinkEvent.EventType.ACTIVATED) return; - onLink(e.getDescription(), isPicture(e.getSourceElement())); - }); - log.setTransferHandler(attachmentTransfer(log)); - - scroll = new JScrollPane(log); - HtmlStyles.fillViewport(log); - scroll.setBorder(BorderFactory.createEmptyBorder()); - scroll.getViewport().addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent e) { - if (!pictureUrls.isEmpty() && pictureWidth() != renderedPictureWidth) keepingScroll(); - } - }); - } - - private static boolean isPicture(Element element) { - return element != null && element.getAttributes().getAttribute(StyleConstants.NameAttribute) == HTML.Tag.IMG; - } - - void setClientUniqueId(String uniqueId) { - if (uniqueId != null && !uniqueId.isBlank()) clientUniqueId = uniqueId; - } - - private void onLink(String href, boolean picture) { - if (href == null) return; - if (ChatAttachment.isHref(href)) { - if (attachmentHandler != null) attachmentHandler.open(href, picture); - return; - } - if (TsLink.isOfflineMessages(href)) { - if (linkHandler != null) linkHandler.onOfflineMessagesLink(); - return; - } - TsLink.Ref ref = TsLink.parse(href); - if (ref == null) { - Links.open(href, ChatPanel.this); - return; - } - if (linkHandler == null) return; - Point p = log.getMousePosition(); - if (p == null) p = new Point(0, 0); - if (ref.client) linkHandler.onClientLink(ref, log, p.x, p.y); - else linkHandler.onChannelLink(ref, log, p.x, p.y); - } - - Component header(boolean closable) { - // Only the height is pinned: a fixed width would freeze the tab at the width of - // whatever name it was built with, clipping longer ones (and the bold unread font). - JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT, UIScale.scale(2), 0)) { - @Override - public Dimension getPreferredSize() { - Dimension d = super.getPreferredSize(); - return new Dimension(d.width, Math.max(d.height, UIScale.scale(HEADER_HEIGHT))); - } - }; - p.setOpaque(false); - titleLabel = new JLabel(title, icon, JLabel.LEADING); - titleLabel.setFont(Theme.uiFont()); - titleLabel.setIconTextGap(UIScale.scale(3)); - p.add(titleLabel); - dragReorder.attach(p); - dragReorder.attach(titleLabel); - if (closable) { - JLabel close = new JLabel("×"); - close.setFont(Theme.uiBold()); - close.setForeground(Theme.chatSystem()); - close.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - close.setToolTipText("Close chat"); - close.addMouseListener(new MouseAdapter() { - @Override - public void mousePressed(MouseEvent e) { - closeTab(Tab.this); - } - }); - p.add(close); - } - return p; - } - - /** Renames the tab in place — the server and channel tabs follow where we are. */ - void setTitle(String title) { - if (title.equals(this.title)) return; - this.title = title; - int index = tabs.indexOfComponent(scroll); - if (index >= 0) tabs.setTitleAt(index, title); - if (titleLabel == null) return; - titleLabel.setText(title); - // The strip lays its tabs out itself; it has to re-measure this one. - tabs.revalidate(); - tabs.repaint(); - } - - void setUnread(boolean unread) { - if (titleLabel == null) return; - titleLabel.setFont(unread ? Theme.uiBold() : Theme.uiFont()); - titleLabel.setForeground(unread ? Theme.accent() : null); - } - - void appendMessage(int fromId, String fromUniqueId, String from, String text) { - append(ChatHtml.message(fromId, - fromUniqueId == null || fromUniqueId.isBlank() ? clientUniqueId : fromUniqueId, from, text, - room())); - } - - void setHistory(List htmlEntries) { - entries.clear(); - pictureUrls.clear(); - if (htmlEntries != null) { - String room = room(); - for (String entry : htmlEntries) add(ChatHtml.logEntry(entry, room)); - } - render(); - } - - /** Replaces the whole log with fixed content; used by static-content tabs. */ - void setStaticContent(String html) { - entries.clear(); - pictureUrls.clear(); - entries.add(html); - render(); - } - - private void add(String entry) { - entries.add(entry); - // Static content comes with its pictures already in place. - if (noteKey == null && DescriptionPictures.hasPictures(entry)) { - pictureUrls.addAll(DescriptionPictures.urls(entry)); - } - } - - /** The entry as drawn: its shared pictures as they stand now. */ - private String drawn(String entry) { - if (noteKey != null || !DescriptionPictures.hasPictures(entry)) return entry; - return pictures.html(entry, renderedPictureWidth, UIScale.scale(PICTURE_HEIGHT)); - } - - /** - * How wide a shared picture may be: the log's width inside its margins, in steps so that - * dragging a divider does not rebuild the log on every pixel. - */ - private int pictureWidth() { - int step = UIScale.scale(PICTURE_WIDTH_STEP); - int width = scroll.getViewport().getWidth() - UIScale.scale(24); - return Math.min(UIScale.scale(PICTURE_WIDTH), Math.max(step, width / step * step)); - } - - /** A picture came or failed: redrawn if it is one of this log's. */ - void picturesChanged() { - if (!pictureUrls.isEmpty() && !pictures.state(pictureUrls).equals(pictureState)) keepingScroll(); - } - - /** Redraws the log, staying where the reader is unless that is at the end. */ - private void keepingScroll() { - JScrollBar bar = scroll.getVerticalScrollBar(); - boolean atEnd = bar.getValue() + bar.getVisibleAmount() >= bar.getMaximum() - UIScale.scale(8); - Point at = scroll.getViewport().getViewPosition(); - render(); - if (!atEnd || search.isOpen()) SwingUtilities.invokeLater(() -> scroll.getViewport().setViewPosition(at)); - } - - void showMatching(TextQuery filter) { - if (Objects.equals(this.filter, filter)) return; - this.filter = filter; - render(); - } - - private boolean shows(String entry) { - return filter == null || filter.matches(HtmlText.plain(entry)); - } - - private void render() { - // Read before drawing, so a picture coming meanwhile still counts as a change. - pictureState = pictures.state(pictureUrls); - renderedPictureWidth = pictureWidth(); - StringBuilder html = new StringBuilder(); - for (String entry : entries) { - if (shows(entry)) html.append(drawn(entry)); - } - log.setText("
    " + html + "
    "); - log.setCaretPosition(noteKey != null ? 0 : log.getDocument().getLength()); - } - - void append(String entry) { - boolean stale = !pictures.state(pictureUrls).equals(pictureState); - add(entry); - if (stale) { - // A picture already shown changed and is about to be redrawn; this joins it. - render(); - } else if (shows(entry)) { - pictureState = pictures.state(pictureUrls); - if (renderedPictureWidth == 0) renderedPictureWidth = pictureWidth(); - try { - HTMLDocument doc = (HTMLDocument) log.getDocument(); - doc.insertBeforeEnd(doc.getElement("chatlog"), drawn(entry)); - // Following new lines would pull the view away from the match being read. - if (!search.isOpen()) log.setCaretPosition(doc.getLength()); - } catch (BadLocationException | IOException ignored) { - } - } - if (tabs.getSelectedComponent() != scroll) setUnread(true); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ChatSearch.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ChatSearch.java deleted file mode 100644 index 96d0bdf..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ChatSearch.java +++ /dev/null @@ -1,270 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.text.TextQuery; - -import javax.swing.JEditorPane; -import javax.swing.JToggleButton; -import javax.swing.JViewport; -import javax.swing.SwingUtilities; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.text.BadLocationException; -import javax.swing.text.DefaultHighlighter; -import javax.swing.text.Document; -import javax.swing.text.Highlighter; -import java.awt.Color; -import java.awt.Point; -import java.awt.Rectangle; -import java.beans.PropertyChangeListener; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; - -/** - * Find in a log pane — the chat's selected conversation, or the server log: highlights the - * query's matches and steps through them, newest first. Optionally shows only the - * messages that match. - */ -final class ChatSearch implements FindBar.Listener { - - /** The conversation being searched: whichever chat tab is selected. */ - interface Host { - /** The selected tab's log, or {@code null} when there is none. */ - JEditorPane selectedLog(); - - /** Shows only the selected tab's messages matching {@code filter}; {@code null} shows all again. */ - void showMatching(TextQuery filter); - } - - /** More highlights than this slow painting down, and nobody steps through them one by one. */ - private static final int MAX_HIGHLIGHTS = 5000; - - private final Host host; - private final FindBar bar = new FindBar(this); - private final JToggleButton onlyMatching; - - private final Highlighter.HighlightPainter matchPainter = new ThemedPainter(false); - private final Highlighter.HighlightPainter currentPainter = new ThemedPainter(true); - private final List highlightTags = new ArrayList<>(); - /** Start and end offsets of each match in the log document, oldest first. */ - private final List matches = new ArrayList<>(); - private int current = -1; - /** The next re-highlight follows a new query, so it starts again from the newest match. */ - private boolean freshQuery; - private boolean rehighlightQueued; - - private JEditorPane log; - private final DocumentListener docListener = new DocumentListener() { - @Override - public void insertUpdate(DocumentEvent e) { - queueRehighlight(); - } - - @Override - public void removeUpdate(DocumentEvent e) { - queueRehighlight(); - } - - @Override - public void changedUpdate(DocumentEvent e) { - } - }; - /** A theme change re-installs the log's document. */ - private final PropertyChangeListener docSwap = e -> { - if (e.getOldValue() instanceof Document old) old.removeDocumentListener(docListener); - if (e.getNewValue() instanceof Document now) now.addDocumentListener(docListener); - queueRehighlight(); - }; - - ChatSearch(Host host) { - this(host, "Show only matching messages"); - } - - ChatSearch(Host host, String filterTooltip) { - this.host = host; - onlyMatching = bar.addFilterToggle(filterTooltip); - } - - FindBar bar() { - return bar; - } - - boolean isOpen() { - return bar.isOpen(); - } - - void open() { - retarget(); - bar.open(); - } - - /** The selected tab changed: carry the search over to it. */ - void retarget() { - JEditorPane now = host.selectedLog(); - if (now != log) { - detach(); - log = now; - if (log != null) { - log.getDocument().addDocumentListener(docListener); - log.addPropertyChangeListener("document", docSwap); - } - } - if (bar.isOpen()) queryChanged(bar.query()); - } - - @Override - public void queryChanged(TextQuery query) { - freshQuery = true; - boolean usable = !query.isEmpty() && !query.isInvalid(); - host.showMatching(onlyMatching.isSelected() && usable ? query : null); - rehighlight(); - } - - @Override - public void next() { - step(1); - } - - @Override - public void previous() { - step(-1); - } - - @Override - public void closed() { - clearHighlights(); - matches.clear(); - host.showMatching(null); - if (log != null) { - log.setCaretPosition(log.getDocument().getLength()); - log.requestFocusInWindow(); - } - } - - private void step(int delta) { - if (matches.isEmpty()) return; - current = Math.floorMod(current + delta, matches.size()); - paintHighlights(); - scrollToCurrent(); - updateStatus(); - } - - private void queueRehighlight() { - if (!bar.isOpen() || rehighlightQueued) return; - rehighlightQueued = true; - SwingUtilities.invokeLater(() -> { - rehighlightQueued = false; - if (bar.isOpen()) rehighlight(); - }); - } - - /** Finds the matches in the log as it now reads, keeping the current one where it can. */ - private void rehighlight() { - int keepStart = !freshQuery && current >= 0 && current < matches.size() ? matches.get(current)[0] : -1; - matches.clear(); - current = -1; - TextQuery query = bar.query(); - Matcher m = null; - if (log != null) { - try { - Document doc = log.getDocument(); - m = query.matcher(doc.getText(0, doc.getLength())); - } catch (BadLocationException ignored) { - } - } - if (m != null) { - while (m.find()) { - if (m.end() > m.start()) matches.add(new int[]{m.start(), m.end()}); - } - } - if (matches.size() > MAX_HIGHLIGHTS) matches.subList(0, matches.size() - MAX_HIGHLIGHTS).clear(); - - if (!matches.isEmpty()) { - current = matches.size() - 1; - if (keepStart >= 0) { - for (int i = 0; i < matches.size(); i++) { - if (matches.get(i)[0] >= keepStart) { - current = i; - break; - } - } - } - } - paintHighlights(); - if (freshQuery) scrollToCurrent(); - freshQuery = false; - updateStatus(); - } - - private void updateStatus() { - TextQuery query = bar.query(); - if (query.isInvalid()) return; - bar.setNavigable(matches.size() > 1); - if (query.isEmpty()) bar.clearCount(); - else bar.setCount(current + 1, matches.size(), matches.size() == MAX_HIGHLIGHTS); - } - - private void paintHighlights() { - clearHighlights(); - if (log == null) return; - Highlighter h = log.getHighlighter(); - for (int i = 0; i < matches.size(); i++) { - int[] r = matches.get(i); - try { - highlightTags.add(h.addHighlight(r[0], r[1], i == current ? currentPainter : matchPainter)); - } catch (BadLocationException ignored) { - } - } - } - - private void clearHighlights() { - if (log != null) { - Highlighter h = log.getHighlighter(); - for (Object tag : highlightTags) h.removeHighlight(tag); - } - highlightTags.clear(); - } - - /** Brings the current match to the middle of the view, once the log has been laid out. */ - private void scrollToCurrent() { - if (current < 0 || log == null) return; - int start = matches.get(current)[0]; - JEditorPane pane = log; - SwingUtilities.invokeLater(() -> { - if (pane != log || !(pane.getParent() instanceof JViewport viewport)) return; - try { - Rectangle r = pane.modelToView2D(start).getBounds(); - Rectangle view = viewport.getViewRect(); - if (view.contains(r)) return; - int maxY = Math.max(0, pane.getHeight() - view.height); - int y = Math.max(0, Math.min(maxY, r.y - (view.height - r.height) / 2)); - viewport.setViewPosition(new Point(view.x, y)); - } catch (BadLocationException ignored) { - } - }); - } - - private void detach() { - clearHighlights(); - matches.clear(); - current = -1; - if (log == null) return; - log.getDocument().removeDocumentListener(docListener); - log.removePropertyChangeListener("document", docSwap); - } - - /** Reads the theme when painting, so highlights follow a light/dark switch. */ - private static final class ThemedPainter extends DefaultHighlighter.DefaultHighlightPainter { - private final boolean current; - - ThemedPainter(boolean current) { - super(null); - this.current = current; - } - - @Override - public Color getColor() { - return current ? Theme.searchCurrent() : Theme.searchMatch(); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ClientMenu.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ClientMenu.java deleted file mode 100644 index 8183bcf..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ClientMenu.java +++ /dev/null @@ -1,161 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.contacts.ContactType; -import com.ts3client.net.ChannelNode; -import com.ts3client.net.ClientEntry; -import com.ts3client.net.Group; -import com.ts3client.net.GroupChoice; -import com.ts3client.net.ServerModel; - -import javax.swing.JCheckBoxMenuItem; -import javax.swing.JMenu; -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; -import java.util.List; - -/** - * The context menu for a client, shared by the server tree and the clickable - * names in the chat log. - */ -final class ClientMenu { - - private ClientMenu() { - } - - /** - * @param fromTree whether this menu was opened from the server tree itself, as - * opposed to a client link elsewhere (chat log, etc.) — "Find - * Client in Channel Tree" is redundant in the former case. - */ - static JPopupMenu build(ClientEntry client, boolean self, boolean fromTree, ServerModel model, - GroupIcons groupIcons, ServerTreePanel.Actions actions) { - JPopupMenu menu = new JPopupMenu(); - if (!self) { - JMenuItem pm = new JMenuItem("Open text chat", Icons.of("PLAYER_CHAT")); - pm.addActionListener(a -> actions.openPrivateChat(client)); - menu.add(pm); - JMenuItem poke = new JMenuItem("Poke", Icons.of("POKE")); - poke.addActionListener(a -> actions.pokeClient(client)); - menu.add(poke); - JMenuItem complain = new JMenuItem("Make a Complaint", Icons.of("SEND_COMPLAINT")); - complain.addActionListener(a -> actions.complainAboutClient(client)); - menu.add(complain); - menu.addSeparator(); - JMenuItem kickChannel = new JMenuItem("Kick Client from Channel", Icons.of("KICK_FROM_CHANNEL")); - kickChannel.addActionListener(a -> actions.kickClientFromChannel(client)); - menu.add(kickChannel); - JMenuItem kickServer = new JMenuItem("Kick Client from Server", Icons.of("KICK_FROM_SERVER")); - kickServer.addActionListener(a -> actions.kickClientFromServer(client)); - menu.add(kickServer); - JMenuItem ban = new JMenuItem("Ban Client", Icons.of("BAN_CLIENT")); - ban.addActionListener(a -> actions.banClient(client)); - menu.add(ban); - boolean muted = actions.isClientLocallyMuted(client.id); - JMenuItem mute = new JMenuItem(muted ? "Unmute client" : "Mute client", - Icons.of(muted ? "PLAYER_ON" : "INPUT_MUTED")); - mute.addActionListener(a -> actions.toggleClientMute(client)); - menu.add(mute); - JMenuItem volume = new JMenuItem("Change Volume…", Icons.of("VOLUME")); - volume.addActionListener(a -> actions.changeClientVolume(client)); - menu.add(volume); - menu.addSeparator(); - addContactItems(menu, client, actions); - } else { - JMenuItem me = new JMenuItem("This is you", Icons.of("PLAYER_OFF")); - me.setEnabled(false); - menu.add(me); - } - menu.addSeparator(); - menu.add(buildServerGroupMenu(client, model, groupIcons, actions)); - menu.add(buildChannelGroupMenu(client, model, groupIcons, actions)); - menu.addSeparator(); - if (!fromTree) { - JMenuItem findInTree = new JMenuItem("Find Client in Channel Tree", Icons.of("CHANNEL_SWITCH")); - findInTree.setEnabled(model.isChannelVisible(client.channelId)); - findInTree.addActionListener(a -> actions.findClientInTree(client)); - menu.add(findInTree); - } - JMenuItem description = new JMenuItem("Change Description", Icons.of("EDIT")); - description.addActionListener(a -> actions.changeClientDescription(client)); - menu.add(description); - if (!self && !client.avatarFlag.isEmpty() && actions.canDeleteOtherAvatars()) { - JMenuItem avatar = new JMenuItem("Delete Avatar", Icons.of("DELETE_AVATAR_OTHER")); - avatar.addActionListener(a -> actions.deleteClientAvatar(client)); - menu.add(avatar); - } - JMenuItem info = new JMenuItem("Connection Info", Icons.of("INFO")); - info.addActionListener(a -> actions.showConnectionInfo(client)); - menu.add(info); - if (!self) { - menu.addSeparator(); - JMenuItem joinChannel = new JMenuItem("Join Channel of Client", Icons.of("CHANNEL_SWITCH")); - joinChannel.setEnabled(model.canJoinChannel(client.channelId)); - joinChannel.addActionListener(a -> actions.joinChannel(client.channelId)); - menu.add(joinChannel); - JMenuItem moveHere = new JMenuItem("Move Client to own Channel", Icons.of("MOVE_CLIENT_TO_OWN_CHANNEL")); - moveHere.addActionListener(a -> actions.moveClientToOwnChannel(client)); - menu.add(moveHere); - } - return menu; - } - - /** - * The contact entries, as TeamSpeak offers them: a client not on the list can be - * added as a friend or blocked; one on it can be edited or removed. - */ - private static void addContactItems(JPopupMenu menu, ClientEntry client, ServerTreePanel.Actions actions) { - ContactType type = actions.contactTypeOf(client); - if (type == null) { - JMenuItem friend = new JMenuItem("Add as Friend", Icons.of("ADD_FRIEND")); - friend.addActionListener(a -> actions.addContact(client, ContactType.FRIEND)); - menu.add(friend); - JMenuItem blocked = new JMenuItem("Add as Blocked", Icons.of("ADD_FOE")); - blocked.addActionListener(a -> actions.addContact(client, ContactType.BLOCKED)); - menu.add(blocked); - return; - } - JMenuItem edit = new JMenuItem("Edit in Contacts", Icons.of("EDIT_FRIEND_FOE_STATUS")); - edit.addActionListener(a -> actions.editContact(client)); - menu.add(edit); - JMenuItem remove = new JMenuItem("Remove from Contacts", - Icons.of(type == ContactType.BLOCKED ? "REMOVE_FOE" : "REMOVE_FRIEND")); - remove.addActionListener(a -> actions.removeContact(client)); - menu.add(remove); - } - - private static JMenu buildServerGroupMenu(ClientEntry client, ServerModel model, GroupIcons groupIcons, - ServerTreePanel.Actions actions) { - JMenu menu = new JMenu("Set Server Groups"); - menu.setIcon(Icons.of("PERMISSIONS_SERVER_GROUPS")); - JMenuItem dialog = new JMenuItem("Server Groups Dialog..."); - dialog.addActionListener(a -> actions.showServerGroupsDialog(client)); - menu.add(dialog); - menu.addSeparator(); - - for (GroupChoice choice : model.serverGroupChoices(client)) { - if (!choice.allowed()) continue; - Group g = choice.group(); - JCheckBoxMenuItem item = new JCheckBoxMenuItem(g.name, groupIcons.iconOf(g)); - item.setSelected(choice.assigned()); - item.addActionListener(a -> actions.setClientServerGroup(client, g, !choice.assigned())); - menu.add(item); - } - return menu; - } - - private static JMenu buildChannelGroupMenu(ClientEntry client, ServerModel model, GroupIcons groupIcons, - ServerTreePanel.Actions actions) { - JMenu menu = new JMenu("Set Channel Group"); - menu.setIcon(Icons.of("PERMISSIONS_CHANNEL_GROUPS")); - int defaultGroupId = model.defaultChannelGroupId(); - for (GroupChoice choice : model.channelGroupChoices(client)) { - Group g = choice.group(); - if (g.id == defaultGroupId || !choice.allowed()) continue; - JCheckBoxMenuItem item = new JCheckBoxMenuItem(g.name, groupIcons.iconOf(g)); - item.setSelected(choice.assigned()); - item.addActionListener(a -> actions.setClientChannelGroup(client, g)); - menu.add(item); - } - return menu; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ClientVersionPanel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ClientVersionPanel.java deleted file mode 100644 index e37441d..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ClientVersionPanel.java +++ /dev/null @@ -1,187 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.config.ClientVersion; -import com.ts3client.config.Settings; - -import javax.swing.DefaultListCellRenderer; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JTextField; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; - -/** - * The Application page's section for the version and operating system reported to the server, which - * is what other clients see next to the nickname ("3.6.2 on Windows"). - * - *

    Servers verify TeamSpeak's signature over the version and platform and refuse - * the connection ("client is modified") when it does not match, so the page is - * built around the signed versions in {@link ClientVersion#PRESETS}. The fields - * behind them can still be edited by hand for a version whose signature is known - * from somewhere else. Changes take effect on the next connect. - */ -final class ClientVersionPanel extends JPanel { - - /** Combo entry that leaves the three fields to the user. */ - private static final String CUSTOM = "Custom…"; - - private final Settings settings; - - private final JCheckBox enabled = new JCheckBox("Report a custom version and operating system"); - private final JComboBox presetCombo = new JComboBox<>(); - private final JTextField versionField = new JTextField(24); - private final JComboBox platformCombo = new JComboBox<>(); - private final JTextField signField = new JTextField(24); - - /** Set while a preset is being copied into the fields, so that does not count as an edit. */ - private boolean filling; - - ClientVersionPanel(Settings settings) { - super(new BorderLayout(0, UIScale.scale(8))); - this.settings = settings; - - add(buildForm(), BorderLayout.NORTH); - - load(); - enabled.addActionListener(e -> updateEnabled()); - updateEnabled(); - } - - /** Copies the edited version into the settings; the caller saves them. */ - void apply() { - settings.customVersion = enabled.isSelected(); - settings.clientVersion = versionField.getText().trim(); - settings.clientPlatform = String.valueOf(platformCombo.getEditor().getItem()).trim(); - settings.clientVersionSign = signField.getText().trim(); - } - - private JComponent buildForm() { - JPanel p = new JPanel(new GridBagLayout()); - GridBagConstraints c = new GridBagConstraints(); - c.insets = UIScale.scale(new Insets(2, 2, 2, 2)); - c.anchor = GridBagConstraints.WEST; - c.fill = GridBagConstraints.HORIZONTAL; - - presetCombo.addItem(CUSTOM); - for (ClientVersion preset : ClientVersion.PRESETS) presetCombo.addItem(preset); - presetCombo.setRenderer(new DefaultListCellRenderer() { - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, - boolean selected, boolean focus) { - super.getListCellRendererComponent(list, value, index, selected, focus); - setText(value instanceof ClientVersion v ? v.label() : String.valueOf(value)); - return this; - } - }); - presetCombo.setToolTipText("Versions with a signature TeamSpeak issued for them"); - presetCombo.addActionListener(e -> onPresetSelected()); - - platformCombo.setEditable(true); - for (String platform : ClientVersion.PLATFORMS) platformCombo.addItem(platform); - - versionField.setToolTipText("Version string, e.g. 3.6.2 [Build: 1695203293]"); - platformCombo.setToolTipText("Operating system shown to other clients"); - signField.setToolTipText("TeamSpeak's signature for this version and platform"); - versionField.getDocument().addDocumentListener(new EditListener()); - signField.getDocument().addDocumentListener(new EditListener()); - platformCombo.addActionListener(e -> onFieldEdited()); - - int row = 0; - c.gridx = 0; - c.gridy = row++; - c.gridwidth = 2; - p.add(enabled, c); - c.gridwidth = 1; - - addRow(p, c, row++, new JLabel("Version:"), presetCombo); - addRow(p, c, row++, new JLabel("Version string:"), versionField); - addRow(p, c, row++, new JLabel("Operating system:"), platformCombo); - addRow(p, c, row++, new JLabel("Signature:"), signField); - - c.gridx = 0; - c.gridy = row; - c.gridwidth = 2; - JLabel note = new JLabel("Servers refuse made-up or outdated versions (\"client is modified\")." - + "
    Takes effect on the next connect."); - note.setEnabled(false); - p.add(note, c); - return p; - } - - private void load() { - enabled.setSelected(settings.customVersion); - ClientVersion preset = ClientVersion.match( - settings.clientVersion, settings.clientPlatform, settings.clientVersionSign); - fill(preset != null ? preset - : new ClientVersion("", settings.clientVersion, settings.clientPlatform, settings.clientVersionSign)); - presetCombo.setSelectedItem(preset != null ? preset : CUSTOM); - } - - private void onPresetSelected() { - if (presetCombo.getSelectedItem() instanceof ClientVersion preset) fill(preset); - } - - /** A hand-edited field no longer describes the selected preset. */ - private void onFieldEdited() { - if (filling) return; - ClientVersion preset = ClientVersion.match(versionField.getText().trim(), - String.valueOf(platformCombo.getEditor().getItem()).trim(), signField.getText().trim()); - presetCombo.setSelectedItem(preset != null ? preset : CUSTOM); - } - - private void fill(ClientVersion version) { - filling = true; - try { - versionField.setText(version.version()); - platformCombo.setSelectedItem(version.platform()); - platformCombo.getEditor().setItem(version.platform()); - signField.setText(version.sign()); - } finally { - filling = false; - } - } - - private void updateEnabled() { - boolean on = enabled.isSelected(); - presetCombo.setEnabled(on); - versionField.setEnabled(on); - platformCombo.setEnabled(on); - signField.setEnabled(on); - } - - /** Notices any typing in the version or signature field. */ - private final class EditListener implements javax.swing.event.DocumentListener { - @Override - public void insertUpdate(javax.swing.event.DocumentEvent e) { - onFieldEdited(); - } - - @Override - public void removeUpdate(javax.swing.event.DocumentEvent e) { - onFieldEdited(); - } - - @Override - public void changedUpdate(javax.swing.event.DocumentEvent e) { - onFieldEdited(); - } - } - - private static void addRow(JPanel p, GridBagConstraints c, int row, JLabel label, Component field) { - c.gridx = 0; - c.gridy = row; - c.weightx = 0; - p.add(label, c); - c.gridx = 1; - c.weightx = 1; - p.add(field, c); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ClientVolumeDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ClientVolumeDialog.java deleted file mode 100644 index 6f00aec..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ClientVolumeDialog.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.net.ClientEntry; -import com.ts3client.net.TeamspeakConnection; - -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSlider; -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.Frame; - -/** - * TeamSpeak's "Change Volume" for one client: a gain in decibels on top of the - * master volume, applied as the slider moves. It is remembered in the client's - * contact entry, when it has one; otherwise it lasts for the session. - */ -final class ClientVolumeDialog extends JDialog { - - private static final int RANGE_DB = 40; - - private final TeamspeakConnection conn; - private final ClientEntry client; - private final JSlider slider = new JSlider(-RANGE_DB, RANGE_DB, 0); - private final JLabel value = new JLabel(); - - ClientVolumeDialog(Frame owner, TeamspeakConnection conn, ClientEntry client) { - super(owner, "Change Volume: " + conn.displayName(client), false); - this.conn = conn; - this.client = client; - - slider.setValue((int) Math.round(conn.getClientVolumeModifier(client))); - slider.setMajorTickSpacing(20); - slider.setMinorTickSpacing(5); - slider.setPaintTicks(true); - slider.setPaintLabels(true); - slider.addChangeListener(e -> onChanged()); - FormPanel.limitWidth(value, 60); - - JPanel content = new JPanel(new BorderLayout(UIScale.scale(8), UIScale.scale(8))); - content.setBorder(new ScaledEmptyBorder(12, 12, 8, 12)); - content.add(new JLabel("Volume Modifier"), BorderLayout.NORTH); - content.add(FormPanel.sliderWithLabel(slider, value), BorderLayout.CENTER); - JLabel hint = new JLabel("Values greater than +6 dB will cause clipping " - + "and distortion that will negatively affect your audio quality. It is advised to choose " - + "lower values."); - hint.setForeground(Theme.chatSystem()); - content.add(hint, BorderLayout.SOUTH); - - JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT)); - JButton reset = new JButton("Reset"); - reset.addActionListener(e -> slider.setValue(0)); - JButton close = new JButton("Close"); - close.addActionListener(e -> dispose()); - buttons.add(reset); - buttons.add(close); - - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(content, BorderLayout.CENTER); - getContentPane().add(buttons, BorderLayout.SOUTH); - - onChanged(); - Dialogs.closeOnEscape(this); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - pack(); - setMinimumSize(new Dimension(UIScale.scale(360), getHeight())); - setLocationRelativeTo(owner); - } - - private void onChanged() { - int db = slider.getValue(); - value.setText((db > 0 ? "+" : "") + db + " dB"); - if (!slider.getValueIsAdjusting()) conn.setClientVolumeModifier(client, db); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ComplaintsDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ComplaintsDialog.java deleted file mode 100644 index b6f3acf..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ComplaintsDialog.java +++ /dev/null @@ -1,511 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.net.ClientEntry; -import com.ts3client.net.Complaint; -import com.ts3client.net.ServerModel; -import com.ts3client.net.TeamspeakConnection; - -import javax.swing.AbstractAction; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.Icon; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.KeyStroke; -import javax.swing.ListSelectionModel; -import javax.swing.SwingUtilities; -import javax.swing.UIManager; -import javax.swing.event.PopupMenuEvent; -import javax.swing.event.PopupMenuListener; -import javax.swing.table.AbstractTableModel; -import javax.swing.table.DefaultTableCellRenderer; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Frame; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.time.Instant; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Consumer; - -/** - * The server's complaints, as the official client's Tools > Complaints List window: one - * collapsible row per client complained about, with each complaint's date, author and - * reason beneath it. - * - *

    One per server tab and modeless, like the ban list; the tab closes it when the - * connection goes away. - */ -final class ComplaintsDialog extends JDialog { - - private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - - private enum Column { - TARGET("Target Nickname", 200), - FROM("From Nickname", 160), - REASON("Reason", 280); - - final String title; - final int width; - - Column(String title, int width) { - this.title = title; - this.width = width; - } - } - - /** A client complained about, with the complaints against them. */ - private record Target(int dbId, String name, List complaints) { - } - - /** A row of the table: a target, or one complaint under its expanded target. */ - private record Row(Target target, Complaint complaint) { - boolean isTarget() { - return complaint == null; - } - } - - private final TeamspeakConnection conn; - private final Consumer banClient; - - private final ComplaintTableModel tableModel = new ComplaintTableModel(); - private final JTable table = new JTable(tableModel) { - /** The popup acts on what was clicked, as a tree's would; Swing asks here before showing it. */ - @Override - public Point getPopupLocation(MouseEvent e) { - int row = e == null ? -1 : rowAtPoint(e.getPoint()); - if (row >= 0 && !isRowSelected(row)) setRowSelectionInterval(row, row); - return super.getPopupLocation(e); - } - }; - private final JButton removeButton = new JButton("Remove", Icons.of("DELETE")); - private final JLabel status = new JLabel(" "); - private final JMenuItem removeItem = item("Remove", "DELETE", this::removeSelected); - private final JMenuItem banItem = item("Ban Client", "BAN_CLIENT", this::banSelected); - - private List targets = List.of(); - /** Targets shown expanded, by database id; kept across reloads. */ - private final Set expanded = new HashSet<>(); - private boolean loading; - - /** @param banClient opens the ban dialog for an online client */ - ComplaintsDialog(Frame owner, TeamspeakConnection conn, Consumer banClient) { - super(owner, "Complaints List", false); - this.conn = conn; - this.banClient = banClient; - - JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(6))); - content.setBackground(Theme.windowBg()); - content.setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); - content.add(buildToolbar(), BorderLayout.NORTH); - content.add(buildTable(), BorderLayout.CENTER); - content.add(buildBottom(), BorderLayout.SOUTH); - setContentPane(content); - bindKeys(); - - serverNameChanged(); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - setPreferredSize(UIScale.scale(new Dimension(680, 420))); - pack(); - setLocationRelativeTo(owner); - reload(); - } - - // ---- construction ---- - - private JPanel buildToolbar() { - removeButton.setToolTipText("Remove selected complaints
    (Delete)"); - removeButton.addActionListener(e -> removeSelected()); - - JPanel bar = new JPanel(); - bar.setLayout(new BoxLayout(bar, BoxLayout.X_AXIS)); - bar.setOpaque(false); - bar.add(removeButton); - bar.add(Box.createHorizontalGlue()); - return bar; - } - - private JScrollPane buildTable() { - table.setFont(Theme.uiFont()); - table.setRowHeight(UIScale.scale(20)); - table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - table.setFillsViewportHeight(true); - table.setShowGrid(false); - table.getTableHeader().setReorderingAllowed(false); - table.getSelectionModel().addListSelectionListener(e -> updateButtons()); - table.setComponentPopupMenu(tablePopup()); - table.addMouseListener(new ToggleOnClick()); - ComplaintCellRenderer renderer = new ComplaintCellRenderer(); - for (Column c : Column.values()) { - table.getColumnModel().getColumn(c.ordinal()).setPreferredWidth(UIScale.scale(c.width)); - table.getColumnModel().getColumn(c.ordinal()).setCellRenderer(renderer); - } - - JScrollPane scroll = new JScrollPane(table); - scroll.getViewport().setBackground(Theme.treeBg()); - return scroll; - } - - private JPanel buildBottom() { - JButton reload = new JButton("Reload", Icons.of("REFRESH")); - reload.setToolTipText("Reload complaints
    (F5)"); - reload.addActionListener(e -> reload()); - JButton close = new JButton("Close"); - close.addActionListener(e -> dispose()); - - JPanel row = new JPanel(new BorderLayout()); - row.setOpaque(false); - row.add(reload, BorderLayout.WEST); - row.add(close, BorderLayout.EAST); - - JPanel bottom = new JPanel(new BorderLayout(0, UIScale.scale(8))); - bottom.setOpaque(false); - bottom.add(status, BorderLayout.NORTH); - bottom.add(row, BorderLayout.SOUTH); - status.setForeground(Theme.chatEvent()); - return bottom; - } - - private JPopupMenu tablePopup() { - JPopupMenu menu = new JPopupMenu(); - menu.add(item("Reload", "REFRESH", this::reload)); - menu.addSeparator(); - menu.add(removeItem); - menu.add(banItem); - menu.addPopupMenuListener(new PopupMenuListener() { - @Override - public void popupMenuWillBecomeVisible(PopupMenuEvent e) { - removeItem.setEnabled(removeButton.isEnabled()); - banItem.setEnabled(banTarget() != null); - } - - @Override - public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { - } - - @Override - public void popupMenuCanceled(PopupMenuEvent e) { - } - }); - return menu; - } - - private static JMenuItem item(String text, String icon, Runnable action) { - JMenuItem item = new JMenuItem(text, Icons.of(icon)); - item.addActionListener(e -> action.run()); - return item; - } - - private void bindKeys() { - bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("F5"), this::reload); - bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control W"), this::dispose); - bind(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), - this::removeSelected); - bind(table, JComponent.WHEN_FOCUSED, KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), () -> setLeadExpanded(true)); - bind(table, JComponent.WHEN_FOCUSED, KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), () -> setLeadExpanded(false)); - Dialogs.closeOnEscape(this); - } - - private static void bind(JComponent target, int condition, KeyStroke key, Runnable action) { - String name = "ts3-complaints-" + key; - target.getInputMap(condition).put(key, name); - target.getActionMap().put(name, new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - action.run(); - } - }); - } - - // ---- data ---- - - /** Follows the server's name, as the ban list's title does. */ - void serverNameChanged() { - String name = conn.getModel().getServerName(); - setTitle(name == null || name.isBlank() ? "Complaints List" : "Complaints List - " + name); - } - - void connectionLost() { - dispose(); - } - - private void reload() { - if (loading) return; - loading = true; - status.setText("Loading…"); - conn.requestComplaints((complaints, error) -> SwingUtilities.invokeLater(() -> { - loading = false; - if (!isDisplayable()) return; - if (error != null) { - setTargets(List.of()); - status.setText("Failed to request complaint list: " + error); - } else { - setTargets(groupByTarget(complaints)); - status.setText(complaints.size() == 1 ? "1 complaint" : complaints.size() + " complaints"); - } - })); - } - - private static List groupByTarget(List complaints) { - Map byId = new LinkedHashMap<>(); - for (Complaint c : complaints) { - byId.computeIfAbsent(c.targetDbId(), id -> new Target(id, c.targetName(), new ArrayList<>())) - .complaints().add(c); - } - List out = new ArrayList<>(byId.values()); - out.sort(Comparator.comparing(Target::name, String.CASE_INSENSITIVE_ORDER)); - for (Target t : out) t.complaints().sort(Comparator.comparingLong(Complaint::timestampEpochSeconds)); - return out; - } - - private void setTargets(List targets) { - this.targets = targets; - rebuildRows(); - } - - /** Lays the rows out again after a reload or a target opening or closing, keeping the selection. */ - private void rebuildRows() { - Set selected = new HashSet<>(selectedRows()); - List rows = new ArrayList<>(); - for (Target t : targets) { - rows.add(new Row(t, null)); - if (expanded.contains(t.dbId())) { - for (Complaint c : t.complaints()) rows.add(new Row(t, c)); - } - } - tableModel.setRows(rows); - for (int i = 0; i < rows.size(); i++) { - if (selected.contains(rows.get(i))) table.addRowSelectionInterval(i, i); - } - updateButtons(); - } - - private void setExpanded(Target target, boolean open) { - if (open ? expanded.add(target.dbId()) : expanded.remove(target.dbId())) rebuildRows(); - } - - private void setLeadExpanded(boolean open) { - int lead = table.getSelectionModel().getLeadSelectionIndex(); - if (lead < 0 || lead >= tableModel.getRowCount()) return; - Row row = tableModel.get(lead); - if (row.isTarget()) { - setExpanded(row.target(), open); - } else if (!open) { - int parent = tableModel.indexOf(new Row(row.target(), null)); - setExpanded(row.target(), false); - table.setRowSelectionInterval(parent, parent); - } - } - - private List selectedRows() { - List rows = new ArrayList<>(); - for (int i : table.getSelectedRows()) rows.add(tableModel.get(i)); - return rows; - } - - /** Whole targets selected, and complaints selected on their own (not under a selected target). */ - private Selection selection() { - Set whole = new LinkedHashSet<>(); - List single = new ArrayList<>(); - List rows = selectedRows(); - for (Row r : rows) if (r.isTarget()) whole.add(r.target()); - for (Row r : rows) if (!r.isTarget() && !whole.contains(r.target())) single.add(r.complaint()); - return new Selection(whole, single); - } - - private record Selection(Set whole, List single) { - boolean isEmpty() { - return whole.isEmpty() && single.isEmpty(); - } - - List affected() { - List all = new ArrayList<>(single); - for (Target t : whole) all.addAll(t.complaints()); - return all; - } - } - - private int selfDbId() { - ClientEntry self = conn.getModel().getClient(conn.getSelfClientId()); - return self == null ? 0 : self.databaseId; - } - - private void updateButtons() { - Selection sel = selection(); - removeButton.setEnabled(!sel.isEmpty() && conn.getModel().canDeleteComplaints(sel.affected(), selfDbId())); - } - - /** - * Who Ban Client acts on: the target on a target row, the author on a complaint row, - * as in the official client. Only an online client can be banned this way. - */ - private ClientEntry banTarget() { - int[] rows = table.getSelectedRows(); - if (rows.length != 1) return null; - ServerModel model = conn.getModel(); - if (model.selfPower("i_client_ban_power") == 0) return null; - Row row = tableModel.get(rows[0]); - ClientEntry client = model.findClientByDatabaseId(row.isTarget() ? row.target().dbId() : row.complaint().fromDbId()); - return client == null || client.id == conn.getSelfClientId() ? null : client; - } - - // ---- actions ---- - - private void removeSelected() { - if (!removeButton.isEnabled()) return; - Selection sel = selection(); - String question = sel.single().isEmpty() && sel.whole().size() == 1 - ? "Do you really want to remove all complaints of this user?" - : "Do you really want to remove the selected complaint(s)?"; - int answer = JOptionPane.showConfirmDialog(this, question, "Remove Complaints", - JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); - if (answer != JOptionPane.YES_OPTION) return; - List whole = sel.whole().stream().map(Target::dbId).toList(); - conn.deleteComplaints(whole, sel.single(), error -> SwingUtilities.invokeLater(() -> { - if (!isDisplayable()) return; - if (error != null) { - JOptionPane.showMessageDialog(this, "Failed to delete complaints: " + error, getTitle(), - JOptionPane.ERROR_MESSAGE); - } - reload(); - })); - } - - private void banSelected() { - ClientEntry client = banTarget(); - if (client != null) banClient.accept(client); - } - - // ---- table ---- - - private final class ToggleOnClick extends MouseAdapter { - @Override - public void mousePressed(MouseEvent e) { - int row = table.rowAtPoint(e.getPoint()); - if (row < 0 || !SwingUtilities.isLeftMouseButton(e)) return; - Row clicked = tableModel.get(row); - if (!clicked.isTarget()) return; - boolean onHandle = table.columnAtPoint(e.getPoint()) == Column.TARGET.ordinal() - && e.getX() - table.getCellRect(row, 0, false).x < handleWidth(); - if (onHandle || e.getClickCount() == 2) { - setExpanded(clicked.target(), !expanded.contains(clicked.target().dbId())); - } - } - } - - private static Icon handleIcon(boolean open) { - return UIManager.getIcon(open ? "Tree.expandedIcon" : "Tree.collapsedIcon"); - } - - private static int handleWidth() { - Icon icon = handleIcon(false); - return (icon == null ? UIScale.scale(12) : icon.getIconWidth()) + UIScale.scale(6); - } - - private final class ComplaintTableModel extends AbstractTableModel { - - private List rows = List.of(); - - void setRows(List rows) { - this.rows = rows; - fireTableDataChanged(); - } - - Row get(int row) { - return rows.get(row); - } - - int indexOf(Row row) { - return rows.indexOf(row); - } - - @Override - public int getRowCount() { - return rows.size(); - } - - @Override - public int getColumnCount() { - return Column.values().length; - } - - @Override - public String getColumnName(int column) { - return Column.values()[column].title; - } - - @Override - public Object getValueAt(int row, int column) { - return text(rows.get(row), Column.values()[column]); - } - - String text(Row row, Column column) { - if (row.isTarget()) { - int n = row.target().complaints().size(); - return switch (column) { - case TARGET -> row.target().name(); - case FROM -> ""; - case REASON -> n == 1 ? "has 1 complaint" : "has " + n + " complaints"; - }; - } - Complaint c = row.complaint(); - return switch (column) { - case TARGET -> c.timestampEpochSeconds() <= 0 ? "" : DATE.format( - Instant.ofEpochSecond(c.timestampEpochSeconds()).atZone(ZoneId.systemDefault())); - case FROM -> c.fromName(); - case REASON -> c.message(); - }; - } - } - - /** Draws the tree handle and indent in the first column, and a target's count greyed out. */ - private final class ComplaintCellRenderer extends DefaultTableCellRenderer { - @Override - public Component getTableCellRendererComponent(JTable t, Object value, boolean selected, - boolean focused, int row, int column) { - // setForeground sticks as the renderer's unselected colour; clear it so the - // table's own colour applies again after a greyed cell. - setForeground(null); - super.getTableCellRendererComponent(t, value, selected, focused, row, column); - Row r = tableModel.get(row); - Column c = Column.values()[column]; - setIcon(null); - setBorder(new ScaledEmptyBorder(0, 2, 0, 2)); - if (c == Column.TARGET) { - if (r.isTarget()) { - setIcon(handleIcon(expanded.contains(r.target().dbId()))); - setIconTextGap(UIScale.scale(6)); - } else { - setBorder(new ScaledEmptyBorder(0, 2 + UIScale.unscale(handleWidth()) + 6, 0, 2)); - } - } - setToolTipText(c == Column.REASON && !r.isTarget() && !r.complaint().message().isEmpty() - ? r.complaint().message() : null); - if (c == Column.REASON && r.isTarget() && !selected) setForeground(UIManager.getColor("Label.disabledForeground")); - return this; - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ConnectDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ConnectDialog.java deleted file mode 100644 index 8cae869..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ConnectDialog.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.config.IdentityStore; -import com.ts3client.config.Settings; - -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JPasswordField; -import javax.swing.JTextField; -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.Frame; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; - -/** Modal "Connect to Server" dialog. */ -public final class ConnectDialog extends JDialog { - - private final JTextField addressField; - private final JTextField portField; - private final JTextField nickField; - private final JPasswordField passwordField; - private final IdentityChooser identityChooser; - - private boolean confirmed; - - public ConnectDialog(Frame owner, Settings settings, IdentityStore identities) { - super(owner, "Connect to Server", true); - - String addr = settings.lastAddress; - int port = 9987; - int colon = addr.lastIndexOf(':'); - if (colon > 0) { - try { - port = Integer.parseInt(addr.substring(colon + 1)); - addr = addr.substring(0, colon); - } catch (NumberFormatException ignored) { - } - } - - addressField = new JTextField(addr, 18); - portField = new JTextField(Integer.toString(port), 6); - nickField = new JTextField(settings.nickname, 18); - passwordField = new JPasswordField(settings.serverPassword, 18); - identityChooser = new IdentityChooser(identities, false, settings.defaultIdentityId); - - JPanel form = new JPanel(new GridBagLayout()); - form.setBorder(new ScaledEmptyBorder(12, 12, 8, 12)); - GridBagConstraints c = new GridBagConstraints(); - c.insets = UIScale.scale(new Insets(4, 4, 4, 4)); - c.anchor = GridBagConstraints.WEST; - c.fill = GridBagConstraints.HORIZONTAL; - - int row = 0; - add(form, c, row++, "Server address:", addressField); - add(form, c, row++, "Port:", portField); - add(form, c, row++, "Nickname:", nickField); - add(form, c, row++, "Password (optional):", passwordField); - add(form, c, row++, "Identity:", identityChooser); - - JPanel buttons = new JPanel(new BorderLayout()); - JPanel right = new JPanel(); - JButton connect = new JButton("Connect"); - JButton cancel = new JButton("Cancel"); - connect.addActionListener(e -> { - confirmed = true; - dispose(); - }); - cancel.addActionListener(e -> dispose()); - right.add(connect); - right.add(cancel); - buttons.add(right, BorderLayout.EAST); - getRootPane().setDefaultButton(connect); - - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(form, BorderLayout.CENTER); - getContentPane().add(buttons, BorderLayout.SOUTH); - - Dialogs.closeOnEscape(this); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - pack(); - setMinimumSize(new Dimension(UIScale.scale(340), getHeight())); - setLocationRelativeTo(owner); - } - - private void add(JPanel form, GridBagConstraints c, int row, String label, java.awt.Component field) { - c.gridx = 0; - c.gridy = row; - c.weightx = 0; - form.add(new JLabel(label), c); - c.gridx = 1; - c.weightx = 1; - form.add(field, c); - } - - public boolean isConfirmed() { - return confirmed; - } - - public String getAddress() { - return addressField.getText().trim(); - } - - public int getPort() { - try { - return Integer.parseInt(portField.getText().trim()); - } catch (NumberFormatException e) { - return 9987; - } - } - - public String getNickname() { - String n = nickField.getText().trim(); - return n.isEmpty() ? "TS3J User" : n; - } - - public String getPassword() { - return new String(passwordField.getPassword()); - } - - /** Chosen identity id, or an empty string to fall back to the default identity. */ - public String getIdentityId() { - return identityChooser.getSelectedIdentityId(); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ConnectionInfoDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ConnectionInfoDialog.java deleted file mode 100644 index f136006..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ConnectionInfoDialog.java +++ /dev/null @@ -1,337 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.net.ClientEntry; -import com.ts3client.net.ConnectionStats; -import com.ts3client.net.ConnectionStatsFormat; -import com.ts3client.net.ConnectionStatsFormat.Row; -import com.ts3client.net.ConnectionStatsFormat.TrafficRow; -import com.ts3client.net.TeamspeakConnection; -import com.ts3client.net.avatar.Avatar; - -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSeparator; -import javax.swing.JTabbedPane; -import javax.swing.SwingConstants; -import javax.swing.SwingUtilities; -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Frame; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Image; -import java.awt.Insets; -import java.awt.Toolkit; -import java.awt.datatransfer.StringSelection; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Live "Client Connection Info" window, laid out as TeamSpeak 3's: name, times, ping and - * address beside the avatar, above a tab per traffic category whose table has Total / In / - * Out columns, and a Quota tab. A Voice received tab adds what our own playback - * made of the client's voice (everyone's, for ourselves). Polls once a second while open. - */ -public final class ConnectionInfoDialog extends JDialog { - - private static final int REFRESH_MS = 1000; - /** Avatar box, about the official window's. */ - private static final int AVATAR_SIZE = 80; - /** Sample texts sizing the columns, as the official window does, so they don't jitter. */ - private static final String TOTAL_SAMPLE = "100.00 %"; - private static final String VALUE_SAMPLE = "1023.00 KiB/s"; - - private final TeamspeakConnection conn; - private final int clientId; - private final String nickname; - private final javax.swing.Timer timer; - private final AtomicBoolean inFlight = new AtomicBoolean(); - - private final Figures summary; - private final JButton copyAddress = new JButton(Icons.of("COPY")); - private final JLabel avatar = new JLabel(); - private Avatar shownAvatar; - private ConnectionStats latest; - - private final List traffic = new ArrayList<>(); - private Figures quota; - private final Figures voice = new Figures(List.of(ConnectionStatsFormat.voiceRows(null)), false); - - public ConnectionInfoDialog(Frame owner, TeamspeakConnection conn, int clientId, String nickname) { - super(owner, "Connection Info - " + nickname, false); - this.conn = conn; - this.clientId = clientId; - this.nickname = nickname; - this.summary = new Figures(List.of(ConnectionStatsFormat.summaryRows(null, nickname)), true); - - JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(12))); - content.setBackground(Theme.windowBg()); - content.setBorder(new ScaledEmptyBorder(10, 10, 10, 10)); - content.add(buildHeader(), BorderLayout.NORTH); - content.add(buildTabs(), BorderLayout.CENTER); - content.add(buildButtons(), BorderLayout.SOUTH); - setContentPane(content); - - Dialogs.closeOnEscape(this); - // Disposing is what stops the refresh timer, so the window button must not merely hide. - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - pack(); - setLocationRelativeTo(owner); - - addWindowListener(new WindowAdapter() { - @Override - public void windowClosed(WindowEvent e) { - timer.stop(); - } - }); - - timer = new javax.swing.Timer(REFRESH_MS, e -> refresh()); - timer.setInitialDelay(0); - timer.start(); - } - - // ---- construction ---- - - private JPanel buildHeader() { - copyAddress.setToolTipText("Copy client address to clipboard"); - copyAddress.setMargin(UIScale.scale(new Insets(1, 1, 1, 1))); - copyAddress.setEnabled(false); - copyAddress.addActionListener(e -> { - String address = ConnectionStatsFormat.copyableAddress(latest); - if (address != null) { - Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(address), null); - } - }); - summary.addTrailing(copyAddress); - - avatar.setVerticalAlignment(SwingConstants.TOP); - avatar.setBorder(new ScaledEmptyBorder(0, 16, 0, 0)); - - JPanel header = new JPanel(new BorderLayout()); - header.setOpaque(false); - header.add(summary, BorderLayout.CENTER); - header.add(avatar, BorderLayout.EAST); - return header; - } - - private JTabbedPane buildTabs() { - JTabbedPane tabs = new JTabbedPane(); - tabs.setFont(Theme.uiFont()); - for (ConnectionStatsFormat.Tab tab : ConnectionStatsFormat.TRAFFIC_TABS) { - TrafficTable table = new TrafficTable(tab.kind()); - traffic.add(table); - tabs.addTab(tab.title(), table); - } - tabs.addTab(ConnectionStatsFormat.QUOTA_TAB, buildQuota()); - tabs.addTab(ConnectionStatsFormat.VOICE_TAB, page(voice)); - return tabs; - } - - private JComponent buildQuota() { - // Laid out for ourselves, the longer form; another client's extra rows hide on the first update. - ConnectionStats self = new ConnectionStats(); - self.self = true; - quota = new Figures(ConnectionStatsFormat.quotaGroups(self), false); - return page(quota); - } - - private static JComponent page(JComponent body) { - JPanel page = new JPanel(new BorderLayout()); - page.setOpaque(false); - page.setBorder(new ScaledEmptyBorder(8, 10, 8, 10)); - page.add(body, BorderLayout.NORTH); - return page; - } - - private JPanel buildButtons() { - JPanel bar = new JPanel(); - bar.setLayout(new BoxLayout(bar, BoxLayout.X_AXIS)); - bar.setOpaque(false); - bar.add(Box.createHorizontalGlue()); - JButton close = new JButton("Close", Icons.of("CLOSE")); - close.addActionListener(e -> dispose()); - bar.add(close); - return bar; - } - - // ---- live update ---- - - private void refresh() { - if (!conn.isConnected()) { - timer.stop(); - return; - } - if (!inFlight.compareAndSet(false, true)) return; // a previous poll is still running - conn.requestConnectionInfo(clientId, stats -> SwingUtilities.invokeLater(() -> { - inFlight.set(false); - apply(stats); - })); - } - - private void apply(ConnectionStats s) { - if (!isDisplayable()) return; - latest = s; - summary.update(List.of(ConnectionStatsFormat.summaryRows(s, nickname))); - copyAddress.setEnabled(ConnectionStatsFormat.copyableAddress(s) != null); - for (TrafficTable table : traffic) table.update(s); - quota.update(ConnectionStatsFormat.quotaGroups(s)); - voice.update(List.of(ConnectionStatsFormat.voiceRows(s.voiceReceived))); - showAvatar(); - } - - private void showAvatar() { - ClientEntry client = conn.getModel().getClient(clientId); - Avatar current = conn.avatarOf(client); - if (current == shownAvatar) return; - shownAvatar = current; - avatar.setIcon(current == null ? null : avatarIcon(current)); - pack(); - } - - private static ImageIcon avatarIcon(Avatar avatar) { - if (avatar.file() == null) return null; - Dimension size = AvatarHtml.fit(AvatarHtml.dimensions(avatar.data()), UIScale.scale(AVATAR_SIZE)); - ImageIcon icon = new ImageIcon(avatar.data()); - if (size == null) return icon; - return new ImageIcon(icon.getImage().getScaledInstance(size.width, size.height, Image.SCALE_SMOOTH)); - } - - // ---- figures ---- - - private static JLabel label(String text) { - JLabel l = new JLabel(text); - l.setFont(Theme.uiFont()); - return l; - } - - /** Pins a label's width to that of {@code sample}, so a growing figure doesn't resize the window. */ - private static JLabel sized(JLabel l, String sample) { - Dimension pref = l.getPreferredSize(); - int width = l.getFontMetrics(l.getFont()).stringWidth(sample); - l.setPreferredSize(new Dimension(Math.max(pref.width, width), pref.height)); - return l; - } - - private static GridBagConstraints cell(int x, int y, int anchor, Insets insets) { - GridBagConstraints c = new GridBagConstraints(); - c.gridx = x; - c.gridy = y; - c.anchor = anchor; - c.insets = UIScale.scale(insets); - return c; - } - - /** - * Labelled figures, one per row, in groups set apart by a rule; refreshed in place, and - * rows an update leaves out hide. - */ - private static final class Figures extends JPanel { - private final List> groups = new ArrayList<>(); - private int lastRow; - - Figures(List> rows, boolean valuesRight) { - super(new GridBagLayout()); - setOpaque(false); - int y = 0; - for (List group : rows) { - if (y > 0) { - GridBagConstraints rule = cell(0, y++, GridBagConstraints.WEST, new Insets(6, 0, 6, 0)); - rule.gridwidth = 2; - rule.fill = GridBagConstraints.HORIZONTAL; - add(new JSeparator(), rule); - } - List labels = new ArrayList<>(); - for (Row row : group) { - JLabel key = label(row.label()); - JLabel value = label(row.value()); - labels.add(new JLabel[]{key, value}); - add(key, cell(0, y, GridBagConstraints.WEST, new Insets(3, 0, 3, 16))); - GridBagConstraints vc = cell(1, y, valuesRight ? GridBagConstraints.EAST : GridBagConstraints.WEST, - new Insets(3, 0, 3, 0)); - vc.weightx = 1; - add(value, vc); - lastRow = y++; - } - groups.add(labels); - } - } - - /** Puts {@code c} after the last row's value. */ - void addTrailing(JComponent c) { - add(c, cell(2, lastRow, GridBagConstraints.EAST, new Insets(0, 6, 0, 0))); - } - - void update(List> rows) { - for (int g = 0; g < groups.size(); g++) { - List labels = groups.get(g); - List group = rows.get(g); - for (int i = 0; i < labels.size(); i++) { - boolean shown = i < group.size(); - labels.get(i)[0].setVisible(shown); - labels.get(i)[1].setVisible(shown); - if (shown) labels.get(i)[1].setText(group.get(i).value()); - } - } - } - } - - /** One traffic category: a row per figure under Total / In / Out headings. */ - private static final class TrafficTable extends JPanel { - private final ConnectionStats.Kind kind; - private final JLabel[][] cells; - - TrafficTable(ConnectionStats.Kind kind) { - super(new GridBagLayout()); - this.kind = kind; - setOpaque(false); - setBorder(new ScaledEmptyBorder(8, 10, 8, 10)); - - List columns = ConnectionStatsFormat.COLUMNS; - for (int c = 0; c < columns.size(); c++) { - JLabel heading = label(columns.get(c)); - heading.setFont(heading.getFont().deriveFont(Font.ITALIC)); - add(heading, column(c + 1, 0)); - } - List rows = ConnectionStatsFormat.trafficRows(null, kind); - cells = new JLabel[rows.size()][]; - for (int r = 0; r < rows.size(); r++) { - TrafficRow row = rows.get(r); - add(label(row.label()), cell(0, r + 1, GridBagConstraints.WEST, new Insets(3, 0, 3, 8))); - cells[r] = new JLabel[]{ - sized(label(row.total()), TOTAL_SAMPLE), sized(label(row.in()), VALUE_SAMPLE), - sized(label(row.out()), VALUE_SAMPLE)}; - for (int c = 0; c < cells[r].length; c++) add(cells[r][c], column(c + 1, r + 1)); - } - GridBagConstraints filler = cell(0, rows.size() + 1, GridBagConstraints.WEST, new Insets(0, 0, 0, 0)); - filler.weighty = 1; - add(Box.createGlue(), filler); - } - - private static GridBagConstraints column(int x, int y) { - GridBagConstraints c = cell(x, y, GridBagConstraints.WEST, new Insets(3, 8, 3, 8)); - c.weightx = 1; - return c; - } - - void update(ConnectionStats s) { - List rows = ConnectionStatsFormat.trafficRows(s, kind); - for (int r = 0; r < rows.size(); r++) { - cells[r][0].setText(rows.get(r).total()); - cells[r][1].setText(rows.get(r).in()); - cells[r][2].setText(rows.get(r).out()); - } - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ContactDefaultsDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ContactDefaultsDialog.java deleted file mode 100644 index 206845e..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ContactDefaultsDialog.java +++ /dev/null @@ -1,201 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.config.Settings; -import com.ts3client.contacts.ContactDefaults; -import com.ts3client.contacts.ContactType; -import com.ts3client.contacts.NicknameDisplay; - -import javax.swing.BorderFactory; -import javax.swing.ButtonGroup; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JSeparator; -import javax.swing.SwingConstants; -import java.awt.BorderLayout; -import java.awt.Dialog; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.util.EnumMap; -import java.util.Map; -import java.util.function.BiConsumer; -import java.util.function.Function; - -/** - * TeamSpeak's "Contact Manager Default Settings": what a client starts out with - * when added as a friend, blocked or neutral — the ignore/hide flags and how its - * nickname is displayed — in a grid with one column per contact type. - */ -final class ContactDefaultsDialog extends JDialog { - - private static final ContactType[] COLUMNS = {ContactType.FRIEND, ContactType.BLOCKED, ContactType.NEUTRAL}; - - private final Settings settings; - private final Map> flags = new EnumMap<>(ContactType.class); - private final Map> displays = new EnumMap<>(ContactType.class); - - ContactDefaultsDialog(Dialog owner, Settings settings) { - super(owner, "Contact Manager Default Settings", true); - this.settings = settings; - for (ContactType t : COLUMNS) { - flags.put(t, new java.util.LinkedHashMap<>()); - displays.put(t, new EnumMap<>(NicknameDisplay.class)); - } - - JPanel content = new JPanel(); - content.setLayout(new javax.swing.BoxLayout(content, javax.swing.BoxLayout.Y_AXIS)); - content.setBorder(new ScaledEmptyBorder(12, 12, 8, 12)); - JLabel intro = new JLabel("Configure default settings when adding a client to the Contact Manager"); - intro.setAlignmentX(LEFT_ALIGNMENT); - content.add(intro); - content.add(javax.swing.Box.createVerticalStrut(UIScale.scale(10))); - content.add(buildFlags()); - content.add(javax.swing.Box.createVerticalStrut(UIScale.scale(10))); - content.add(buildDisplays()); - - JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT)); - JButton ok = new JButton("OK"); - ok.addActionListener(e -> { - apply(); - dispose(); - }); - JButton cancel = new JButton("Cancel"); - cancel.addActionListener(e -> dispose()); - buttons.add(ok); - buttons.add(cancel); - getRootPane().setDefaultButton(ok); - - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(content, BorderLayout.CENTER); - getContentPane().add(buttons, BorderLayout.SOUTH); - - load(); - Dialogs.closeOnEscape(this); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - pack(); - setMinimumSize(new Dimension(getWidth(), getHeight())); - setLocationRelativeTo(owner); - } - - private JPanel buildFlags() { - JPanel grid = titledGrid("Ignore and Hide Defaults"); - int row = 1; - row = flagRow(grid, row, "Mute", "automute", "Automatically mute this person"); - row = flagRow(grid, row, "Ignore server/channel chat", "ignorePublicMessages", - "Ignore messages this person sends to the server or in channels"); - row = flagRow(grid, row, "Ignore private chat", "ignorePrivateMessages", "Ignore private chat by this person"); - row = flagRow(grid, row, "Ignore Pokes", "ignorePokes", "Ignore pokes this person sends you"); - row = flagRow(grid, row, "Hide avatar", "ignoreAvatar", "Do not download this person's avatar"); - row = flagRow(grid, row, "Hide away message", "ignoreAwayMessage", "Ignore this person's away messages"); - flagRow(grid, row, "Deny whisper", "ignoreWhisper", "This contact is always denied to whisper to you."); - return grid; - } - - private JPanel buildDisplays() { - JPanel grid = titledGrid("Nickname Display Defaults"); - Map groups = new EnumMap<>(ContactType.class); - for (ContactType t : COLUMNS) groups.put(t, new ButtonGroup()); - int row = 1; - for (NicknameDisplay display : NicknameDisplay.values()) { - GridBagConstraints c = cell(0, row); - c.anchor = GridBagConstraints.WEST; - grid.add(new JLabel(display.label()), c); - for (int i = 0; i < COLUMNS.length; i++) { - JRadioButton radio = new JRadioButton(); - radio.setToolTipText(display == NicknameDisplay.BOTH ? "Show both custom name and the nickname" - : display == NicknameDisplay.ONLY_CUSTOM ? "Show only custom name" : "Show only the nickname"); - groups.get(COLUMNS[i]).add(radio); - displays.get(COLUMNS[i]).put(display, radio); - grid.add(radio, cell(i + 1, row)); - } - row++; - } - return grid; - } - - /** A grid with the three contact types as column headings. */ - private JPanel titledGrid(String title) { - JPanel grid = new JPanel(new GridBagLayout()); - grid.setBorder(BorderFactory.createTitledBorder(title)); - grid.setAlignmentX(LEFT_ALIGNMENT); - String[] headings = {"Friends", "Blocked", "Neutral"}; - for (int i = 0; i < headings.length; i++) { - JLabel heading = new JLabel(headings[i], SwingConstants.CENTER); - heading.setFont(Theme.uiBold()); - GridBagConstraints c = cell(i + 1, 0); - c.ipadx = 12; - grid.add(heading, c); - } - GridBagConstraints line = cell(0, 100); - line.gridwidth = 4; - line.fill = GridBagConstraints.HORIZONTAL; - grid.add(new JSeparator(), line); - return grid; - } - - private int flagRow(JPanel grid, int row, String label, String key, String tooltip) { - GridBagConstraints c = cell(0, row); - c.anchor = GridBagConstraints.WEST; - c.weightx = 1; - grid.add(new JLabel(label), c); - for (int i = 0; i < COLUMNS.length; i++) { - JCheckBox box = new JCheckBox(); - box.setToolTipText(tooltip); - flags.get(COLUMNS[i]).put(key, box); - grid.add(box, cell(i + 1, row)); - } - return row + 1; - } - - private static GridBagConstraints cell(int x, int y) { - GridBagConstraints c = new GridBagConstraints(); - c.gridx = x; - c.gridy = y; - c.insets = UIScale.scale(new Insets(1, 6, 1, 6)); - c.anchor = GridBagConstraints.CENTER; - return c; - } - - // ---- model <-> fields ---- - - private void load() { - for (ContactType t : COLUMNS) { - ContactDefaults.Entry e = settings.contactDefaults.of(t); - Map boxes = flags.get(t); - boxes.get("automute").setSelected(e.automute); - boxes.get("ignorePublicMessages").setSelected(e.ignorePublicMessages); - boxes.get("ignorePrivateMessages").setSelected(e.ignorePrivateMessages); - boxes.get("ignorePokes").setSelected(e.ignorePokes); - boxes.get("ignoreAvatar").setSelected(e.ignoreAvatar); - boxes.get("ignoreAwayMessage").setSelected(e.ignoreAwayMessage); - boxes.get("ignoreWhisper").setSelected(e.ignoreWhisper); - displays.get(t).get(e.nicknameDisplay).setSelected(true); - } - } - - private void apply() { - for (ContactType t : COLUMNS) { - ContactDefaults.Entry e = settings.contactDefaults.of(t); - Map boxes = flags.get(t); - e.automute = boxes.get("automute").isSelected(); - e.ignorePublicMessages = boxes.get("ignorePublicMessages").isSelected(); - e.ignorePrivateMessages = boxes.get("ignorePrivateMessages").isSelected(); - e.ignorePokes = boxes.get("ignorePokes").isSelected(); - e.ignoreAvatar = boxes.get("ignoreAvatar").isSelected(); - e.ignoreAwayMessage = boxes.get("ignoreAwayMessage").isSelected(); - e.ignoreWhisper = boxes.get("ignoreWhisper").isSelected(); - for (Map.Entry radio : displays.get(t).entrySet()) { - if (radio.getValue().isSelected()) e.nicknameDisplay = radio.getKey(); - } - } - settings.save(); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ContactsDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ContactsDialog.java deleted file mode 100644 index 3a36f9e..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ContactsDialog.java +++ /dev/null @@ -1,569 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.config.Settings; -import com.ts3client.contacts.Contact; -import com.ts3client.contacts.ContactStore; -import com.ts3client.contacts.ContactType; -import com.ts3client.contacts.NicknameDisplay; -import com.ts3client.teamspeak.TeamSpeakSettingsDb; -import com.ts3client.text.TsLink; - -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.ButtonGroup; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.JRadioButton; -import javax.swing.JScrollPane; -import javax.swing.JTextField; -import javax.swing.JTree; -import javax.swing.KeyStroke; -import javax.swing.SwingUtilities; -import javax.swing.TransferHandler; -import javax.swing.border.Border; -import javax.swing.plaf.basic.BasicTreeUI; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeCellRenderer; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.Frame; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.Toolkit; -import java.awt.datatransfer.DataFlavor; -import java.awt.datatransfer.StringSelection; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.io.File; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.function.Consumer; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * The contact list window: the contacts grouped as friends, blocked and neutral on - * the left, and on the right all of the selected one's settings — TeamSpeak's - * General / Display / Ignore / Whisper pages, in one column rather than as tabs - * since each holds only a few options. Every edit is stored as it is made. - * - *

    Clients can be dragged in from the server tree — the drag carries the - * client's TS3 link, which names its unique id. - */ -final class ContactsDialog extends JDialog { - - private static final DateTimeFormatter SEEN = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); - private static final DateTimeFormatter SEEN_DAY = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - private static final Pattern CLIENT_LINK = Pattern.compile("client://[^\\]\\s]+"); - - private final ContactStore contacts; - private final Settings settings; - private final ContactStore.Listener storeListener = () -> SwingUtilities.invokeLater(this::reload); - - private final DefaultMutableTreeNode root = new DefaultMutableTreeNode(); - private final DefaultTreeModel treeModel = new DefaultTreeModel(root); - private final JTree tree = new JTree(treeModel); - private final DefaultMutableTreeNode friends = new DefaultMutableTreeNode("Friends"); - private final DefaultMutableTreeNode blocked = new DefaultMutableTreeNode("Blocked"); - private final DefaultMutableTreeNode neutral = new DefaultMutableTreeNode("Neutral"); - - private final JTextField nicknameField = new JTextField(18); - private final JButton nicknameApply = new JButton("Apply"); - private final JRadioButton neutralRadio = new JRadioButton("Neutral"); - private final JRadioButton blockedRadio = new JRadioButton("Blocked"); - private final JRadioButton friendRadio = new JRadioButton("Friend"); - private final JTextField phoneticField = new JTextField(18); - private final JLabel lastSeenLabel = new JLabel(" "); - private final JRadioButton bothRadio = new JRadioButton(NicknameDisplay.BOTH.label()); - private final JRadioButton onlyCustomRadio = new JRadioButton(NicknameDisplay.ONLY_CUSTOM.label()); - private final JRadioButton onlyNicknameRadio = new JRadioButton(NicknameDisplay.ONLY_NICKNAME.label()); - private final JCheckBox automute = new JCheckBox("Mute"); - private final JCheckBox ignorePublic = new JCheckBox("Ignore server/channel chat"); - private final JCheckBox ignorePrivate = new JCheckBox("Ignore private chat"); - private final JCheckBox ignorePokes = new JCheckBox("Ignore Pokes"); - private final JCheckBox ignoreAvatar = new JCheckBox("Hide avatar"); - private final JCheckBox ignoreAway = new JCheckBox("Hide away message"); - private final JCheckBox denyWhisper = new JCheckBox("Deny whisper"); - private final JPanel details = new JPanel(new BorderLayout(0, UIScale.scale(8))); - - /** Set while the fields are being filled from a contact, so that does not count as an edit. */ - private boolean filling; - - ContactsDialog(Frame owner, ContactStore contacts, Settings settings) { - super(owner, "Contacts", false); - this.contacts = contacts; - this.settings = settings; - - buildTree(); - JPanel left = new JPanel(new BorderLayout(0, UIScale.scale(4))); - left.setBorder(new ScaledEmptyBorder(8, 8, 8, 4)); - JLabel hint = new JLabel("Drag & Drop users here"); - hint.setForeground(Theme.chatSystem()); - left.add(hint, BorderLayout.NORTH); - JScrollPane scroll = new JScrollPane(tree); - scroll.setPreferredSize(UIScale.scale(new Dimension(300, 340))); - left.add(scroll, BorderLayout.CENTER); - - details.setBorder(new ScaledEmptyBorder(8, 4, 8, 8)); - details.add(buildNicknameRow(), BorderLayout.NORTH); - details.add(buildOptions(), BorderLayout.CENTER); - - JPanel buttons = new JPanel(new BorderLayout()); - buttons.setBorder(new ScaledEmptyBorder(0, 8, 8, 8)); - JPanel leftButtons = new JPanel(new FlowLayout(FlowLayout.LEFT, UIScale.scale(6), 0)); - JButton defaults = new JButton("Set Defaults"); - defaults.setToolTipText("Set default display, ignore and hide options"); - defaults.addActionListener(e -> new ContactDefaultsDialog(this, settings).setVisible(true)); - leftButtons.add(defaults); - if (TeamSpeakSettingsDb.locate() != null) { - JButton importButton = new JButton("Import from TeamSpeak 3…"); - importButton.setToolTipText("Add the contacts of the TeamSpeak 3 client installed on this computer"); - importButton.addActionListener(e -> importFromTeamSpeak()); - leftButtons.add(importButton); - } - buttons.add(leftButtons, BorderLayout.WEST); - JButton close = new JButton("Close"); - close.addActionListener(e -> dispose()); - JPanel rightButtons = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0)); - rightButtons.add(close); - buttons.add(rightButtons, BorderLayout.EAST); - - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(left, BorderLayout.WEST); - getContentPane().add(details, BorderLayout.CENTER); - getContentPane().add(buttons, BorderLayout.SOUTH); - - contacts.addListener(storeListener); - addWindowListener(new java.awt.event.WindowAdapter() { - @Override - public void windowClosed(java.awt.event.WindowEvent e) { - contacts.removeListener(storeListener); - } - }); - - reload(); - Dialogs.closeOnEscape(this); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - pack(); - // Only the list scrolls, so the window never gets shorter than the options column. - setMinimumSize(new Dimension(UIScale.scale(620), getHeight())); - setLocationRelativeTo(owner); - } - - // ---- tree ---- - - private void buildTree() { - root.add(friends); - root.add(blocked); - root.add(neutral); - tree.setRootVisible(false); - tree.setShowsRootHandles(true); - // Half the usual nesting, so long names and their dates fit in the narrow list. - if (tree.getUI() instanceof BasicTreeUI) { - BasicTreeUI ui = (BasicTreeUI) tree.getUI(); - ui.setLeftChildIndent(UIScale.scale(4)); - ui.setRightChildIndent(UIScale.scale(5)); - } - tree.setRowHeight(UIScale.scale(20)); - tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); - tree.setCellRenderer(new ContactRenderer()); - tree.addTreeSelectionListener(e -> showSelected()); - tree.addMouseListener(new MouseAdapter() { - @Override - public void mousePressed(MouseEvent e) { - maybePopup(e); - } - - @Override - public void mouseReleased(MouseEvent e) { - maybePopup(e); - } - }); - tree.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "remove"); - tree.getActionMap().put("remove", new javax.swing.AbstractAction() { - @Override - public void actionPerformed(java.awt.event.ActionEvent e) { - removeSelected(); - } - }); - tree.setTransferHandler(new DropHandler()); - } - - /** Re-lists the contacts, keeping the selection on the same unique id. */ - private void reload() { - String selectedUid = selectedContact() == null ? null : selectedContact().uniqueId; - for (DefaultMutableTreeNode group : List.of(friends, blocked, neutral)) group.removeAllChildren(); - List sorted = new ArrayList<>(contacts.all()); - sorted.sort(Comparator.comparing((Contact c) -> c.nickname, String.CASE_INSENSITIVE_ORDER) - .thenComparing(c -> c.uniqueId)); - for (Contact c : sorted) groupOf(c.type).add(new DefaultMutableTreeNode(c)); - treeModel.reload(); - for (int i = 0; i < tree.getRowCount(); i++) tree.expandRow(i); - if (selectedUid != null) select(selectedUid); - else showSelected(); - } - - private DefaultMutableTreeNode groupOf(ContactType type) { - switch (type) { - case FRIEND: - return friends; - case BLOCKED: - return blocked; - default: - return neutral; - } - } - - /** Selects the contact with a unique id, if it is on the list. */ - void select(String uniqueId) { - java.util.Enumeration nodes = root.depthFirstEnumeration(); - while (nodes.hasMoreElements()) { - DefaultMutableTreeNode n = (DefaultMutableTreeNode) nodes.nextElement(); - if (n.getUserObject() instanceof Contact && ((Contact) n.getUserObject()).uniqueId.equals(uniqueId)) { - TreePath path = new TreePath(n.getPath()); - tree.setSelectionPath(path); - tree.scrollPathToVisible(path); - return; - } - } - } - - private Contact selectedContact() { - TreePath path = tree.getSelectionPath(); - if (path == null) return null; - Object obj = ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); - return obj instanceof Contact ? (Contact) obj : null; - } - - private void maybePopup(MouseEvent e) { - if (!e.isPopupTrigger()) return; - TreePath path = tree.getPathForLocation(e.getX(), e.getY()); - if (path == null) return; - tree.setSelectionPath(path); - Contact contact = selectedContact(); - if (contact == null) return; - - JPopupMenu menu = new JPopupMenu(); - for (ContactType type : new ContactType[]{ContactType.FRIEND, ContactType.BLOCKED, ContactType.NEUTRAL}) { - JMenuItem item = new javax.swing.JRadioButtonMenuItem(type.label(), type == contact.type); - item.addActionListener(a -> edit(c -> c.type = type)); - menu.add(item); - } - menu.addSeparator(); - JMenuItem remove = new JMenuItem("Remove", Icons.of("DELETE")); - remove.addActionListener(a -> removeSelected()); - menu.add(remove); - JMenuItem applyDefaults = new JMenuItem("Apply Defaults"); - applyDefaults.addActionListener(a -> edit(c -> c.applyDefaults(settings.contactDefaults.of(c.type)))); - menu.add(applyDefaults); - menu.addSeparator(); - JMenuItem copyUid = new JMenuItem("Copy Unique ID to Clipboard", Icons.of("COPY")); - copyUid.addActionListener(a -> Toolkit.getDefaultToolkit().getSystemClipboard() - .setContents(new StringSelection(contact.uniqueId), null)); - menu.add(copyUid); - menu.show(tree, e.getX(), e.getY()); - } - - private void removeSelected() { - Contact contact = selectedContact(); - if (contact == null) return; - int answer = JOptionPane.showConfirmDialog(this, - "Do you really want to delete contact " + contact.nickname + "?", "Remove Contact", - JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); - if (answer == JOptionPane.YES_OPTION) contacts.remove(contact.uniqueId); - } - - private void importFromTeamSpeak() { - File db = TeamSpeakSettingsDb.locate(); - if (db == null) return; - try { - List imported = TeamSpeakSettingsDb.readContacts(db); - int added = contacts.merge(imported); - JOptionPane.showMessageDialog(this, imported.size() + " contact(s) read from " + db - + "\n" + added + " new, " + (imported.size() - added) + " updated.", - "Import from TeamSpeak 3", JOptionPane.INFORMATION_MESSAGE); - } catch (Exception e) { - JOptionPane.showMessageDialog(this, "Could not read " + db + ":\n" + e.getMessage(), - "Import from TeamSpeak 3", JOptionPane.ERROR_MESSAGE); - } - } - - // ---- details ---- - - /** The names, each label on its own line above its field. */ - private JComponent buildNicknameRow() { - JPanel row = new JPanel(new GridBagLayout()); - GridBagConstraints c = new GridBagConstraints(); - c.insets = UIScale.scale(new Insets(2, 2, 2, 2)); - c.anchor = GridBagConstraints.WEST; - c.gridx = 0; - c.gridy = 0; - c.gridwidth = 2; - row.add(new JLabel("Custom Nickname:"), c); - - c.gridy = 1; - c.gridwidth = 1; - c.weightx = 1; - c.fill = GridBagConstraints.HORIZONTAL; - nicknameField.setToolTipText("Enter custom nickname"); - nicknameField.addActionListener(e -> applyNickname()); - row.add(nicknameField, c); - c.gridx = 1; - c.weightx = 0; - c.fill = GridBagConstraints.NONE; - nicknameApply.setToolTipText("Apply nickname change"); - nicknameApply.addActionListener(e -> applyNickname()); - row.add(nicknameApply, c); - - c.gridx = 0; - c.gridy = 2; - c.gridwidth = 2; - row.add(new JLabel("Phonetic Nickname:"), c); - c.gridy = 3; - c.weightx = 1; - c.fill = GridBagConstraints.HORIZONTAL; - row.add(phoneticField, c); - c.gridy = 4; - row.add(lastSeenLabel, c); - return row; - } - - /** Every option at once, one short group under the other. */ - private JComponent buildOptions() { - JComponent contact = group("Contact", radioGroup(neutralRadio, blockedRadio, friendRadio)); - neutralRadio.setToolTipText("Mark as neutral"); - blockedRadio.setToolTipText("Mark as blocked"); - friendRadio.setToolTipText("Mark as friend"); - phoneticField.setToolTipText("Client nickname written as phonemes (optional)"); - neutralRadio.addActionListener(e -> edit(c -> c.type = ContactType.NEUTRAL)); - blockedRadio.addActionListener(e -> edit(c -> c.type = ContactType.BLOCKED)); - friendRadio.addActionListener(e -> edit(c -> c.type = ContactType.FRIEND)); - phoneticField.addActionListener(e -> applyPhonetic()); - phoneticField.addFocusListener(new java.awt.event.FocusAdapter() { - @Override - public void focusLost(java.awt.event.FocusEvent e) { - applyPhonetic(); - } - }); - - JComponent display = group("Display", radioGroup(bothRadio, onlyCustomRadio, onlyNicknameRadio)); - bothRadio.setToolTipText("Show custom name and nickname"); - onlyCustomRadio.setToolTipText("Show only custom name"); - onlyNicknameRadio.setToolTipText("Show nickname only"); - bothRadio.addActionListener(e -> edit(c -> c.nicknameDisplay = NicknameDisplay.BOTH)); - onlyCustomRadio.addActionListener(e -> edit(c -> c.nicknameDisplay = NicknameDisplay.ONLY_CUSTOM)); - onlyNicknameRadio.addActionListener(e -> edit(c -> c.nicknameDisplay = NicknameDisplay.ONLY_NICKNAME)); - - JComponent ignore = group("Ignore", automute, ignorePublic, ignorePrivate, ignorePokes, ignoreAvatar, ignoreAway, - denyWhisper); - automute.setToolTipText("Automatically mute this person"); - ignorePublic.setToolTipText("Ignore messages this person sends to the server or in channels"); - ignorePrivate.setToolTipText("Ignore private chat by this person"); - ignorePokes.setToolTipText("Ignore pokes this person sends you"); - ignoreAvatar.setToolTipText("Do not download this person's avatar"); - ignoreAway.setToolTipText("Ignore this person's away messages"); - automute.addActionListener(e -> edit(c -> c.automute = automute.isSelected())); - ignorePublic.addActionListener(e -> edit(c -> c.ignorePublicMessages = ignorePublic.isSelected())); - ignorePrivate.addActionListener(e -> edit(c -> c.ignorePrivateMessages = ignorePrivate.isSelected())); - ignorePokes.addActionListener(e -> edit(c -> c.ignorePokes = ignorePokes.isSelected())); - ignoreAvatar.addActionListener(e -> edit(c -> c.ignoreAvatar = ignoreAvatar.isSelected())); - ignoreAway.addActionListener(e -> edit(c -> c.ignoreAwayMessage = ignoreAway.isSelected())); - - denyWhisper.setToolTipText("This contact is always denied to whisper to you"); - denyWhisper.addActionListener(e -> edit(c -> c.whisperAllowed = !denyWhisper.isSelected())); - return column(contact, display, ignore); - } - - private static JPanel column(JComponent... groups) { - JPanel p = new JPanel(); - p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); - for (JComponent g : groups) { - g.setAlignmentX(Component.LEFT_ALIGNMENT); - g.setMaximumSize(new Dimension(Integer.MAX_VALUE, g.getPreferredSize().height)); - p.add(g); - p.add(Box.createVerticalStrut(UIScale.scale(6))); - } - p.add(Box.createVerticalGlue()); - return p; - } - - private static JPanel group(String title, JComponent... rows) { - JPanel p = new JPanel(); - p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); - p.setBorder(BorderFactory.createTitledBorder(title)); - for (JComponent row : rows) { - row.setAlignmentX(Component.LEFT_ALIGNMENT); - p.add(row); - } - return p; - } - - private static JPanel radioGroup(JRadioButton... buttons) { - ButtonGroup group = new ButtonGroup(); - JPanel p = new JPanel(); - p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); - for (JRadioButton b : buttons) { - group.add(b); - b.setAlignmentX(Component.LEFT_ALIGNMENT); - p.add(b); - } - return p; - } - - /** Fills the right-hand side from the selected contact, or greys it out. */ - private void showSelected() { - Contact c = selectedContact(); - filling = true; - try { - setDetailsEnabled(details, c != null); - if (c == null) { - nicknameField.setText(""); - phoneticField.setText(""); - lastSeenLabel.setText(" "); - return; - } - nicknameField.setText(c.nickname); - phoneticField.setText(c.phoneticNickname); - lastSeenLabel.setText(lastSeen(c)); - (c.type == ContactType.FRIEND ? friendRadio : c.type == ContactType.BLOCKED ? blockedRadio : neutralRadio) - .setSelected(true); - (c.nicknameDisplay == NicknameDisplay.ONLY_CUSTOM ? onlyCustomRadio - : c.nicknameDisplay == NicknameDisplay.ONLY_NICKNAME ? onlyNicknameRadio : bothRadio) - .setSelected(true); - automute.setSelected(c.automute); - ignorePublic.setSelected(c.ignorePublicMessages); - ignorePrivate.setSelected(c.ignorePrivateMessages); - ignorePokes.setSelected(c.ignorePokes); - ignoreAvatar.setSelected(c.ignoreAvatar); - ignoreAway.setSelected(c.ignoreAwayMessage); - denyWhisper.setSelected(!c.whisperAllowed); - } finally { - filling = false; - } - } - - private static String lastSeen(Contact c) { - if (c.lastSeen == null) return "Never seen"; - String where = c.lastSeenServerName.isEmpty() ? c.lastSeenServerAddress : c.lastSeenServerName; - return "Last seen " + SEEN.format(c.lastSeen) + (where.isEmpty() ? "" : " on " + where); - } - - private static void setDetailsEnabled(Component component, boolean enabled) { - component.setEnabled(enabled); - if (component instanceof java.awt.Container) { - for (Component child : ((java.awt.Container) component).getComponents()) { - setDetailsEnabled(child, enabled); - } - } - } - - /** Changes the selected contact and stores it; the store's change notice re-lists the tree. */ - private void edit(Consumer change) { - if (filling) return; - Contact c = selectedContact(); - if (c == null) return; - change.accept(c); - contacts.put(c); - } - - private void applyNickname() { - String name = nicknameField.getText().trim(); - Contact c = selectedContact(); - if (c == null || name.isEmpty() || name.equals(c.nickname)) return; - edit(contact -> contact.nickname = name); - } - - private void applyPhonetic() { - String name = phoneticField.getText().trim(); - Contact c = selectedContact(); - if (c == null || name.equals(c.phoneticNickname)) return; - edit(contact -> contact.phoneticNickname = name); - } - - // ---- drop target ---- - - /** Accepts clients dragged out of a server tree, whose transfer text is their TS3 link. */ - private final class DropHandler extends TransferHandler { - @Override - public boolean canImport(TransferSupport support) { - return support.isDataFlavorSupported(DataFlavor.stringFlavor); - } - - @Override - public boolean importData(TransferSupport support) { - String text; - try { - text = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor); - } catch (Exception e) { - return false; - } - boolean added = false; - Matcher m = CLIENT_LINK.matcher(text); - while (m.find()) { - TsLink.Ref ref = TsLink.parse(m.group()); - if (ref == null || !ref.client || ref.uniqueId.isEmpty()) continue; - if (contacts.find(ref.uniqueId) == null) { - contacts.add(ref.uniqueId, ref.name, ContactType.NEUTRAL, settings.contactDefaults); - } - select(ref.uniqueId); - added = true; - } - return added; - } - } - - // ---- rendering ---- - - private static final class ContactRenderer extends DefaultTreeCellRenderer { - private final Border margin = getBorder(); - /** Keeps a group's name clear of its expand arrow, which the tight nesting brings close. */ - private final Border groupMargin = BorderFactory.createCompoundBorder(margin, new ScaledEmptyBorder(0, 4, 0, 0)); - - @Override - public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, - boolean leaf, int row, boolean hasFocus) { - super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); - Object obj = ((DefaultMutableTreeNode) value).getUserObject(); - if (obj instanceof Contact) { - Contact c = (Contact) obj; - setText("" + esc(c.nickname) + "  " + (c.lastSeen == null ? "Never" : SEEN_DAY.format(c.lastSeen)) + ""); - setFont(Theme.uiFont()); - setBorder(margin); - } else { - setText(String.valueOf(obj)); - setFont(Theme.uiBold()); - setBorder(groupMargin); - } - setIcon(null); - return this; - } - - private static String esc(String s) { - return s.replace("&", "&").replace("<", "<").replace(">", ">"); - } - - private static String hex(java.awt.Color c) { - return String.format("#%02x%02x%02x", c.getRed(), c.getGreen(), c.getBlue()); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ContactsPanel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ContactsPanel.java deleted file mode 100644 index f0d2175..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ContactsPanel.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.config.Settings; - -import javax.swing.DefaultListCellRenderer; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.SwingUtilities; -import java.awt.Component; -import java.awt.FlowLayout; -import java.awt.GridBagConstraints; - -/** - * Options page for the contact list: whether friends and blocked clients are - * coloured in the server tree, whose whispers get through (TeamSpeak's whisper - * options), and the defaults a new contact starts with. - */ -final class ContactsPanel extends FormPanel { - - private final Settings settings; - private final JCheckBox colorContacts = new JCheckBox("Colour friends and blocked clients in the server tree"); - private final JComboBox whisperPolicy = new JComboBox<>(Settings.WhisperPolicy.values()); - - ContactsPanel(Settings settings) { - this.settings = settings; - GridBagConstraints c = gbc(); - - colorContacts.setSelected(settings.colorContacts); - colorContacts.setToolTipText("Friends in green and blocked clients in red, as the TeamSpeak client shows them"); - - whisperPolicy.setSelectedItem(settings.whisperPolicy); - whisperPolicy.setRenderer(new DefaultListCellRenderer() { - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, - boolean selected, boolean focus) { - super.getListCellRendererComponent(list, value, index, selected, focus); - if (value instanceof Settings.WhisperPolicy) setText(((Settings.WhisperPolicy) value).label()); - return this; - } - }); - whisperPolicy.setToolTipText("Use individual settings in contacts, else allow: a client not on your " - + "contact list may whisper to you.
    Use individual settings in contacts, else deny: only " - + "contacts marked \"Allow whisper\" may.
    Nobody: individual contact settings are ignored."); - - JButton defaults = new JButton("Contact defaults…"); - defaults.setToolTipText("Configure default settings when adding a client to the Contact Manager"); - defaults.addActionListener(e -> { - java.awt.Window owner = SwingUtilities.getWindowAncestor(this); - new ContactDefaultsDialog(owner instanceof JDialog ? (JDialog) owner : null, settings).setVisible(true); - }); - JPanel defaultsRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); - defaultsRow.add(defaults); - - int row = 0; - addSection(this, c, row++, "Server Tree"); - addWide(this, c, row++, colorContacts); - addSection(this, c, row++, "Whispers"); - addRow(this, c, row++, new JLabel("Allow whispers from:"), whisperPolicy); - addSection(this, c, row++, "New Contacts"); - addWide(this, c, row++, defaultsRow); - addFiller(this, c, row); - } - - /** Copies the page into the settings; the caller saves them. */ - void apply() { - settings.colorContacts = colorContacts.isSelected(); - settings.whisperPolicy = (Settings.WhisperPolicy) whisperPolicy.getSelectedItem(); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/CountryFlagIcons.java b/ts3-client/swing/src/main/java/com/ts3client/ui/CountryFlagIcons.java deleted file mode 100644 index c111a94..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/CountryFlagIcons.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.gfx.CountryFlags; - -import javax.swing.ImageIcon; -import java.awt.Image; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; - -/** TeamSpeak's country flags as Swing icons, at their own 16×11 scaled with the interface. */ -final class CountryFlagIcons { - - private static final int WIDTH = 16; - private static final int HEIGHT = 11; - private static final Map> ICONS = new ConcurrentHashMap<>(); - - private CountryFlagIcons() { - } - - /** @return the flag, or {@code null} for an unknown or empty code */ - static ImageIcon of(String code) { - if (code == null || code.isEmpty()) return null; - return ICONS.computeIfAbsent(code, CountryFlagIcons::load).orElse(null); - } - - private static Optional load(String code) { - byte[] png = CountryFlags.png(code); - if (png == null) return Optional.empty(); - ImageIcon icon = new ImageIcon(png); - if (icon.getIconWidth() <= 0) return Optional.empty(); - int width = UIScale.scale(WIDTH); - int height = UIScale.scale(HEIGHT); - if (icon.getIconWidth() != width || icon.getIconHeight() != height) { - icon = new ImageIcon(icon.getImage().getScaledInstance(width, height, Image.SCALE_SMOOTH)); - } - return Optional.of(icon); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/DescriptionEditorDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/DescriptionEditorDialog.java deleted file mode 100644 index 16ab826..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/DescriptionEditorDialog.java +++ /dev/null @@ -1,172 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.text.BBCode; - -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JColorChooser; -import javax.swing.JDialog; -import javax.swing.JEditorPane; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.JToggleButton; -import javax.swing.JToolBar; -import java.awt.BorderLayout; -import java.awt.CardLayout; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Window; - -/** - * The description editor TeamSpeak tears off the channel dialog: the raw BBCode plus - * the handful of formatting buttons it offers (bold, italic, underline, colour) and a - * preview that renders the text the way the info panel will. - * - *

    Formatting works on the selection, wrapping it in the tag pair; with nothing - * selected the pair is inserted and the caret placed between the two halves, so typing - * continues inside it. - */ -final class DescriptionEditorDialog extends JDialog { - - private static final String EDIT_CARD = "edit"; - private static final String PREVIEW_CARD = "preview"; - - private final JTextArea area = new JTextArea(); - private final JEditorPane preview = new JEditorPane("text/html", ""); - private final CardLayout cards = new CardLayout(); - private final JPanel body = new JPanel(cards); - private final JToggleButton previewButton = new JToggleButton("Preview"); - private boolean accepted; - - DescriptionEditorDialog(Window owner, String description) { - super(owner, "Channel Description", ModalityType.APPLICATION_MODAL); - area.setText(description); - area.setLineWrap(true); - area.setWrapStyleWord(true); - area.setFont(new Font(Font.MONOSPACED, Font.PLAIN, UIScale.scale(12))); - area.setCaretPosition(0); - - preview.setEditable(false); - preview.setBackground(Theme.chatBg()); - preview.setBorder(new ScaledEmptyBorder(6, 8, 6, 8)); - - body.add(new JScrollPane(area), EDIT_CARD); - body.add(new JScrollPane(preview), PREVIEW_CARD); - - JLabel hint = new JLabel("Press Button to \"Preview\" the changes in channel info."); - hint.setForeground(Theme.chatSystem()); - hint.setBorder(new ScaledEmptyBorder(4, 6, 0, 6)); - - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(buildToolbar(), BorderLayout.NORTH); - getContentPane().add(body, BorderLayout.CENTER); - JPanel south = new JPanel(new BorderLayout()); - south.add(hint, BorderLayout.NORTH); - south.add(buildButtons(), BorderLayout.SOUTH); - getContentPane().add(south, BorderLayout.SOUTH); - - Dialogs.closeOnEscape(this); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - setSize(UIScale.scale(new Dimension(520, 380))); - setMinimumSize(UIScale.scale(new Dimension(360, 260))); - setLocationRelativeTo(owner); - } - - /** @return whether the user confirmed; {@link #getDescription()} then holds the new text */ - boolean isAccepted() { - return accepted; - } - - String getDescription() { - return area.getText(); - } - - private JToolBar buildToolbar() { - JToolBar bar = new JToolBar(); - bar.setFloatable(false); - bar.add(tagButton("B", "Bold", Font.BOLD, "[b]", "[/b]")); - bar.add(tagButton("I", "Italic", Font.ITALIC, "[i]", "[/i]")); - JButton underline = tagButton("U", "Underline", Font.PLAIN, "[u]", "[/u]"); - bar.add(underline); - JButton color = new JButton("Color"); - color.setToolTipText("Color"); - color.addActionListener(a -> chooseColor()); - bar.add(square(color)); - bar.add(Box.createHorizontalGlue()); - previewButton.setToolTipText("Show the description as the info panel renders it"); - previewButton.addActionListener(a -> showPreview(previewButton.isSelected())); - previewButton.setMaximumSize(previewButton.getPreferredSize()); - bar.add(previewButton); - return bar; - } - - private JPanel buildButtons() { - JButton ok = new JButton("OK"); - JButton cancel = new JButton("Cancel"); - ok.addActionListener(a -> { - accepted = true; - dispose(); - }); - cancel.addActionListener(a -> dispose()); - JPanel panel = new JPanel(new BorderLayout()); - JPanel right = new JPanel(); - right.add(ok); - right.add(cancel); - panel.add(right, BorderLayout.EAST); - getRootPane().setDefaultButton(ok); - return panel; - } - - private JButton tagButton(String text, String tip, int style, String open, String close) { - JButton button = new JButton(text); - button.setToolTipText(tip); - button.setFont(button.getFont().deriveFont(style)); - button.addActionListener(a -> wrapSelection(open, close)); - return square(button); - } - - /** - * Pins a toolbar button to its natural size: the tool bar lays its children out along a - * box, which would otherwise let one of them soak up all the free width. - */ - private static JButton square(JButton button) { - Dimension size = new Dimension(Math.max(UIScale.scale(28), button.getPreferredSize().width), - button.getPreferredSize().height); - button.setPreferredSize(size); - button.setMaximumSize(size); - return button; - } - - private void chooseColor() { - Color chosen = JColorChooser.showDialog(this, "Color", Color.BLACK); - if (chosen == null) return; - wrapSelection(String.format("[color=#%02x%02x%02x]", - chosen.getRed(), chosen.getGreen(), chosen.getBlue()), "[/color]"); - } - - /** Wraps the selection (or the caret) in a BBCode tag pair and returns focus to the text. */ - private void wrapSelection(String open, String close) { - if (previewButton.isSelected()) showPreview(false); - int start = area.getSelectionStart(); - int end = area.getSelectionEnd(); - String selected = area.getSelectedText(); - area.replaceRange(open + (selected == null ? "" : selected) + close, start, end); - area.setCaretPosition(start + open.length() + (selected == null ? 0 : selected.length())); - area.requestFocusInWindow(); - } - - private void showPreview(boolean on) { - previewButton.setSelected(on); - if (on) { - preview.setText("" - + BBCode.toHtml(area.getText()) + ""); - preview.setCaretPosition(0); - } - cards.show(body, on ? PREVIEW_CARD : EDIT_CARD); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/DescriptionPictures.java b/ts3-client/swing/src/main/java/com/ts3client/ui/DescriptionPictures.java deleted file mode 100644 index 6683c36..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/DescriptionPictures.java +++ /dev/null @@ -1,166 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.config.Settings; -import com.ts3client.myts.ChatAttachment; -import com.ts3client.net.PictureDownloads; -import com.ts3client.text.BBCode; -import com.ts3client.text.ChatHtml; - -import javax.imageio.ImageIO; -import javax.imageio.ImageReader; -import javax.imageio.stream.ImageInputStream; -import java.awt.Dimension; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Shows the pictures of description HTML as the info views can: from the downloads' files, - * narrowed to fit, with a loading icon while one comes. With pictures turned off, or when one - * cannot be had, it is a link to the picture behind a picture icon instead. - */ -final class DescriptionPictures { - - /** A picture, and the links it may sit in. */ - private static final Pattern TAG = Pattern.compile( - "|]*href=\"([^\"]*)\"[^>]*>|", Pattern.CASE_INSENSITIVE); - private static final int ICON = 16; - - private final PictureDownloads downloads; - private final Settings settings; - private final Map sizes = new ConcurrentHashMap<>(); - - DescriptionPictures(PictureDownloads downloads, Settings settings) { - this.downloads = downloads; - this.settings = settings; - } - - static boolean hasPictures(String html) { - return html.contains(" urls(String html) { - List urls = new ArrayList<>(); - Matcher m = TAG.matcher(html); - while (m.find()) { - if (m.group(1) != null) urls.add(unescape(m.group(1))); - } - return urls; - } - - /** - * How the pictures stand, one letter each: it changes when one of them comes or fails, - * and asks for those not on their way yet. - */ - String state(List urls) { - if (!settings.descriptionPictures) return ""; - StringBuilder state = new StringBuilder(urls.size()); - for (String url : urls) { - state.append(downloads.get(url) != null ? 'y' : downloads.failed(url) ? 'n' : '-'); - } - return state.toString(); - } - - private String picture(String url, String anchor, String href, int maxWidth, int maxHeight) { - if (!settings.descriptionPictures) return link("ICONVIEWER", url, anchor, href); - File file = downloads.get(url); - if (file == null) { - return downloads.failed(url) ? link("BROKEN_IMAGE", url, anchor, href) : icon("LOADING_IMAGE"); - } - Dimension size = sizes.computeIfAbsent(file, DescriptionPictures::read); - if (size.width <= 0 || size.height <= 0) return link("BROKEN_IMAGE", url, anchor, href); - int width = Math.min(UIScale.scale(size.width), Math.max(1, maxWidth)); - int height = (int) ((long) size.height * width / size.width); - if (height > maxHeight) { - height = Math.max(1, maxHeight); - width = Math.max(1, (int) ((long) size.width * height / size.height)); - } - // Swing frames a picture inside a link unless told not to. - return ""; - } - - /** - * The picture's address as a link behind {@code iconKey}, shortened: Swing never breaks a - * long one, so it would widen the view past its edge; a file shared in chat goes by its - * name. Inside another link, that link is closed around it and shown after it, so it is - * not lost with the picture that carried it. - */ - private static String link(String iconKey, String url, String anchor, String href) { - ChatAttachment.Ref attachment = ChatAttachment.Ref.parse(url); - String label = attachment != null ? attachment.fileName() : BBCode.shortAddress(url); - String linkClass = attachment != null ? ChatHtml.ATTACHMENT_CLASS : BBCode.linkClass(url); - // A link to the picture itself already is the link this would be. - if (anchor != null && href.equals(url)) return icon(iconKey) + BBCode.escape(label); - String own = icon(iconKey) + "" - + BBCode.escape(label) + ""; - if (anchor == null) return own; - return "" + own + " " + anchor + BBCode.escape(href) + "" + anchor; - } - - private static String icon(String key) { - int size = UIScale.scale(ICON); - File file = IconFiles.of(key, size); - if (file == null) return ""; - return " "; - } - - /** The picture's size in pixels, read from its header; zero when it is no picture Swing can show. */ - private static Dimension read(File file) { - try (ImageInputStream in = ImageIO.createImageInputStream(file)) { - Iterator readers = in == null ? null : ImageIO.getImageReaders(in); - if (readers == null || !readers.hasNext()) return new Dimension(); - ImageReader reader = readers.next(); - try { - reader.setInput(in); - return new Dimension(reader.getWidth(0), reader.getHeight(0)); - } finally { - reader.dispose(); - } - } catch (IOException e) { - return new Dimension(); - } - } - - private static String unescape(String s) { - return s.replace("<", "<").replace(">", ">").replace(""", "\"").replace("&", "&"); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/DesignPanel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/DesignPanel.java deleted file mode 100644 index 67a8c54..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/DesignPanel.java +++ /dev/null @@ -1,282 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.config.Settings; -import com.ts3client.gfx.IconPack; - -import javax.swing.DefaultListCellRenderer; -import javax.swing.DefaultListModel; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JFileChooser; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextField; -import javax.swing.SwingConstants; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.io.File; -import java.util.Arrays; - -/** - * Options page for how the client looks: the light or dark look-and-feel, the interface - * scale, the channel tree's flags and row colours, and the icon pack the user interface is drawn with — where to look for more of - * them, and a viewer showing everything the active pack contains. - * - *

    Theme and pack apply right away so the change can be seen in the window behind the - * dialog; cancelling puts the previous ones back. The scale is only read at startup. - */ -final class DesignPanel extends JPanel { - - /** Size of the tiles in the icon viewer. */ - private static final int PREVIEW_SIZE = 32; - private static final int TILE = 44; - - /** Stands for "no pack": the icons the client draws itself. */ - private static final String BUILT_IN = "Plain (drawn by the client)"; - - /** The scale factors offered besides following the desktop (0). */ - private static final double[] SCALES = {0, 1, 1.25, 1.5, 1.75, 2, 2.5, 3}; - - private final Settings settings; - /** What {@link #revert()} goes back to: as the dialog opened, or as last applied. */ - private String originalPackId; - private String originalPackDir; - private Settings.Appearance originalAppearance; - - private final JComboBox appearanceCombo = - new JComboBox<>(Settings.Appearance.values()); - private final JComboBox scaleCombo = new JComboBox<>(); - private final JComboBox packCombo = new JComboBox<>(); - private final JLabel packInfo = new JLabel(); - private final JTextField packDirField; - private final JCheckBox countryFlags = new JCheckBox("Show country flags in the channel tree"); - private final RowColorCombo anyColor; - private final RowColorCombo talkingColor; - private final RowColorCombo mutedAwayColor; - private final DefaultListModel previewModel = new DefaultListModel<>(); - private final JList preview = new JList<>(previewModel); - - DesignPanel(Settings settings) { - super(new BorderLayout(0, UIScale.scale(8))); - this.settings = settings; - this.originalPackId = settings.iconPack; - this.originalPackDir = settings.iconPackDir; - this.originalAppearance = settings.appearance; - this.packDirField = new JTextField(settings.iconPackDir, 18); - this.anyColor = new RowColorCombo(settings.clientRowColors.any); - this.talkingColor = new RowColorCombo(settings.clientRowColors.talking); - this.mutedAwayColor = new RowColorCombo(settings.clientRowColors.mutedAway); - - setBorder(new ScaledEmptyBorder(12, 12, 12, 12)); - add(buildHeader(), BorderLayout.NORTH); - add(buildPreview(), BorderLayout.CENTER); - - reloadPacks(); - } - - /** Copies the chosen appearance and pack into the settings; the caller saves them. */ - void apply() { - settings.appearance = selectedAppearance(); - if (scaleCombo.getSelectedItem() instanceof Double scale) settings.uiScale = scale; - settings.iconPackDir = packDirField.getText().trim(); - Object selected = packCombo.getSelectedItem(); - settings.iconPack = selected instanceof IconPack pack ? pack.id() : ""; - settings.countryFlags = countryFlags.isSelected(); - settings.clientRowColors.any = anyColor.value(); - settings.clientRowColors.talking = talkingColor.value(); - settings.clientRowColors.mutedAway = mutedAwayColor.value(); - originalPackId = settings.iconPack; - originalPackDir = settings.iconPackDir; - originalAppearance = settings.appearance; - } - - /** Puts back the appearance and pack last applied, for a cancelled edit. */ - void revert() { - settings.iconPack = originalPackId; - settings.iconPackDir = originalPackDir; - IconTheme.get().reload(settings); - if (settings.appearance != originalAppearance) { - settings.appearance = originalAppearance; - LookAndFeelManager.switchTo(originalAppearance); - } - } - - // ---- layout ---- - - private JComponent buildHeader() { - JPanel p = new JPanel(new GridBagLayout()); - GridBagConstraints c = new GridBagConstraints(); - c.insets = UIScale.scale(new Insets(4, 4, 4, 4)); - c.anchor = GridBagConstraints.WEST; - c.fill = GridBagConstraints.HORIZONTAL; - - packCombo.setToolTipText("Icon packs installed here or in a TeamSpeak 3 client"); - packCombo.addActionListener(e -> onPackSelected()); - packCombo.setRenderer(new DefaultListCellRenderer() { - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, - boolean selected, boolean focus) { - super.getListCellRendererComponent(list, value, index, selected, focus); - setText(value instanceof IconPack pack ? pack.name() : String.valueOf(value)); - return this; - } - }); - - appearanceCombo.setToolTipText("Light or dark window colours"); - appearanceCombo.setSelectedItem(settings.appearance); - appearanceCombo.setRenderer(new DefaultListCellRenderer() { - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, - boolean selected, boolean focus) { - super.getListCellRendererComponent(list, value, index, selected, focus); - setText(value == Settings.Appearance.DARK ? "Dark" : "Light"); - return this; - } - }); - appearanceCombo.addActionListener(e -> onAppearanceSelected()); - - JPanel dirRow = new JPanel(new BorderLayout(UIScale.scale(6), 0)); - JButton browse = new JButton("Browse…"); - browse.addActionListener(e -> browseForPackFolder()); - dirRow.add(packDirField, BorderLayout.CENTER); - dirRow.add(browse, BorderLayout.EAST); - packDirField.setToolTipText("Extra folder to look for icon packs in"); - packInfo.setEnabled(false); - countryFlags.setSelected(settings.countryFlags); - - int row = 0; - FormPanel.addSection(p, c, row++, "Appearance"); - FormPanel.addRow(p, c, row++, new JLabel("Theme:"), appearanceCombo); - if (DisplayScale.isManaged()) { - buildScaleCombo(); - FormPanel.addRow(p, c, row++, new JLabel("Interface scale:"), scaleCombo); - } - FormPanel.addSection(p, c, row++, "Channel Tree"); - FormPanel.addWide(p, c, row++, countryFlags); - FormPanel.addRow(p, c, row++, new JLabel("Client background:"), anyColor); - FormPanel.addRow(p, c, row++, new JLabel("While talking:"), talkingColor); - FormPanel.addRow(p, c, row++, new JLabel("Muted / away:"), mutedAwayColor); - FormPanel.addSection(p, c, row++, "Icon Pack"); - FormPanel.addRow(p, c, row++, new JLabel("Icon pack:"), packCombo); - c.gridx = 1; - c.gridy = row++; - p.add(packInfo, c); - FormPanel.addRow(p, c, row, new JLabel("Extra pack folder:"), dirRow); - return p; - } - - private void buildScaleCombo() { - for (double scale : SCALES) scaleCombo.addItem(scale); - if (settings.uiScale > 0 && Arrays.stream(SCALES).noneMatch(s -> s == settings.uiScale)) { - scaleCombo.addItem(settings.uiScale); - } - scaleCombo.setSelectedItem(Math.max(0, settings.uiScale)); - scaleCombo.setToolTipText("Size of text, icons and controls; takes effect after a restart"); - scaleCombo.setRenderer(new DefaultListCellRenderer() { - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, - boolean selected, boolean focus) { - super.getListCellRendererComponent(list, value, index, selected, focus); - double scale = value instanceof Double d ? d : 0; - setText(scale > 0 ? percent(scale) - : "Automatic (" + percent(DisplayScale.detected()) + ")"); - return this; - } - }); - } - - private static String percent(double scale) { - return Math.round(scale * 100) + "%"; - } - - private JComponent buildPreview() { - preview.setLayoutOrientation(JList.HORIZONTAL_WRAP); - preview.setVisibleRowCount(-1); - preview.setFixedCellWidth(UIScale.scale(TILE)); - preview.setFixedCellHeight(UIScale.scale(TILE)); - preview.setCellRenderer(new DefaultListCellRenderer() { - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, - boolean selected, boolean focus) { - super.getListCellRendererComponent(list, value, index, selected, focus); - String key = String.valueOf(value); - ImageIcon icon = Icons.of(key, UIScale.scale(PREVIEW_SIZE)); - setText(""); - setIcon(icon); - setToolTipText(key); - setHorizontalAlignment(SwingConstants.CENTER); - return this; - } - }); - - JScrollPane scroll = new JScrollPane(preview); - scroll.setPreferredSize(UIScale.scale(new Dimension(360, 200))); - return scroll; - } - - // ---- behaviour ---- - - private void reloadPacks() { - IconTheme theme = IconTheme.get(); - theme.reload(settings); - // Filling the combo box changes its selection, and with it the active pack, - // so remember the one the settings asked for before touching it. - IconPack selected = theme.activePack(); - - packCombo.removeAllItems(); - packCombo.addItem(BUILT_IN); - for (IconPack pack : theme.packs()) packCombo.addItem(pack); - packCombo.setSelectedItem(selected == null ? BUILT_IN : selected); - onPackSelected(); - } - - private Settings.Appearance selectedAppearance() { - Object selected = appearanceCombo.getSelectedItem(); - return selected instanceof Settings.Appearance a ? a : Settings.Appearance.LIGHT; - } - - private void onAppearanceSelected() { - Settings.Appearance chosen = selectedAppearance(); - if (chosen == settings.appearance) return; - settings.appearance = chosen; - LookAndFeelManager.switchTo(chosen); - } - - private void onPackSelected() { - Object selected = packCombo.getSelectedItem(); - IconPack pack = selected instanceof IconPack p ? p : null; - IconTheme.get().setPack(pack); - - previewModel.clear(); - if (pack == null) { - packInfo.setText("Drawn by the client itself"); - } else { - for (String key : pack.keys()) previewModel.addElement(key); - packInfo.setText(pack.keys().size() + " icons" - + (pack.fallsBack() ? ", missing ones from the default pack" : "")); - } - } - - private void browseForPackFolder() { - JFileChooser chooser = new JFileChooser(); - chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - chooser.setDialogTitle("Folder containing icon packs"); - String current = packDirField.getText().trim(); - if (!current.isEmpty()) chooser.setCurrentDirectory(new File(current)); - if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return; - packDirField.setText(chooser.getSelectedFile().getAbsolutePath()); - settings.iconPackDir = packDirField.getText(); - reloadPacks(); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/DesktopEntry.java b/ts3-client/swing/src/main/java/com/ts3client/ui/DesktopEntry.java deleted file mode 100644 index a9ec5e2..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/DesktopEntry.java +++ /dev/null @@ -1,140 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.Main; -import com.ts3client.session.ServerLink; - -import javax.imageio.ImageIO; -import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.net.URISyntaxException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardCopyOption; -import java.util.Arrays; -import java.util.Locale; - -/** - * Installs a freedesktop launcher for the client in the user's applications folder. - * - *

    Task bars find the launcher belonging to a window through its {@code WM_CLASS} - * ({@link WindowClass}), matched against {@code StartupWMClass}. When no launcher - * claims the class, Plasma falls back to the process's command line — {@code java} — - * and files the window under whatever launcher runs Java, with its name and icon. - * - *

    A launcher run from a jar also takes {@code ts3server://} links. - * - *

    The files are only rewritten when their content changes, e.g. after the jar moved. - * {@code -Dts3j.desktopEntry=false} turns this off. - */ -public final class DesktopEntry { - - private static final int ICON_SIZE = 256; - - private DesktopEntry() { - } - - /** Call on the event thread. */ - public static void install() { - if (!System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("linux") - || !Boolean.parseBoolean(System.getProperty("ts3j.desktopEntry", "true"))) { - return; - } - try { - Path data = dataHome(); - Path icon = icon(); - writeIfChanged(icon, iconPng()); - Path applications = data.resolve("applications"); - if (writeIfChanged(applications.resolve(WindowClass.NAME + ".desktop"), - entry(icon).getBytes(StandardCharsets.UTF_8))) { - updateSchemeHandlers(applications); - } - } catch (IOException | RuntimeException e) { - System.err.println("Cannot install the desktop entry: " + e); - } - } - - /** The application icon the entry names, which desktop notifications show too. */ - static Path icon() { - return dataHome().resolve("icons").resolve(WindowClass.NAME + ".png"); - } - - private static Path dataHome() { - String xdg = System.getenv("XDG_DATA_HOME"); - if (xdg != null && !xdg.isBlank()) return Path.of(xdg); - return Path.of(System.getProperty("user.home"), ".local", "share"); - } - - private static String entry(Path icon) { - String exec = launchCommand(); - StringBuilder s = new StringBuilder() - .append("[Desktop Entry]\n") - .append("Type=Application\n") - .append("Name=TS3J\n") - .append("GenericName=TeamSpeak 3 Client\n") - .append("Comment=Voice chat on TeamSpeak 3 servers\n") - .append("Icon=").append(icon).append('\n') - .append("Exec=").append(exec == null ? "java" : exec + " %u").append('\n') - .append("StartupWMClass=").append(WindowClass.NAME).append('\n') - .append("Categories=Network;InstantMessaging;AudioVideo;\n") - .append("Terminal=false\n"); - // Run from classes (an IDE, mvn exec:java) there is nothing sensible to launch; - // the entry is still needed to name the window, but stays out of the menu. - if (exec == null) s.append("NoDisplay=true\n"); - else s.append("MimeType=x-scheme-handler/").append(ServerLink.SCHEME).append(";\n"); - return s.toString(); - } - - /** {@code java -jar }, or {@code null} when not running from a jar. */ - private static String launchCommand() { - try { - Path jar = Path.of(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI()); - if (!jar.toString().endsWith(".jar")) return null; - String java = ProcessHandle.current().info().command().orElse("java"); - return quote(java) + " -jar " + quote(jar.toAbsolutePath().toString()); - } catch (URISyntaxException | RuntimeException e) { - return null; - } - } - - /** Quotes an Exec argument as the Desktop Entry spec asks. */ - private static String quote(String arg) { - arg = arg.replace("%", "%%"); - if (arg.chars().noneMatch(c -> " \t\"'\\`$;&|<>()*?#~".indexOf(c) >= 0)) return arg; - String escaped = arg.replaceAll("([\"`$\\\\])", "\\\\$1"); - // The whole value is also a desktop-file string, where a backslash is escaped again. - return ("\"" + escaped + "\"").replace("\\", "\\\\"); - } - - private static byte[] iconPng() throws IOException { - BufferedImage img = new BufferedImage(ICON_SIZE, ICON_SIZE, BufferedImage.TYPE_INT_ARGB); - Icons.app(ICON_SIZE).paintIcon(null, img.getGraphics(), 0, 0); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ImageIO.write(img, "png", out); - return out.toByteArray(); - } - - /** - * Browsers find the handler of a {@code ts3server://} link in the folder's MIME cache, which - * only this tool rebuilds; without it the entry still names the window. - */ - private static void updateSchemeHandlers(Path applications) { - try { - new ProcessBuilder("update-desktop-database", applications.toString()) - .redirectErrorStream(true).redirectOutput(ProcessBuilder.Redirect.DISCARD).start(); - } catch (IOException ignored) { - } - } - - /** @return whether the file changed */ - private static boolean writeIfChanged(Path file, byte[] content) throws IOException { - if (Files.exists(file) && Arrays.equals(Files.readAllBytes(file), content)) return false; - Files.createDirectories(file.getParent()); - Path tmp = file.resolveSibling(file.getFileName() + ".tmp"); - Files.write(tmp, content); - Files.move(tmp, file, StandardCopyOption.REPLACE_EXISTING, - StandardCopyOption.ATOMIC_MOVE); - return true; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/DesktopNotifier.java b/ts3-client/swing/src/main/java/com/ts3client/ui/DesktopNotifier.java deleted file mode 100644 index b7ca558..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/DesktopNotifier.java +++ /dev/null @@ -1,159 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.config.Settings; -import com.ts3client.net.ConnectionListener.ChatScope; -import com.ts3client.notify.desktop.DesktopNotifications; -import com.ts3client.notify.desktop.DesktopNotifications.Notice; -import com.ts3client.notify.desktop.FreedesktopNotifications; -import com.ts3client.text.BBCode; -import com.ts3client.text.ChatHtml; -import com.ts3client.ui.tray.AwtTray; - -import javax.swing.SwingUtilities; -import java.awt.KeyboardFocusManager; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * Tells the user about pokes and private messages through the desktop's notifications - * while none of the client's windows has the focus. A private conversation keeps one - * notification, updated as messages come; all of them go once the window is back in - * front, as they have then been seen. - * - *

    Called on the event thread. Talking to the desktop may block, so that happens on a - * thread of its own, which also keeps the notifications in order. - */ -final class DesktopNotifier { - - private static final int MAX_LINES = 5; - - private final MainFrame frame; - private final Settings settings; - private final ExecutorService worker = Executors.newSingleThreadExecutor(r -> { - Thread t = new Thread(r, "notifications"); - t.setDaemon(true); - return t; - }); - - /** Found on first use, on the worker; {@code null} where the desktop offers none. */ - private DesktopNotifications backend; - private boolean resolved; - - /** One notification per private conversation; touched on the worker only. */ - private final Map conversations = new HashMap<>(); - private final List pokes = new ArrayList<>(); - - private record Conversation(ServerTab tab, int clientId) { - } - - private static final class Shown { - final List lines = new ArrayList<>(); - int id; - } - - DesktopNotifier(MainFrame frame, Settings settings) { - this.frame = frame; - this.settings = settings; - } - - void poke(ServerTab tab, String from, String message) { - if (!wanted()) return; - String body = BBCode.toPlain(message); - Notice notice = new Notice(from + " poked you", body, () -> open(tab, null), null); - worker.execute(() -> { - DesktopNotifications out = backend(); - if (out == null) return; - int id = out.show(notice, 0); - if (id != 0) pokes.add(id); - }); - } - - void privateMessage(ServerTab tab, int clientId, String from, String message) { - if (!wanted()) return; - String text = ChatHtml.plainMessage(message); - Conversation key = new Conversation(tab, clientId); - worker.execute(() -> { - DesktopNotifications out = backend(); - if (out == null) return; - Shown shown = conversations.computeIfAbsent(key, k -> new Shown()); - shown.lines.add(text); - if (shown.lines.size() > MAX_LINES) shown.lines.removeFirst(); - Notice notice = new Notice(from, String.join("\n", shown.lines), - () -> open(tab, clientId), reply -> reply(tab, clientId, reply)); - shown.id = out.show(notice, shown.id); - }); - } - - /** The window is in front again: what was notified of is in plain sight. */ - void windowActivated() { - worker.execute(() -> { - if (backend == null) return; - conversations.values().forEach(shown -> backend.close(shown.id)); - conversations.clear(); - pokes.forEach(backend::close); - pokes.clear(); - }); - } - - /** A private chat on a server that went away can neither be opened nor answered. */ - void forget(ServerTab tab) { - worker.execute(() -> conversations.entrySet().removeIf(e -> { - if (e.getKey().tab() != tab) return false; - if (backend != null) backend.close(e.getValue().id); - return true; - })); - } - - void shutdown() { - worker.execute(() -> { - if (backend != null) backend.shutdown(); - }); - worker.shutdown(); - } - - private boolean wanted() { - // Some window of ours has the focus exactly when there is an active window. - return settings.desktopNotifications - && KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow() == null; - } - - private DesktopNotifications backend() { - if (!resolved) { - resolved = true; - backend = create(); - } - return backend; - } - - /** The desktop's notification service on Linux; elsewhere the tray icon's messages. */ - private DesktopNotifications create() { - if (System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("linux")) { - DesktopNotifications service = FreedesktopNotifications.connect( - "TS3J", WindowClass.NAME, DesktopEntry.icon().toString()); - if (service != null) return service; - } - return frame.awtTray() instanceof AwtTray tray ? new TrayNotifications(tray) : null; - } - - private void open(ServerTab tab, Integer clientId) { - SwingUtilities.invokeLater(() -> { - frame.bringToFront(); - frame.selectTab(tab); - if (clientId != null) { - var client = tab.connection().getModel().getClient(clientId); - if (client != null) tab.chat().openPrivateChat(clientId, client.uniqueId, client.nickname); - } - }); - } - - private void reply(ServerTab tab, int clientId, String text) { - SwingUtilities.invokeLater(() -> { - if (tab.session().isConnected()) tab.session().sendChat(ChatScope.PRIVATE, clientId, text); - }); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/Dialogs.java b/ts3-client/swing/src/main/java/com/ts3client/ui/Dialogs.java deleted file mode 100644 index d9a5560..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/Dialogs.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.ts3client.ui; - -import javax.swing.AbstractAction; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JRootPane; -import javax.swing.KeyStroke; -import java.awt.event.ActionEvent; -import java.awt.event.KeyEvent; - -/** Behaviour shared by the client's dialogs. */ -final class Dialogs { - - private Dialogs() { - } - - /** - * Makes Escape close a dialog, the way Swing's own option panes do. - * - *

    The binding lives on the root pane's window-wide input map, so it fires - * wherever the focus sits — but only where nothing nearer to the focused - * component claims Escape first, which is what leaves a table's or combo - * box's own "cancel the edit" behaviour intact. - */ - static void closeOnEscape(JDialog dialog) { - closeOnEscape(dialog, dialog::dispose); - } - - /** - * Binds Escape to the dialog's own way of closing, for dialogs that have to - * tidy up (or discard edits) on the way out. - */ - static void closeOnEscape(JDialog dialog, Runnable close) { - JRootPane root = dialog.getRootPane(); - root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) - .put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "ts3-close"); - root.getActionMap().put("ts3-close", new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - close.run(); - } - }); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/DisplayScale.java b/ts3-client/swing/src/main/java/com/ts3client/ui/DisplayScale.java deleted file mode 100644 index 04a2554..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/DisplayScale.java +++ /dev/null @@ -1,134 +0,0 @@ -package com.ts3client.ui; - -import java.awt.Toolkit; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; -import java.util.Locale; - -/** - * Decides how large the user interface is drawn on Linux, where Java2D only knows - * whole-number scale factors: asked for 150 %, it draws at 100 % — or, told - * 2 by the desktop, at 200 %, while FlatLaf's own scaling goes on top of that. - * - *

    So on Linux Java2D is pinned to 1 and the whole factor, fractional or not, is - * handed to FlatLaf, which scales fonts and its own metrics; the client scales its own - * sizes through FlatLaf's {@link com.formdev.flatlaf.util.UIScale} to match. - * - *

    The desktop's factor is read the way an X11 toolkit would learn it: - *

      - *
    1. {@code Xft/DPI} from XSETTINGS — GNOME and Plasma (through xsettingsd) publish - * the device-pixel DPI there, fractional scale and text scaling included;
    2. - *
    3. KWin's {@code [Xwayland] Scale}, which Plasma sets when X11 apps are left to - * scale themselves — for sessions with no XSETTINGS daemon running;
    4. - *
    5. {@code GDK_SCALE}, which Java2D would otherwise have honoured itself.
    6. - *
    - * With the compositor scaling X11 apps (GNOME's default, and Plasma's "Scaled by the - * system") the client sees 96 DPI and is drawn at 100 %, which is what those - * modes expect; they then upscale the window, blurry but the right size. - * - *

    A {@code sun.java2d.uiScale} or {@code flatlaf.uiScale} given on the command line - * turns all of this off. - */ -public final class DisplayScale { - - private static final String JAVA2D_SCALE = "sun.java2d.uiScale"; - private static final String FLATLAF_SCALE = "flatlaf.uiScale"; - private static final double BASE_DPI = 96; - private static final double MAX_SCALE = 4; - - private static boolean managed; - private static double detected = 1; - - private DisplayScale() { - } - - /** - * Sets the scale up; call before anything touches AWT. - * - * @param override the user's chosen factor, or 0 to follow the desktop - */ - public static void configure(double override) { - if (!isLinux() || System.getProperty(JAVA2D_SCALE) != null - || System.getProperty(FLATLAF_SCALE) != null) { - return; - } - System.setProperty(JAVA2D_SCALE, "1"); - managed = true; - detected = detect(); - double factor = override > 0 ? override : detected; - System.setProperty(FLATLAF_SCALE, Double.toString(factor)); - } - - /** Whether the client sets the scale itself, so that the user may choose one. */ - public static boolean isManaged() { - return managed; - } - - /** The desktop's factor, as found at startup. */ - public static double detected() { - return detected; - } - - private static double detect() { - double scale = xftScale(); - if (scale <= 0) scale = kwinXwaylandScale(); - scale = Math.max(scale, gdkScale()); - return Math.max(1, Math.min(MAX_SCALE, scale)); - } - - private static double xftScale() { - // The XSETTINGS value is in 1024ths of a DPI; -1 means "unset". - Object dpi = Toolkit.getDefaultToolkit().getDesktopProperty("gnome.Xft/DPI"); - return dpi instanceof Integer d && d > 0 ? d / 1024.0 / BASE_DPI : 0; - } - - private static double kwinXwaylandScale() { - // Left behind by a Wayland session, the key would be stale in an X11 one. - if (System.getenv("WAYLAND_DISPLAY") == null) return 0; - String configHome = System.getenv("XDG_CONFIG_HOME"); - Path kwinrc = (configHome == null || configHome.isEmpty() - ? Path.of(System.getProperty("user.home"), ".config") - : Path.of(configHome)).resolve("kwinrc"); - try { - return parseDouble(iniValue(Files.readAllLines(kwinrc), "Xwayland", "Scale")); - } catch (IOException e) { - return 0; - } - } - - private static double gdkScale() { - return parseDouble(System.getenv("GDK_SCALE")); - } - - /** The value of {@code key} in {@code [group]} of a KConfig-style file, or {@code null}. */ - static String iniValue(List lines, String group, String key) { - boolean inGroup = false; - for (String line : lines) { - String t = line.trim(); - if (t.startsWith("[")) { - inGroup = t.equals("[" + group + "]"); - } else if (inGroup) { - int eq = t.indexOf('='); - if (eq > 0 && t.substring(0, eq).trim().equals(key)) { - return t.substring(eq + 1).trim(); - } - } - } - return null; - } - - private static double parseDouble(String s) { - if (s == null) return 0; - try { - return Double.parseDouble(s.trim()); - } catch (NumberFormatException e) { - return 0; - } - } - - private static boolean isLinux() { - return System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("linux"); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/DropDownToggleButton.java b/ts3-client/swing/src/main/java/com/ts3client/ui/DropDownToggleButton.java deleted file mode 100644 index 546f694..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/DropDownToggleButton.java +++ /dev/null @@ -1,122 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.UIScale; - -import javax.swing.BorderFactory; -import javax.swing.Icon; -import javax.swing.JButton; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.JToggleButton; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Insets; -import java.awt.RenderingHints; -import java.awt.event.ActionListener; -import java.util.function.Supplier; - -/** - * A toolbar toggle button with a small arrow next to it that opens a menu: - * clicking the button toggles, clicking the arrow offers the related actions. - * - *

    The menu is built on every click by the supplier, so it can reflect the - * current state (checked items, the presets that exist right now). - */ -public final class DropDownToggleButton extends JPanel { - - private final JToggleButton button = new JToggleButton(); - private final JButton arrow = new JButton(new ArrowIcon()); - - public DropDownToggleButton(Icon icon, String tooltip, Supplier menu) { - super(new BorderLayout()); - setOpaque(false); - // Sitting inside this panel, the halves are not toolbar children any more, so the - // look and feel would paint them as filled buttons; ask for the flat toolbar look - // the plain toggles next to us get. - button.putClientProperty("JButton.buttonType", "toolBarButton"); - arrow.putClientProperty("JButton.buttonType", "toolBarButton"); - button.setIcon(icon); - button.setToolTipText(tooltip); - - arrow.setToolTipText(tooltip); - arrow.setMargin(new Insets(0, 2, 0, 2)); - arrow.setFocusable(false); - arrow.addActionListener(e -> { - JPopupMenu popup = menu.get(); - if (popup != null) popup.show(this, 0, getHeight()); - }); - - // Keep the whole control the size of a plain toolbar button: the arrow's - // width comes out of the toggle half instead of being added to it. - Dimension plain = button.getPreferredSize(); - button.setPreferredSize(new Dimension( - Math.max(icon.getIconWidth() + UIScale.scale(8), plain.width - arrow.getPreferredSize().width), - plain.height)); - - add(button, BorderLayout.CENTER); - add(arrow, BorderLayout.EAST); - } - - /** Listener for the toggle half only; the arrow half opens the menu instead. */ - public void addActionListener(ActionListener l) { - button.addActionListener(l); - } - - public boolean isSelected() { - return button.isSelected(); - } - - public void setSelected(boolean selected) { - button.setSelected(selected); - } - - public void setIcon(Icon icon) { - button.setIcon(icon); - } - - @Override - public void setEnabled(boolean enabled) { - super.setEnabled(enabled); - button.setEnabled(enabled); - arrow.setEnabled(enabled); - } - - /** Disables the toggle half on its own, leaving the menu reachable. */ - public void setToggleEnabled(boolean enabled) { - button.setEnabled(enabled); - } - - @Override - public Dimension getMaximumSize() { - return getPreferredSize(); // keep the toolbar from stretching us - } - - /** The downward triangle on the menu half of the button. */ - private static final class ArrowIcon implements Icon { - - @Override - public void paintIcon(Component c, Graphics g0, int x, int y) { - Graphics2D g = (Graphics2D) g0.create(); - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.setColor(c.isEnabled() ? Color.DARK_GRAY : Color.GRAY); - int[] xs = {x, x + getIconWidth(), x + getIconWidth() / 2}; - int[] ys = {y, y, y + getIconHeight()}; - g.fillPolygon(xs, ys, 3); - g.dispose(); - } - - @Override - public int getIconWidth() { - return UIScale.scale(7); - } - - @Override - public int getIconHeight() { - return UIScale.scale(4); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/DropIndicatorTree.java b/ts3-client/swing/src/main/java/com/ts3client/ui/DropIndicatorTree.java deleted file mode 100644 index 3ece40b..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/DropIndicatorTree.java +++ /dev/null @@ -1,342 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.config.Settings; -import com.ts3client.net.ChannelNode; -import com.ts3client.net.Spacers; -import com.ts3client.net.ClientEntry; -import com.ts3client.net.ClientStatus; -import com.ts3client.net.ServerModel; - -import javax.swing.Icon; -import javax.swing.JTree; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreeModel; -import javax.swing.tree.TreePath; -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.Collections; -import java.util.List; -import java.util.Set; -import java.util.function.Predicate; - -/** - * The {@link ServerTreePanel} tree, extended to draw where a drag-and-drop would - * land: an insertion line between rows, or an outline around the row that will - * receive the dragged node. Also keeps the server row permanently expanded and - * paints the right-aligned group icon strip, both of which need to hook into - * this component's own paint cycle. - */ -final class DropIndicatorTree extends JTree { - - /** Gap kept between a row's label and the right-aligned icon strip. */ - private static final int BADGE_GAP = 8; - /** Inset of the strip from the visible right edge. */ - private static final int BADGE_MARGIN = 4; - - private final ServerModel model; - private final GroupIcons groupIcons; - private final Settings settings; - /** Set while a drop would move a client into this channel row. */ - private TreePath highlight; - /** The row the pointer is over, or -1 when it is over none. */ - private int hoverRow = -1; - /** User objects of the rows a find bar matched, compared by identity. */ - private Set searchHits = Collections.emptySet(); - private Predicate pathEditable = path -> false; - - DropIndicatorTree(TreeModel treeModel, ServerModel model, GroupIcons groupIcons, Settings settings) { - super(treeModel); - this.model = model; - this.groupIcons = groupIcons; - this.settings = settings; - MouseAdapter hover = new MouseAdapter() { - @Override - public void mouseMoved(MouseEvent e) { - setHoverRow(rowAt(e.getY())); - } - - @Override - public void mouseDragged(MouseEvent e) { - setHoverRow(-1); - } - - @Override - public void mouseExited(MouseEvent e) { - setHoverRow(-1); - } - }; - addMouseMotionListener(hover); - addMouseListener(hover); - // The selected row is filled across the full width below, before the rows - // themselves are drawn, so this component must not clear its own background. - setOpaque(false); - } - - /** - * The row a point falls on, going by its vertical band alone: a row reaches - * across the whole width, not just as far as its label. - */ - int rowAt(int y) { - int row = getClosestRowForLocation(0, y); - if (row < 0) return -1; - Rectangle bounds = getRowBounds(row); - return bounds != null && y >= bounds.y && y < bounds.y + bounds.height ? row : -1; - } - - /** The path a point falls on, by the same rule as {@link #rowAt(int)}. */ - TreePath pathAt(int y) { - int row = rowAt(y); - return row < 0 ? null : getPathForRow(row); - } - - /** - * Re-reads the row the pointer is over. Scrolling moves the rows under a pointer - * that never moved itself, so the enclosing scroll pane calls this on every scroll. - */ - void refreshHoverRow() { - Point pointer = getMousePosition(); - setHoverRow(pointer == null ? -1 : rowAt(pointer.y)); - } - - private void setHoverRow(int row) { - if (row == hoverRow) return; - repaintRow(hoverRow); - hoverRow = row; - repaintRow(row); - } - - private void repaintRow(int row) { - if (row < 0) return; - Rectangle bounds = getRowBounds(row); - if (bounds != null) repaint(0, bounds.y, getWidth(), bounds.height); - } - - /** Which rows an inline editor may open on; nothing, until one is installed. */ - void setPathEditable(Predicate editable) { - this.pathEditable = editable; - } - - @Override - public boolean isPathEditable(TreePath path) { - return isEditable() && pathEditable.test(path); - } - - /** Keeps the server row permanently open; collapsing it would hide everything. */ - @Override - public void setExpandedState(TreePath path, boolean state) { - if (!state && path.getPathCount() == 1) return; - super.setExpandedState(path, state); - } - - /** - * Widens every repaint request to the full visible width. Swing only asks for - * the row rectangle, which stops short of the right-aligned icon strip and would - * leave it behind when a row's label changes width. - */ - @Override - public void repaint(long tm, int x, int y, int width, int height) { - Rectangle visible = getVisibleRect(); - super.repaint(tm, visible.x, y, visible.width, height); - } - - void setSearchHits(Set hits) { - searchHits = hits; - repaint(); - } - - void highlightChannel(TreePath path) { - if (path == highlight || (path != null && path.equals(highlight))) return; - highlight = path; - repaint(); - } - - @Override - protected void paintComponent(Graphics g) { - Rectangle clip = g.getClipBounds(); - g.setColor(getBackground()); - g.fillRect(clip.x, clip.y, clip.width, clip.height); - paintClientColors(g); - paintSearchHits(g); - paintSelection(g); - paintHover(g); - super.paintComponent(g); - paintBadges(g); - JTree.DropLocation loc = getDropLocation(); - if (loc == null || loc.getPath() == null) return; - - Graphics2D g2 = (Graphics2D) g.create(); - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g2.setColor(Theme.accent()); - if (highlight != null || loc.getChildIndex() < 0) { - Rectangle r = getPathBounds(highlight != null ? highlight : loc.getPath()); - if (r != null) { - g2.setStroke(new BasicStroke(UIScale.scale(2f))); - int arc = UIScale.scale(4); - g2.drawRoundRect(r.x, r.y + 1, r.width - 1, r.height - 3, arc, arc); - } - } else { - Rectangle line = insertLine(loc); - if (line != null) { - int dot = UIScale.scale(7); - g2.fillRect(line.x, line.y - line.height / 2, line.width, line.height); - g2.fillOval(line.x - dot / 2, line.y - dot / 2 - 1, dot, dot); - } - } - g2.dispose(); - } - - /** - * Fills the selected row across the full width, in the colour the cell renderer - * puts behind the label itself, so the selection covers the whole line rather - * than stopping where the name ends. - */ - private void paintSelection(Graphics g) { - int[] rows = getSelectionRows(); - if (rows == null) return; - Rectangle visible = getVisibleRect(); - g.setColor(Theme.treeSelection()); - for (int row : rows) { - Rectangle bounds = getRowBounds(row); - if (bounds != null) g.fillRect(visible.x, bounds.y, visible.width, bounds.height); - } - } - - /** Fills client rows across the full width in the colour chosen for what they are doing. */ - private void paintClientColors(Graphics g) { - Rectangle visible = getVisibleRect(); - int first = Math.max(0, getClosestRowForLocation(visible.x, visible.y)); - for (int row = first; row < getRowCount(); row++) { - Rectangle bounds = getRowBounds(row); - if (bounds == null) continue; - if (bounds.y > visible.y + visible.height) break; - Object obj = ((DefaultMutableTreeNode) getPathForRow(row).getLastPathComponent()).getUserObject(); - if (!(obj instanceof ClientEntry cl)) continue; - int argb = settings.clientRowColors.of(ClientStatus.of(cl)); - if (argb == 0) continue; - g.setColor(new Color(argb, true)); - g.fillRect(visible.x, bounds.y, visible.width, bounds.height); - } - } - - private void paintSearchHits(Graphics g) { - if (searchHits.isEmpty()) return; - Rectangle visible = getVisibleRect(); - int first = Math.max(0, getClosestRowForLocation(visible.x, visible.y)); - g.setColor(Theme.searchMatch()); - for (int row = first; row < getRowCount(); row++) { - Rectangle bounds = getRowBounds(row); - if (bounds == null) continue; - if (bounds.y > visible.y + visible.height) break; - Object obj = ((DefaultMutableTreeNode) getPathForRow(row).getLastPathComponent()).getUserObject(); - if (searchHits.contains(obj)) g.fillRect(visible.x, bounds.y, visible.width, bounds.height); - } - } - - /** - * Washes the row under the pointer across the full width it occupies — the same - * area a click on it acts on. A selected row keeps its selection colour, and - * spacers, which nothing can be done with, are left alone. - */ - private void paintHover(Graphics g) { - if (hoverRow < 0 || getDropLocation() != null || isRowSelected(hoverRow)) return; - Rectangle bounds = getRowBounds(hoverRow); - TreePath path = getPathForRow(hoverRow); - if (bounds == null || path == null || isSpacer(path)) return; - - Rectangle visible = getVisibleRect(); - g.setColor(Theme.hover()); - g.fillRect(visible.x, bounds.y, visible.width, bounds.height); - } - - private boolean isSpacer(TreePath path) { - Object obj = ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); - return obj instanceof ChannelNode && Spacers.isSpacer(((ChannelNode) obj).name); - } - - /** The strip where the insertion line goes, in tree coordinates. */ - private Rectangle insertLine(JTree.DropLocation loc) { - DefaultMutableTreeNode parent = (DefaultMutableTreeNode) loc.getPath().getLastPathComponent(); - int index = loc.getChildIndex(); - if (index < parent.getChildCount()) { - Rectangle r = getPathBounds(loc.getPath().pathByAddingChild(parent.getChildAt(index))); - return r == null ? null : new Rectangle(r.x, r.y, getWidth() - r.x, UIScale.scale(2)); - } - if (parent.getChildCount() == 0) { - Rectangle r = getPathBounds(loc.getPath()); - if (r == null) return null; - int x = r.x + getRowHeight(); - return new Rectangle(x, r.y + r.height, getWidth() - x, UIScale.scale(2)); - } - // Past the last child: below that child's whole (expanded) subtree. - TreePath lastChild = loc.getPath().pathByAddingChild(parent.getChildAt(parent.getChildCount() - 1)); - Rectangle head = getPathBounds(lastChild); - Rectangle tail = getPathBounds(lastVisibleRow(lastChild)); - if (head == null || tail == null) return null; - return new Rectangle(head.x, tail.y + tail.height, getWidth() - head.x, 2); - } - - private TreePath lastVisibleRow(TreePath path) { - int row = getRowForPath(path); - if (row < 0) return path; - for (int i = row + 1; i < getRowCount(); i++) { - if (!path.isDescendant(getPathForRow(i))) break; - row = i; - } - return getPathForRow(row); - } - - /** - * Paints the icons of every visible row — a client's group icons, a channel's - * own icon — flush with the right edge of the viewport, the way TeamSpeak lines - * them up. Drawing them separately from the cell renderer keeps the rows' - * measured widths (and thus the selection highlight) tied to the label alone. - */ - private void paintBadges(Graphics g) { - Rectangle visible = getVisibleRect(); - int right = visible.x + visible.width - UIScale.scale(BADGE_MARGIN); - for (int row = 0; row < getRowCount(); row++) { - Rectangle bounds = getRowBounds(row); - if (bounds == null || bounds.y + bounds.height < visible.y) continue; - if (bounds.y > visible.y + visible.height) break; - - List icons = badgesOf((DefaultMutableTreeNode) getPathForRow(row).getLastPathComponent()); - if (icons.isEmpty()) continue; - - GroupIcons.Row strip = new GroupIcons.Row(icons); - int x = Math.max(bounds.x + bounds.width + UIScale.scale(BADGE_GAP), right - strip.getIconWidth()); - strip.paintIcon(this, g, x, bounds.y + (bounds.height - strip.getIconHeight()) / 2); - } - } - - /** The icon strip a row shows on its right, empty when it has none (yet). */ - private List badgesOf(DefaultMutableTreeNode treeNode) { - Object node = treeNode.getUserObject(); - if (treeNode.isRoot()) { - Icon icon = groupIcons.icon(model.serverIconId()); - return icon == null ? List.of() : List.of(icon); - } - if (node instanceof ClientEntry) { - ClientEntry cl = (ClientEntry) node; - List icons = groupIcons.iconsOf( - model.serverGroupsOf(cl.serverGroupIds), model.channelGroup(cl.channelGroupId)); - // The country's flag comes last, at the row's edge, as in TeamSpeak. - Icon flag = settings.countryFlags ? CountryFlagIcons.of(cl.country) : null; - if (flag != null) icons.add(flag); - return icons; - } - if (node instanceof ChannelNode) { - ChannelNode ch = (ChannelNode) node; - Icon icon = Spacers.isSpacer(ch.name) ? null : groupIcons.icon(ch.iconId); - if (icon != null) return List.of(icon); - } - return List.of(); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/FileBrowserDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/FileBrowserDialog.java deleted file mode 100644 index 5f0abd7..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/FileBrowserDialog.java +++ /dev/null @@ -1,482 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.net.ChannelNode; -import com.ts3client.net.TeamspeakConnection; -import com.ts3client.net.filetransfer.FileTransfer; -import com.ts3client.net.filetransfer.RemoteFile; - -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFileChooser; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JProgressBar; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.ListSelectionModel; -import javax.swing.SwingUtilities; -import javax.swing.table.AbstractTableModel; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Frame; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.io.File; -import java.text.DecimalFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.List; - -/** - * Browses a channel's file repository and drives uploads and downloads. The table - * lists the current directory; the toolbar navigates and acts on the selection; the - * strip at the bottom shows live progress for each active transfer. - * - *

    All server calls run on background threads so the dialog never blocks the EDT; - * results are marshalled back with {@link SwingUtilities#invokeLater}. - */ -public final class FileBrowserDialog extends JDialog { - - private final TeamspeakConnection conn; - private final int channelId; - private final String channelPassword; - - private final FileTableModel tableModel = new FileTableModel(); - private final JTable table = new JTable(tableModel); - private final JLabel pathLabel = new JLabel("/"); - private final JButton upButton = new JButton("Up", Icons.of("FILE_UP")); - private final JButton downloadButton = new JButton("Download", Icons.of("DOWNLOAD")); - private final JButton deleteButton = new JButton("Delete", Icons.of("DELETE")); - private final JPanel transfersPanel = new JPanel(); - - private volatile String currentPath = "/"; - - public FileBrowserDialog(Frame owner, TeamspeakConnection conn, ChannelNode channel) { - super(owner, "Files — " + channel.name, false); - this.conn = conn; - this.channelId = channel.id; - this.channelPassword = ""; - - JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(8))); - content.setBackground(Theme.windowBg()); - content.setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); - content.add(buildToolbar(), BorderLayout.NORTH); - content.add(buildTable(), BorderLayout.CENTER); - content.add(buildTransfers(), BorderLayout.SOUTH); - setContentPane(content); - - setPreferredSize(UIScale.scale(new Dimension(640, 480))); - pack(); - setLocationRelativeTo(owner); - - refresh(); - } - - // ---- construction ---- - - private JPanel buildToolbar() { - JPanel bar = new JPanel(); - bar.setLayout(new BoxLayout(bar, BoxLayout.X_AXIS)); - bar.setBackground(Theme.windowBg()); - - upButton.addActionListener(e -> navigateUp()); - JButton refresh = new JButton("Refresh", Icons.of("FILE_REFRESH")); - refresh.addActionListener(e -> refresh()); - JButton mkdir = new JButton("New folder", Icons.of("ADD_FOLDER")); - mkdir.addActionListener(e -> createDirectory()); - JButton upload = new JButton("Upload…", Icons.of("UPLOAD")); - upload.addActionListener(e -> chooseUpload()); - downloadButton.addActionListener(e -> downloadSelected()); - deleteButton.addActionListener(e -> deleteSelected()); - - bar.add(upButton); - bar.add(Box.createHorizontalStrut(UIScale.scale(6))); - bar.add(refresh); - bar.add(Box.createHorizontalStrut(UIScale.scale(16))); - bar.add(pathLabel); - bar.add(Box.createHorizontalGlue()); - bar.add(mkdir); - bar.add(Box.createHorizontalStrut(UIScale.scale(6))); - bar.add(upload); - bar.add(Box.createHorizontalStrut(UIScale.scale(6))); - bar.add(downloadButton); - bar.add(Box.createHorizontalStrut(UIScale.scale(6))); - bar.add(deleteButton); - - pathLabel.setFont(Theme.uiFont()); - pathLabel.setForeground(Theme.treeText()); - return bar; - } - - private JScrollPane buildTable() { - table.setFont(Theme.uiFont()); - table.setRowHeight(UIScale.scale(20)); - table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - table.setFillsViewportHeight(true); - table.getColumnModel().getColumn(0).setPreferredWidth(UIScale.scale(300)); - table.getColumnModel().getColumn(0).setCellRenderer(new NameRenderer()); - table.getColumnModel().getColumn(1).setPreferredWidth(UIScale.scale(90)); - table.getColumnModel().getColumn(2).setPreferredWidth(UIScale.scale(70)); - table.getColumnModel().getColumn(3).setPreferredWidth(UIScale.scale(150)); - table.getSelectionModel().addListSelectionListener(e -> updateButtons()); - table.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) { - int row = table.rowAtPoint(e.getPoint()); - if (row >= 0) openEntry(tableModel.get(row)); - } - } - }); - JScrollPane scroll = new JScrollPane(table); - scroll.getViewport().setBackground(Theme.treeBg()); - return scroll; - } - - private JScrollPane buildTransfers() { - transfersPanel.setLayout(new BoxLayout(transfersPanel, BoxLayout.Y_AXIS)); - transfersPanel.setBackground(Theme.windowBg()); - JScrollPane scroll = new JScrollPane(transfersPanel); - scroll.setBorder(BorderFactory.createTitledBorder("Transfers")); - scroll.setPreferredSize(UIScale.scale(new Dimension(10, 120))); - scroll.getViewport().setBackground(Theme.windowBg()); - return scroll; - } - - // ---- navigation ---- - - private void navigateUp() { - String path = currentPath; - if (path.equals("/")) return; - String trimmed = path.substring(0, path.length() - 1); // drop trailing slash - int slash = trimmed.lastIndexOf('/'); - currentPath = slash <= 0 ? "/" : trimmed.substring(0, slash + 1); - refresh(); - } - - private void openEntry(RemoteFile file) { - if (file == null) return; - if (file.isDirectory()) { - currentPath = currentPath + file.getName() + "/"; - refresh(); - } else { - download(file); - } - } - - /** Reloads the current directory listing from the server. */ - private void refresh() { - pathLabel.setText(currentPath); - upButton.setEnabled(!currentPath.equals("/")); - final String path = currentPath; - new Thread(() -> { - try { - List files = conn.listFiles(channelId, channelPassword, path); - Collections.sort(files, DIRECTORIES_FIRST); - SwingUtilities.invokeLater(() -> { - if (path.equals(currentPath)) tableModel.setFiles(files); - updateButtons(); - }); - } catch (Exception ex) { - SwingUtilities.invokeLater(() -> { - if (path.equals(currentPath)) tableModel.setFiles(new ArrayList<>()); - error("Could not list files", ex); - }); - } - }, "ts3j-ft-list").start(); - } - - private void updateButtons() { - boolean hasSelection = table.getSelectedRowCount() > 0; - deleteButton.setEnabled(hasSelection); - boolean fileSelected = false; - for (int row : table.getSelectedRows()) { - if (!tableModel.get(row).isDirectory()) { - fileSelected = true; - break; - } - } - downloadButton.setEnabled(fileSelected); - } - - // ---- actions ---- - - private void downloadSelected() { - List files = new ArrayList<>(); - for (int row : table.getSelectedRows()) { - RemoteFile f = tableModel.get(row); - if (!f.isDirectory()) files.add(f); - } - if (files.isEmpty()) return; - if (files.size() == 1) { - download(files.get(0)); - return; - } - // Multiple files: pick a target directory once. - JFileChooser chooser = new JFileChooser(); - chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - chooser.setDialogTitle("Download " + files.size() + " files to…"); - if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return; - File dir = chooser.getSelectedFile(); - for (RemoteFile f : files) { - startDownload(f, new File(dir, f.getName())); - } - } - - private void download(RemoteFile file) { - JFileChooser chooser = new JFileChooser(); - chooser.setSelectedFile(new File(file.getName())); - chooser.setDialogTitle("Download " + file.getName()); - if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return; - startDownload(file, chooser.getSelectedFile()); - } - - private void startDownload(RemoteFile file, File target) { - TransferRow row = new TransferRow(); - FileTransfer transfer = conn.downloadFile(channelId, channelPassword, file.getFullPath(), target, - t -> SwingUtilities.invokeLater(() -> row.update(t))); - row.attach(transfer); - addTransferRow(row); - } - - private void chooseUpload() { - JFileChooser chooser = new JFileChooser(); - chooser.setMultiSelectionEnabled(true); - chooser.setDialogTitle("Upload to " + currentPath); - if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return; - for (File source : chooser.getSelectedFiles()) { - if (!source.isFile()) continue; - String remotePath = currentPath + source.getName(); - TransferRow row = new TransferRow(); - FileTransfer transfer = conn.uploadFile(channelId, channelPassword, remotePath, source, true, - t -> SwingUtilities.invokeLater(() -> { - row.update(t); - if (t.getState() == FileTransfer.State.COMPLETED) refresh(); - })); - row.attach(transfer); - addTransferRow(row); - } - } - - private void createDirectory() { - String name = JOptionPane.showInputDialog(this, "New folder name:", "New folder", - JOptionPane.PLAIN_MESSAGE); - if (name == null || name.trim().isEmpty()) return; - final String dirPath = currentPath + name.trim(); - new Thread(() -> { - try { - conn.createDirectory(channelId, channelPassword, dirPath); - SwingUtilities.invokeLater(this::refresh); - } catch (Exception ex) { - SwingUtilities.invokeLater(() -> error("Could not create folder", ex)); - } - }, "ts3j-ft-mkdir").start(); - } - - private void deleteSelected() { - List files = new ArrayList<>(); - for (int row : table.getSelectedRows()) files.add(tableModel.get(row)); - if (files.isEmpty()) return; - int choice = JOptionPane.showConfirmDialog(this, - "Delete " + (files.size() == 1 ? "\"" + files.get(0).getName() + "\"" : files.size() + " items") - + "?", "Delete", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); - if (choice != JOptionPane.OK_OPTION) return; - new Thread(() -> { - Exception failure = null; - for (RemoteFile f : files) { - try { - conn.deleteFile(channelId, channelPassword, f.getFullPath()); - } catch (Exception ex) { - failure = ex; - } - } - final Exception shown = failure; - SwingUtilities.invokeLater(() -> { - refresh(); - if (shown != null) error("Could not delete some items", shown); - }); - }, "ts3j-ft-delete").start(); - } - - private void addTransferRow(TransferRow row) { - transfersPanel.add(row); - transfersPanel.revalidate(); - transfersPanel.repaint(); - } - - private void error(String title, Exception ex) { - JOptionPane.showMessageDialog(this, rootMessage(ex), title, JOptionPane.ERROR_MESSAGE); - } - - // ---- one transfer's row ---- - - private final class TransferRow extends JPanel { - private final JLabel label = new JLabel(); - private final JProgressBar bar = new JProgressBar(0, 1000); - private final JButton action = new JButton("Cancel"); - private FileTransfer transfer; - - TransferRow() { - setLayout(new BorderLayout(UIScale.scale(8), 0)); - setBackground(Theme.windowBg()); - setBorder(new ScaledEmptyBorder(3, 2, 3, 2)); - setMaximumSize(new Dimension(Integer.MAX_VALUE, UIScale.scale(44))); - label.setFont(Theme.uiFont()); - bar.setStringPainted(true); - add(label, BorderLayout.NORTH); - add(bar, BorderLayout.CENTER); - add(action, BorderLayout.EAST); - } - - void attach(FileTransfer t) { - this.transfer = t; - action.addActionListener(e -> { - if (transfer.isDone()) { - transfersPanel.remove(this); - transfersPanel.revalidate(); - transfersPanel.repaint(); - } else { - transfer.cancel(); - } - }); - update(t); - } - - void update(FileTransfer t) { - String arrow = t.getDirection() == FileTransfer.Direction.UPLOAD ? "↑" : "↓"; - String head = arrow + " " + t.getRemoteName(); - switch (t.getState()) { - case PENDING: - label.setText(head + " — starting…"); - break; - case ACTIVE: - label.setText(head + " — " + formatBytes(t.getTransferredBytes()) + " / " - + formatBytes(t.getTotalBytes()) + " (" + formatRate(t.getAverageSpeed()) + ")"); - break; - case COMPLETED: - label.setText(head + " — done (" + formatBytes(t.getTotalBytes()) + ")"); - break; - case CANCELLED: - label.setText(head + " — cancelled"); - break; - case FAILED: - label.setText(head + " — failed: " + orEmpty(t.getErrorMessage())); - break; - default: - break; - } - int permille = (int) Math.round(t.getProgress() * 1000); - bar.setValue(permille); - bar.setString(t.getTotalBytes() > 0 ? (permille / 10) + "%" : ""); - if (t.isDone()) { - bar.setValue(t.getState() == FileTransfer.State.COMPLETED ? 1000 : bar.getValue()); - action.setText("Clear"); - } - } - } - - // ---- table model ---- - - private static final Comparator DIRECTORIES_FIRST = (a, b) -> { - if (a.isDirectory() != b.isDirectory()) return a.isDirectory() ? -1 : 1; - return a.getName().compareToIgnoreCase(b.getName()); - }; - - private static final class FileTableModel extends AbstractTableModel { - private static final String[] COLUMNS = {"Name", "Size", "Type", "Modified"}; - private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); - private List files = new ArrayList<>(); - - void setFiles(List files) { - this.files = files; - fireTableDataChanged(); - } - - RemoteFile get(int row) { - return files.get(row); - } - - @Override - public int getRowCount() { - return files.size(); - } - - @Override - public int getColumnCount() { - return COLUMNS.length; - } - - @Override - public String getColumnName(int column) { - return COLUMNS[column]; - } - - @Override - public Object getValueAt(int rowIndex, int columnIndex) { - RemoteFile f = files.get(rowIndex); - switch (columnIndex) { - case 0: - return f.getName(); - case 1: - return f.isDirectory() ? "" : formatBytes(f.getSize()); - case 2: - return f.isDirectory() ? "Folder" : "File"; - case 3: - long sec = f.getLastModifiedEpochSec(); - return sec > 0 ? dateFormat.format(new Date(sec * 1000)) : ""; - default: - return ""; - } - } - } - - /** Marks folders and files with the icon pack's own glyphs. */ - private final class NameRenderer extends javax.swing.table.DefaultTableCellRenderer { - @Override - public java.awt.Component getTableCellRendererComponent(JTable t, Object value, boolean selected, - boolean focus, int row, int column) { - super.getTableCellRendererComponent(t, value, selected, focus, row, column); - boolean directory = row >= 0 && row < tableModel.getRowCount() && tableModel.get(row).isDirectory(); - setIcon(Icons.of(directory ? "FOLDER" : "DEFAULT")); - return this; - } - } - - // ---- formatting ---- - - private static String formatBytes(long bytes) { - if (bytes < 0) return "—"; - if (bytes < 1024) return bytes + " B"; - double kib = bytes / 1024.0; - if (kib < 1024) return new DecimalFormat("0.0").format(kib) + " KiB"; - double mib = kib / 1024.0; - if (mib < 1024) return new DecimalFormat("0.00").format(mib) + " MiB"; - return new DecimalFormat("0.00").format(mib / 1024.0) + " GiB"; - } - - private static String formatRate(double bytesPerSecond) { - if (bytesPerSecond <= 0) return "—"; - return formatBytes(Math.round(bytesPerSecond)) + "/s"; - } - - private static String orEmpty(String s) { - return s == null ? "" : s; - } - - private static String rootMessage(Throwable t) { - Throwable r = t; - while (r.getCause() != null && r.getCause() != r) r = r.getCause(); - String m = r.getMessage(); - return m != null ? m : r.getClass().getSimpleName(); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/FindBar.java b/ts3-client/swing/src/main/java/com/ts3client/ui/FindBar.java deleted file mode 100644 index 7885b62..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/FindBar.java +++ /dev/null @@ -1,379 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.FlatClientProperties; -import com.formdev.flatlaf.icons.FlatAbstractIcon; -import com.formdev.flatlaf.icons.FlatSearchIcon; -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.text.TextQuery; - -import javax.swing.AbstractAction; -import javax.swing.AbstractButton; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.JToggleButton; -import javax.swing.JToolBar; -import javax.swing.KeyStroke; -import javax.swing.Timer; -import javax.swing.UIManager; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import java.awt.BasicStroke; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Insets; -import java.awt.Graphics2D; -import java.awt.event.ActionEvent; -import java.awt.event.KeyEvent; -import java.awt.geom.Path2D; -import java.util.ArrayList; -import java.util.List; -import java.util.function.BooleanSupplier; - -/** - * A single-row find bar for a view: the search field with its match-case, whole-word - * and regex toggles, the match count, previous/next and close. A view puts its own - * controls (what to search, whether to filter) in front of the field via - * {@link #addLeading} and {@link #addFilterToggle}. - * - *

    Typing is debounced; a toggle takes effect at once. Enter / F3 go to the next - * match, Shift+Enter / Shift+F3 to the previous one. Escape first resets the bar (text - * and every option) and closes it only once there is nothing left to reset. - */ -final class FindBar extends JPanel { - - interface Listener { - void queryChanged(TextQuery query); - - void next(); - - void previous(); - - void closed(); - } - - private static final int TYPING_DELAY_MS = 150; - - private final Listener listener; - private final JTextField field = new JTextField(); - private final JToggleButton matchCase = fieldToggle("Aa", "Match case"); - private final JToggleButton wholeWord = fieldToggle("ab", "Whole words"); - private final JToggleButton regex = fieldToggle(".*", "Regular expression"); - /** Wide enough for "00 / 00" whatever it shows, so the field beside it keeps its width. */ - private final JLabel status = new JLabel("", JLabel.TRAILING) { - @Override - public Dimension getPreferredSize() { - Dimension d = super.getPreferredSize(); - Insets in = getInsets(); - int reserved = getFontMetrics(getFont()).stringWidth("00 / 00") + in.left + in.right; - return new Dimension(Math.max(d.width, reserved), d.height); - } - - @Override - public Dimension getMinimumSize() { - return getPreferredSize(); - } - - @Override - public Dimension getMaximumSize() { - return getPreferredSize(); - } - }; - private final JButton previous = navButton(new Glyph(Glyph.UP), "Previous match (Shift+Enter)"); - private final JButton next = navButton(new Glyph(Glyph.DOWN), "Next match (Enter)"); - private final JPanel leading = new JPanel(); - private final Timer typing = new Timer(TYPING_DELAY_MS, e -> fireQueryChanged()); - /** Options beyond the built-in toggles: whether each is at its default, and how to put it back. */ - private final List optionDefaults = new ArrayList<>(); - private final List optionResets = new ArrayList<>(); - - FindBar(Listener listener) { - super(new BorderLayout(UIScale.scale(2), 0)); - this.listener = listener; - setBorder(new ScaledEmptyBorder(4, 4, 4, 4)); - setVisible(false); - - typing.setRepeats(false); - field.putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, "Find"); - field.putClientProperty(FlatClientProperties.TEXT_FIELD_LEADING_ICON, new FlatSearchIcon()); - field.putClientProperty(FlatClientProperties.TEXT_FIELD_SHOW_CLEAR_BUTTON, true); - JToolBar toggles = new JToolBar(); - toggles.setFloatable(false); - toggles.setBorder(null); - toggles.setOpaque(false); - for (JToggleButton b : new JToggleButton[]{matchCase, wholeWord, regex}) { - b.addActionListener(e -> fireQueryChanged()); - toggles.add(b); - } - field.putClientProperty(FlatClientProperties.TEXT_FIELD_TRAILING_COMPONENT, toggles); - field.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void insertUpdate(DocumentEvent e) { - typing.restart(); - } - - @Override - public void removeUpdate(DocumentEvent e) { - typing.restart(); - } - - @Override - public void changedUpdate(DocumentEvent e) { - } - }); - - status.setFont(Theme.uiSmall()); - status.setForeground(Theme.chatSystem()); - JButton close = navButton(new Glyph(Glyph.CLOSE), "Close (Escape)"); - previous.addActionListener(e -> goPrevious()); - next.addActionListener(e -> goNext()); - close.addActionListener(e -> close()); - - JPanel controls = new JPanel(); - controls.setLayout(new BoxLayout(controls, BoxLayout.LINE_AXIS)); - controls.setBorder(new ScaledEmptyBorder(0, 6, 0, 0)); - controls.add(status); - controls.add(Box.createHorizontalStrut(UIScale.scale(4))); - controls.add(previous); - controls.add(next); - controls.add(close); - - leading.setLayout(new BoxLayout(leading, BoxLayout.LINE_AXIS)); - leading.setVisible(false); - add(leading, BorderLayout.WEST); - add(field, BorderLayout.CENTER); - add(controls, BorderLayout.EAST); - - bind(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), this::goNext); - bind(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0), this::goNext); - bind(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.SHIFT_DOWN_MASK), this::goPrevious); - bind(KeyStroke.getKeyStroke(KeyEvent.VK_F3, KeyEvent.SHIFT_DOWN_MASK), this::goPrevious); - bind(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), this::resetOrClose); - } - - /** Adds a view-specific control in front of the field; one that changes the query should call {@link #fireQueryChanged()}. */ - void addLeading(JComponent c) { - if (c instanceof AbstractButton b) { - b.setFocusable(false); - b.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON); - } - leading.add(c); - leading.setVisible(true); - } - - /** Adds the "show only matches" toggle: a funnel that turns from grey to the accent colour when on. */ - JToggleButton addFilterToggle(String tooltip) { - JToggleButton filter = new JToggleButton(new Glyph(Glyph.FILTER)); - filter.setToolTipText(tooltip); - filter.addActionListener(e -> fireQueryChanged()); - addLeading(filter); - addResettable(() -> !filter.isSelected(), () -> filter.setSelected(false)); - return filter; - } - - /** - * Lets Escape reset a view-specific option. {@code reset} only puts the option back; - * the bar re-runs the query itself afterwards. - */ - void addResettable(BooleanSupplier isDefault, Runnable reset) { - optionDefaults.add(isDefault); - optionResets.add(reset); - } - - private boolean isDefault() { - if (!field.getText().isEmpty() || matchCase.isSelected() || wholeWord.isSelected() || regex.isSelected()) { - return false; - } - for (BooleanSupplier d : optionDefaults) { - if (!d.getAsBoolean()) return false; - } - return true; - } - - private void resetOrClose() { - if (isDefault()) { - close(); - return; - } - field.setText(""); - matchCase.setSelected(false); - wholeWord.setSelected(false); - regex.setSelected(false); - for (Runnable r : optionResets) r.run(); - fireQueryChanged(); - } - - void setPlaceholder(String text) { - field.putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, text); - } - - /** Shows the bar (if hidden) and puts the cursor in the field with its text selected. */ - void open() { - if (!isVisible()) { - setVisible(true); - revalidate(); - } - field.requestFocusInWindow(); - field.selectAll(); - if (!field.getText().isEmpty()) fireQueryChanged(); - } - - void close() { - if (!isVisible()) return; - typing.stop(); - setVisible(false); - revalidate(); - listener.closed(); - } - - boolean isOpen() { - return isVisible(); - } - - TextQuery query() { - return isVisible() - ? new TextQuery(field.getText(), matchCase.isSelected(), wholeWord.isSelected(), regex.isSelected()) - : TextQuery.EMPTY; - } - - /** - * Shows where the view is among the matches, as "3 / 17". It keeps that shape even - * with no match or none selected (" / 0"), so the field does not change width as - * the count comes and goes while typing. - * - * @param position the 1-based match the view is on, or 0 for none - * @param more whether there are more matches than {@code total} - */ - void setCount(int position, int total, boolean more) { - showStatus((position > 0 ? String.valueOf(position) : " ") + " / " + total + (more ? "+" : ""), total == 0); - } - - /** No query, nothing to count. */ - void clearCount() { - showStatus("", false); - } - - private void showStatus(String text, boolean noMatch) { - status.setText(text); - status.setToolTipText(null); - field.putClientProperty(FlatClientProperties.OUTLINE, noMatch ? FlatClientProperties.OUTLINE_ERROR : null); - } - - void setNavigable(boolean navigable) { - previous.setEnabled(navigable); - next.setEnabled(navigable); - } - - /** Re-runs the query now, e.g. after an option changed. */ - void fireQueryChanged() { - typing.stop(); - TextQuery q = query(); - if (q.isInvalid()) { - setCount(0, 0, false); - status.setToolTipText(q.error()); - setNavigable(false); - } - listener.queryChanged(q); - } - - /** Stepping through matches acts on what is typed, even if the pause that would run it is still pending. */ - private void goNext() { - if (typing.isRunning()) fireQueryChanged(); - listener.next(); - } - - private void goPrevious() { - if (typing.isRunning()) fireQueryChanged(); - listener.previous(); - } - - private void bind(KeyStroke key, Runnable action) { - String name = "ts3-find-" + key; - getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(key, name); - getActionMap().put(name, new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - action.run(); - } - }); - } - - private static JToggleButton fieldToggle(String text, String tooltip) { - JToggleButton b = new JToggleButton(text); - b.setToolTipText(tooltip); - b.setFont(Theme.uiSmall()); - b.setFocusable(false); - b.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON); - b.setMargin(new Insets(1, 3, 1, 3)); - return b; - } - - private static JButton navButton(Glyph icon, String tooltip) { - JButton b = new JButton(icon); - b.setToolTipText(tooltip); - b.setFocusable(false); - b.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON); - return b; - } - - /** The bar's line icons, drawn in the button's own text colour so they follow the theme. */ - private static final class Glyph extends FlatAbstractIcon { - static final int UP = 0; - static final int DOWN = 1; - static final int CLOSE = 2; - static final int FILTER = 3; - - private final int shape; - - Glyph(int shape) { - super(shape == FILTER ? 14 : 12, shape == FILTER ? 14 : 12, null); - this.shape = shape; - } - - @Override - protected void paintIcon(Component c, Graphics2D g) { - if (!c.isEnabled()) g.setColor(UIManager.getColor("Label.disabledForeground")); - else if (shape == FILTER) g.setColor(((AbstractButton) c).isSelected() ? Theme.accent() : Theme.chatSystem()); - else g.setColor(c.getForeground()); - if (shape == FILTER) { - Path2D.Float funnel = new Path2D.Float(); - funnel.moveTo(1.5f, 2.5f); - funnel.lineTo(12.5f, 2.5f); - funnel.lineTo(8.25f, 7.5f); - funnel.lineTo(8.25f, 12f); - funnel.lineTo(5.75f, 10.75f); - funnel.lineTo(5.75f, 7.5f); - funnel.closePath(); - g.fill(funnel); - return; - } - g.setStroke(new BasicStroke(1.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); - Path2D.Float p = new Path2D.Float(); - switch (shape) { - case UP -> { - p.moveTo(2.5f, 8f); - p.lineTo(6f, 4.5f); - p.lineTo(9.5f, 8f); - } - case DOWN -> { - p.moveTo(2.5f, 4.5f); - p.lineTo(6f, 8f); - p.lineTo(9.5f, 4.5f); - } - default -> { - p.moveTo(3f, 3f); - p.lineTo(9f, 9f); - p.moveTo(9f, 3f); - p.lineTo(3f, 9f); - } - } - g.draw(p); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/FormPanel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/FormPanel.java deleted file mode 100644 index 380d13d..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/FormPanel.java +++ /dev/null @@ -1,178 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; - -import javax.swing.Box; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSeparator; -import javax.swing.JSlider; -import javax.swing.Scrollable; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.Rectangle; - -/** - * Base for a settings tab's field grid: follows the scroll pane's width instead of - * demanding its own preferred one, so rows stay inside the dialog instead of scrolling - * sideways. Also holds the small GridBagLayout helpers every such tab needs. - */ -class FormPanel extends JPanel implements Scrollable { - - static final int FIELD_WIDTH = 240; - static final int SLIDER_WIDTH = 200; - static final int MIN_FIELD_WIDTH = 60; - - FormPanel() { - this(true); - } - - /** @param padded {@code false} for a form embedded in another one, which pads it already */ - FormPanel(boolean padded) { - super(new GridBagLayout()); - if (padded) setBorder(new ScaledEmptyBorder(12, 12, 12, 12)); - } - - @Override - public Dimension getPreferredScrollableViewportSize() { - return getPreferredSize(); - } - - @Override - public int getScrollableUnitIncrement(Rectangle visible, int orientation, int direction) { - return 16; - } - - @Override - public int getScrollableBlockIncrement(Rectangle visible, int orientation, int direction) { - return visible.height; - } - - @Override - public boolean getScrollableTracksViewportWidth() { - return true; - } - - @Override - public boolean getScrollableTracksViewportHeight() { - return false; - } - - static GridBagConstraints gbc() { - GridBagConstraints c = new GridBagConstraints(); - c.insets = UIScale.scale(new Insets(4, 4, 4, 4)); - c.anchor = GridBagConstraints.WEST; - c.fill = GridBagConstraints.HORIZONTAL; - return c; - } - - /** A group heading: the title in bold, followed by a rule to the right edge. */ - static JComponent sectionHeader(String title) { - JPanel header = new JPanel(new GridBagLayout()); - JLabel label = new JLabel(title) { - @Override - public void updateUI() { - super.updateUI(); - setFont(getFont().deriveFont(Font.BOLD)); - } - }; - GridBagConstraints c = new GridBagConstraints(); - c.insets = UIScale.scale(new Insets(0, 0, 0, 8)); - header.add(label, c); - c.gridx = 1; - c.weightx = 1; - c.fill = GridBagConstraints.HORIZONTAL; - c.insets = new Insets(0, 0, 0, 0); - header.add(new JSeparator(), c); - return header; - } - - /** - * Adds a {@link #sectionHeader} spanning the grid at {@code row}, with space above it - * unless it is the first row; leaves {@code c} as it found it. - */ - static void addSection(JPanel p, GridBagConstraints c, int row, String title) { - Insets insets = c.insets; - int width = c.gridwidth; - c.gridx = 0; - c.gridy = row; - c.gridwidth = 2; - c.weightx = 0; - c.insets = UIScale.scale(new Insets(row == 0 ? 0 : 14, 0, 2, 0)); - p.add(sectionHeader(title), c); - c.insets = insets; - c.gridwidth = width; - } - - /** Adds a component spanning the whole grid at {@code row}, such as a check box. */ - static void addWide(JPanel p, GridBagConstraints c, int row, Component comp) { - int width = c.gridwidth; - c.gridx = 0; - c.gridy = row; - // No weight of its own: GridBag would hand part of it to the label column. - c.gridwidth = 2; - c.weightx = 0; - p.add(comp, c); - c.gridwidth = width; - } - - /** - * Pushes the rows above it to the top of a taller viewport, and gives the field column - * the spare width, which a form of only {@link #addWide} rows would otherwise centre. - */ - static void addFiller(JPanel p, GridBagConstraints c, int row) { - c.gridx = 1; - c.gridy = row; - c.gridwidth = 1; - c.weightx = 1; - c.weighty = 1; - p.add(Box.createGlue(), c); - c.weighty = 0; - } - - static void addRow(JPanel p, GridBagConstraints c, int row, Component label, Component field) { - c.gridx = 0; - c.gridy = row; - c.weightx = 0; - c.gridwidth = 1; - p.add(label, c); - c.gridx = 1; - c.weightx = 1; - p.add(field, c); - } - - /** - * Caps a field's preferred width and lets it shrink: long device names and wide sliders - * would otherwise force the form past the dialog's edge, where the scroll pane (which - * never scrolls horizontally) simply clips them. - */ - static void limitWidth(JComponent comp, int preferredWidth) { - int height = comp.getPreferredSize().height; - comp.setPreferredSize(new Dimension(UIScale.scale(preferredWidth), height)); - comp.setMinimumSize(new Dimension(UIScale.scale(MIN_FIELD_WIDTH), height)); - } - - static JPanel sliderWithLabel(JSlider slider, JLabel valueLabel) { - return sliderWithLabel(slider, valueLabel, 56); - } - - /** - * Pairs a slider with its value readout. The readout gets a fixed width wide enough for - * the longest value so the slider does not jump around as it is dragged. - */ - static JPanel sliderWithLabel(JSlider slider, JLabel valueLabel, int labelWidth) { - JPanel panel = new JPanel(new BorderLayout(UIScale.scale(6), 0)); - limitWidth(slider, SLIDER_WIDTH); - panel.add(slider, BorderLayout.CENTER); - valueLabel.setPreferredSize(new Dimension(UIScale.scale(labelWidth), valueLabel.getPreferredSize().height)); - panel.add(valueLabel, BorderLayout.EAST); - return panel; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/GiantPttWindow.java b/ts3-client/swing/src/main/java/com/ts3client/ui/GiantPttWindow.java deleted file mode 100644 index f72aef4..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/GiantPttWindow.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.UIScale; - -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JFrame; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.function.BooleanSupplier; -import java.util.function.Consumer; - -/** - * A resizable window that is one big push-to-talk button. Pressing it transmits in any - * input mode, past the voice-activation gate. - */ -final class GiantPttWindow extends JDialog { - - private static final Color IDLE = new Color(0x1C, 0x6F, 0xB8); - private static final Color TALKING = new Color(0x2E, 0x9B, 0xF0); - - private final Consumer transmit; - private final BooleanSupplier talking; - private final Pad pad = new Pad(); - private boolean pressed; - - /** - * @param transmit forces transmission on the server holding the microphone while given {@code true} - * @param talking whether we are talking on that server, as it reports - */ - GiantPttWindow(JFrame owner, Consumer transmit, BooleanSupplier talking) { - super(owner, "Giant PTT", false); - this.transmit = transmit; - this.talking = talking; - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - setContentPane(pad); - pad.addMouseListener(new MouseAdapter() { - @Override - public void mousePressed(MouseEvent e) { - press(true); - } - - @Override - public void mouseReleased(MouseEvent e) { - press(false); - } - }); - addWindowListener(new WindowAdapter() { - @Override - public void windowDeactivated(WindowEvent e) { - press(false); - } - - @Override - public void windowClosed(WindowEvent e) { - press(false); - } - }); - pad.setPreferredSize(new Dimension(UIScale.scale(360), UIScale.scale(360))); - pack(); - setLocationRelativeTo(owner); - } - - /** Our talking state changed on some server. */ - void refresh() { - pad.repaint(); - } - - private void press(boolean down) { - if (pressed == down) return; - pressed = down; - transmit.accept(down); - pad.repaint(); - } - - private final class Pad extends JComponent { - - @Override - protected void paintComponent(Graphics g) { - Graphics2D g2 = (Graphics2D) g.create(); - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - g2.setColor(Theme.windowBg()); - g2.fillRect(0, 0, getWidth(), getHeight()); - - boolean lit = pressed || talking.getAsBoolean(); - int margin = UIScale.scale(12); - int arc = UIScale.scale(32); - g2.setColor(lit ? TALKING : IDLE); - g2.fillRoundRect(margin, margin, getWidth() - 2 * margin, getHeight() - 2 * margin, arc, arc); - - String text = lit ? "Talking…" : "Hold to talk"; - float size = Math.max(UIScale.scale(12f), Math.min(getWidth() / 8f, getHeight() / 4f)); - g2.setFont(Theme.uiFont().deriveFont(Font.BOLD, size)); - FontMetrics fm = g2.getFontMetrics(); - g2.setColor(Color.WHITE); - g2.drawString(text, (getWidth() - fm.stringWidth(text)) / 2, - (getHeight() - fm.getHeight()) / 2 + fm.getAscent()); - g2.dispose(); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/GroupIcons.java b/ts3-client/swing/src/main/java/com/ts3client/ui/GroupIcons.java deleted file mode 100644 index ea406ed..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/GroupIcons.java +++ /dev/null @@ -1,140 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.net.Group; -import com.ts3client.net.IconRepository; - -import javax.swing.Icon; -import javax.swing.ImageIcon; -import java.awt.Component; -import java.awt.Graphics; -import java.awt.Image; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Turns the {@link IconRepository}'s icon bytes into Swing icons for one server's - * groups, caching the decoded images. Icons that still have to be downloaded simply - * do not render yet; the repository repaints the view once they arrive. - */ -public final class GroupIcons { - - /** Tree rows are 16×16 like TeamSpeak's own icon set. */ - private static final int SIZE = 16; - - private static final Map DISK_CACHED = new ConcurrentHashMap<>(); - - private final IconRepository repository; - private final Map decoded = new ConcurrentHashMap<>(); - - public GroupIcons(IconRepository repository) { - this.repository = repository; - } - - /** @return the group's icon, or {@code null} if it has none or it is not loaded yet */ - public ImageIcon iconOf(Group group) { - if (group == null || group.iconId == 0) return null; - return icon(group.iconId); - } - - public ImageIcon icon(long iconId) { - if (iconId == 0) return null; - ImageIcon themed = themed(iconId); - if (themed != null) return themed; - - ImageIcon cached = decoded.get(iconId); - if (cached != null) return cached; - - ImageIcon icon = decode(repository.get(iconId)); - if (icon != null) decoded.put(iconId, icon); - return icon; - } - - /** - * An icon from the client's own cache, without a server to fetch it from, as - * bookmarks show their server's. - * - * @return the icon, or {@code null} when it has never been downloaded - */ - public static ImageIcon cached(long iconId) { - if (iconId == 0) return null; - ImageIcon themed = themed(iconId); - if (themed != null) return themed; - ImageIcon icon = DISK_CACHED.get(iconId); - if (icon != null) return icon; - icon = decode(IconRepository.cached(iconId)); - if (icon != null) DISK_CACHED.put(iconId, icon); - return icon; - } - - /** - * TeamSpeak's default group icons belong to the icon pack, which draws them in its - * own style; only server-uploaded icons come off the wire. The theme keeps its own - * cache, so those are not cached again here. - */ - private static ImageIcon themed(long iconId) { - if (iconId <= 0 || iconId > IconRepository.MAX_BUNDLED_ID) return null; - return IconTheme.icon("GROUP_" + iconId, UIScale.scale(SIZE)); - } - - private static ImageIcon decode(byte[] data) { - if (data == null) return null; - ImageIcon icon = new ImageIcon(data); - if (icon.getIconWidth() <= 0) return null; - int size = UIScale.scale(SIZE); - if (icon.getIconWidth() != size || icon.getIconHeight() != size) { - icon = new ImageIcon(icon.getImage().getScaledInstance(size, size, Image.SCALE_SMOOTH)); - } - return icon; - } - - /** Collects the icons of a client's server groups plus its channel group, in display order. */ - public List iconsOf(List serverGroups, Group channelGroup) { - List icons = new ArrayList<>(); - for (Group g : serverGroups) { - ImageIcon icon = iconOf(g); - if (icon != null) icons.add(icon); - } - ImageIcon channelIcon = iconOf(channelGroup); - if (channelIcon != null) icons.add(channelIcon); - return icons; - } - - /** Lays several icons out in a row, so a single tree cell can show a badge strip. */ - public static final class Row implements Icon { - - private static final int GAP = 2; - - private final List icons; - - public Row(List icons) { - this.icons = icons; - } - - @Override - public void paintIcon(Component c, Graphics g, int x, int y) { - int offset = x; - for (Icon icon : icons) { - icon.paintIcon(c, g, offset, y + (getIconHeight() - icon.getIconHeight()) / 2); - offset += icon.getIconWidth() + UIScale.scale(GAP); - } - } - - @Override - public int getIconWidth() { - int width = 0; - int gap = UIScale.scale(GAP); - for (Icon icon : icons) width += icon.getIconWidth() + gap; - return Math.max(0, width - gap); - } - - @Override - public int getIconHeight() { - int height = 0; - for (Icon icon : icons) height = Math.max(height, icon.getIconHeight()); - return height; - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/HostButtonView.java b/ts3-client/swing/src/main/java/com/ts3client/ui/HostButtonView.java deleted file mode 100644 index 0395dfa..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/HostButtonView.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.net.HostButton; -import com.ts3client.net.PictureDownloads; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.SwingUtilities; -import java.awt.Image; -import java.io.File; -import java.util.Objects; - -/** - * The server's host button in the toolbar's corner: its own picture, fitted to the - * toolbar's height, or TeamSpeak's host button icon while there is none (yet). - */ -final class HostButtonView extends JButton { - - /** Keeps a banner-shaped picture from crowding out the rest of the toolbar. */ - private static final int MAX_ASPECT = 6; - - private final PictureDownloads pictures; - private final Runnable onPictureLoaded = () -> SwingUtilities.invokeLater(this::refreshIcon); - private HostButton shown; - - HostButtonView(PictureDownloads pictures) { - this.pictures = pictures; - setVisible(false); - addActionListener(e -> { - if (shown != null && !shown.url().isEmpty()) Links.open(shown.url(), this); - }); - } - - /** @param button the selected server's, or {@code null} to hide it */ - void show(HostButton button) { - if (Objects.equals(button, shown)) return; - shown = button; - setVisible(button != null); - if (button == null) return; - setToolTipText(!button.tooltip().isEmpty() ? button.tooltip() : button.url().isEmpty() ? null : button.url()); - refreshIcon(); - } - - @Override - public void addNotify() { - super.addNotify(); - pictures.addListener(onPictureLoaded); - } - - @Override - public void removeNotify() { - pictures.removeListener(onPictureLoaded); - super.removeNotify(); - } - - private void refreshIcon() { - if (shown == null) return; - ImageIcon picture = shown.gfxUrl().isEmpty() ? null : picture(pictures.get(shown.gfxUrl())); - setIcon(picture != null ? picture : Icons.of("HOSTER_BUTTON", UIScale.scale(IconTheme.TOOLBAR_SIZE))); - } - - private static ImageIcon picture(File file) { - if (file == null) return null; - ImageIcon icon = new ImageIcon(file.getPath()); - int w = icon.getIconWidth(); - int h = icon.getIconHeight(); - if (w <= 0 || h <= 0) return null; - int height = UIScale.scale(IconTheme.TOOLBAR_SIZE); - int width = Math.min(Math.max(1, Math.round((float) w * height / h)), height * MAX_ASPECT); - if (w == width && h == height) return icon; - return new ImageIcon(icon.getImage().getScaledInstance(width, height, Image.SCALE_SMOOTH)); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/HotkeyActions.java b/ts3-client/swing/src/main/java/com/ts3client/ui/HotkeyActions.java deleted file mode 100644 index e3b0f94..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/HotkeyActions.java +++ /dev/null @@ -1,170 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.hotkey.Hotkey; -import com.ts3client.hotkey.HotkeyEngine; - -import javax.swing.SwingUtilities; -import java.util.List; - -/** - * Carries a fired hotkey out on the client. - * - *

    Activations arrive on the input hook's thread, so everything is handed to the - * event dispatch thread first. Which connections an action reaches is the binding's - * "on active server" flag: set, only the selected tab; clear, every connected one. - */ -final class HotkeyActions implements HotkeyEngine.Handler { - - /** How much one press of the master-volume hotkeys moves the slider. */ - private static final double VOLUME_STEP = 0.05; - - private final MainFrame frame; - /** Latched push-to-talk, driven by the "Toggle Push-to-Talk" action. */ - private boolean pttLatched; - - HotkeyActions(MainFrame frame) { - this.frame = frame; - } - - @Override - public void onHotkey(Hotkey hotkey, boolean active) { - SwingUtilities.invokeLater(() -> perform(hotkey, active)); - } - - private void perform(Hotkey hotkey, boolean active) { - List targets = frame.hotkeyTargets(hotkey.activeServerOnly); - switch (hotkey.action) { - case CONNECT_CURRENT_TAB -> frame.connectBookmark(hotkey.argument, false); - case CONNECT_NEW_TAB -> frame.connectBookmark(hotkey.argument, true); - case DISCONNECT_CURRENT -> { - ServerTab tab = frame.selectedTab(); - if (tab != null) tab.session().disconnect(); - } - case DISCONNECT_ALL -> { - for (ServerTab tab : frame.allTabs()) tab.session().disconnect(); - } - - case MIC_ACTIVATE -> frame.moveMicrophoneToSelectedTab(); - case MIC_MUTE -> setMicMuted(targets, true); - case MIC_UNMUTE -> setMicMuted(targets, false); - case MIC_TOGGLE -> setMicMuted(targets, !anyMicMuted(targets)); - - case MIC_LOCAL_MUTE -> setMicLocalMuted(targets, true); - case MIC_LOCAL_UNMUTE -> setMicLocalMuted(targets, false); - case MIC_LOCAL_TOGGLE -> setMicLocalMuted(targets, !anyMicLocalMuted(targets)); - - case SPEAKER_MUTE -> setDeafened(targets, true); - case SPEAKER_UNMUTE -> setDeafened(targets, false); - case SPEAKER_TOGGLE -> setDeafened(targets, !anyDeafened(targets)); - - case AWAY_SET -> setAway(targets, true, ""); - case AWAY_ONLINE -> setAway(targets, false, ""); - case AWAY_TOGGLE -> setAway(targets, !anyAway(targets), ""); - case AWAY_TOGGLE_WITH_MESSAGE -> setAway(targets, !anyAway(targets), hotkey.argument); - - case COMMANDER_ACTIVATE -> setCommander(targets, true); - case COMMANDER_DEACTIVATE -> setCommander(targets, false); - case COMMANDER_TOGGLE -> setCommander(targets, !anyCommander(targets)); - - // Momentary: the engine reports the release too, so the key simply holds it open. - case PTT_ACTIVATE -> frame.setPushToTalk(active || pttLatched); - case PTT_DEACTIVATE -> { - pttLatched = false; - frame.setPushToTalk(false); - } - case PTT_TOGGLE -> { - pttLatched = !pttLatched; - frame.setPushToTalk(pttLatched); - } - - case CHANNEL_SWITCH -> { - for (ServerTab tab : targets) tab.session().joinChannelPath(hotkey.argument); - } - case SERVER_TAB_SELECT -> frame.selectTabNumber(parseIndex(hotkey.argument)); - case SERVER_TAB_NEXT -> frame.stepTab(1); - case SERVER_TAB_PREVIOUS -> frame.stepTab(-1); - - case SOUND_MUTE -> frame.setSoundsMuted(true); - case SOUND_UNMUTE -> frame.setSoundsMuted(false); - case SOUND_TOGGLE -> frame.setSoundsMuted(!frame.areSoundsMuted()); - - case VOLUME_INCREASE -> frame.adjustMasterVolume(VOLUME_STEP); - case VOLUME_DECREASE -> frame.adjustMasterVolume(-VOLUME_STEP); - - case NICKNAME_CHANGE -> frame.changeNickname(hotkey.argument); - - case RECORDING_START -> startRecording(targets, false); - case RECORDING_START_MULTITRACK -> startRecording(targets, true); - case RECORDING_STOP -> { - for (ServerTab tab : targets) tab.session().stopRecording(); - } - - case FILEBROWSER -> frame.browseCurrentChannel(); - case SKIN_RELOAD -> frame.reloadSkin(); - case BRING_TO_FRONT -> frame.bringToFront(); - case SEND_TO_BACK -> frame.sendToBack(); - - default -> { - // Listed for completeness in the action catalogue, but not implemented here. - } - } - } - - private void startRecording(List targets, boolean multitrack) { - for (ServerTab tab : targets) frame.recordings().startNow(tab.session(), multitrack); - } - - private void setMicMuted(List targets, boolean muted) { - for (ServerTab tab : targets) tab.session().setMicMuted(muted); - frame.refreshAfterHotkey(); - } - - private void setMicLocalMuted(List targets, boolean muted) { - for (ServerTab tab : targets) tab.session().setMicLocalMuted(muted); - frame.refreshAfterHotkey(); - } - - private void setDeafened(List targets, boolean deaf) { - for (ServerTab tab : targets) tab.session().setDeafened(deaf); - frame.refreshAfterHotkey(); - } - - private void setAway(List targets, boolean away, String message) { - for (ServerTab tab : targets) tab.session().setAway(away, message == null ? "" : message); - frame.refreshAfterHotkey(); - } - - private void setCommander(List targets, boolean commander) { - for (ServerTab tab : targets) tab.session().setCommander(commander); - frame.refreshAfterHotkey(); - } - - private static boolean anyMicMuted(List tabs) { - return tabs.stream().anyMatch(t -> t.session().isMicMuted()); - } - - private static boolean anyMicLocalMuted(List tabs) { - return tabs.stream().anyMatch(t -> t.session().isMicLocalMuted()); - } - - private static boolean anyDeafened(List tabs) { - return tabs.stream().anyMatch(t -> t.session().isDeafened()); - } - - private static boolean anyAway(List tabs) { - return tabs.stream().anyMatch(t -> t.session().isAway()); - } - - private static boolean anyCommander(List tabs) { - return tabs.stream().anyMatch(t -> t.session().isCommander()); - } - - /** @return the 1-based tab number in the argument, or 1 when it is not a number */ - private static int parseIndex(String argument) { - try { - return Math.max(1, Integer.parseInt(argument.trim())); - } catch (RuntimeException e) { - return 1; - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/HotkeyArguments.java b/ts3-client/swing/src/main/java/com/ts3client/ui/HotkeyArguments.java deleted file mode 100644 index c456b72..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/HotkeyArguments.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.hotkey.HotkeyAction; - -import java.util.List; - -/** - * Supplies the concrete values an action's parameter can take — the bookmarks, sound - * packs and channels the hotkey tree hangs under an action as its leaves, so a binding - * reads as "Sounds / Activate Soundpack / Default Sound Pack (Male)". - */ -interface HotkeyArguments { - - /** @return the choices for this action, or an empty list when it is free-form */ - List choices(HotkeyAction action); -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/HotkeyDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/HotkeyDialog.java deleted file mode 100644 index eccbddd..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/HotkeyDialog.java +++ /dev/null @@ -1,386 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.hotkey.Hotkey; -import com.ts3client.hotkey.HotkeyAction; -import com.ts3client.hotkey.HotkeyCombo; -import com.ts3client.hotkey.HotkeyEngine; - -import javax.swing.Box; -import javax.swing.DefaultListCellRenderer; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextField; -import javax.swing.JTree; -import javax.swing.SwingUtilities; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeCellRenderer; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.Window; -import java.util.List; - -/** - * Adds or edits one hotkey, following the official client's dialog: pick the action - * from the tree — category, action group, action, and where the action takes one, the - * concrete bookmark, sound pack or channel — press the key combination to bind, and - * choose the edge it triggers on and whether it applies to the active server only. - */ -final class HotkeyDialog extends JDialog { - - /** - * A tree node: a category or group heading ({@code action == null}), an action, or - * one of the values an action's parameter can take ({@code argument != null}). - */ - private record Node(HotkeyAction action, String argument, String label) { - - static Node heading(String label) { - return new Node(null, null, label); - } - - static Node of(HotkeyAction action) { - return new Node(action, null, action.label()); - } - - static Node value(HotkeyAction action, String argument) { - return new Node(action, argument, argument); - } - - boolean isHeading() { - return action == null; - } - - @Override - public String toString() { - return label; - } - } - - private final HotkeyService service; - private final Hotkey hotkey; - - private final DefaultMutableTreeNode root = new DefaultMutableTreeNode("Actions"); - private final DefaultTreeModel treeModel = new DefaultTreeModel(root); - private final JTree tree = new JTree(treeModel); - private final JCheckBox advancedCheck = new JCheckBox("Show advanced actions"); - private final JButton keyButton = new JButton(); - private final JComboBox triggerCombo = new JComboBox<>(Hotkey.Trigger.values()); - private final JCheckBox activeServerCheck = new JCheckBox("On active server"); - private final JLabel argumentLabel = new JLabel(); - private final JTextField argumentField = new JTextField(); - private final JLabel hint = new JLabel(); - - private HotkeyCombo combo; - private boolean recording; - private boolean confirmed; - - HotkeyDialog(Window owner, HotkeyService service, Hotkey existing) { - // Any window may open this: the options dialog's hotkey tab as much as a frame. - super(owner, existing == null ? "Add hotkey" : "Edit hotkey", ModalityType.APPLICATION_MODAL); - this.service = service; - this.hotkey = existing == null ? new Hotkey() : existing.copy(); - this.combo = hotkey.combo; - - advancedCheck.setSelected(hotkey.action != null && hotkey.action.advanced()); - advancedCheck.addActionListener(e -> rebuildTree()); - tree.setRootVisible(false); - tree.setShowsRootHandles(true); - tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); - tree.setCellRenderer(new NodeRenderer()); - tree.addTreeSelectionListener(e -> selectionChanged()); - rebuildTree(); - - keyButton.addActionListener(e -> startRecording()); - triggerCombo.setRenderer(new DefaultListCellRenderer() { - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, - boolean selected, boolean focused) { - super.getListCellRendererComponent(list, value, index, selected, focused); - if (value instanceof Hotkey.Trigger t) setText(t.label()); - return this; - } - }); - triggerCombo.setSelectedItem(hotkey.trigger); - activeServerCheck.setSelected(hotkey.activeServerOnly); - argumentField.setText(hotkey.argument == null ? "" : hotkey.argument); - hint.setFont(hint.getFont().deriveFont(Font.ITALIC, hint.getFont().getSize2D() - 1f)); - - getContentPane().setLayout(new BorderLayout(UIScale.scale(8), UIScale.scale(8))); - ((JComponent) getContentPane()).setBorder(new ScaledEmptyBorder(8, 8, 8, 8)); - getContentPane().add(buildActionPane(), BorderLayout.CENTER); - getContentPane().add(buildForm(), BorderLayout.SOUTH); - - updateKeyButton(); - updateForAction(); - Dialogs.closeOnEscape(this, this::cancel); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - setSize(UIScale.scale(new Dimension(470, 560))); - setLocationRelativeTo(owner); - } - - private JPanel buildActionPane() { - JPanel p = new JPanel(new BorderLayout(0, UIScale.scale(4))); - p.add(new JLabel("Action:"), BorderLayout.NORTH); - p.add(new JScrollPane(tree), BorderLayout.CENTER); - p.add(advancedCheck, BorderLayout.SOUTH); - return p; - } - - private JPanel buildForm() { - JPanel p = new JPanel(new GridBagLayout()); - GridBagConstraints c = new GridBagConstraints(); - c.insets = UIScale.scale(new Insets(3, 3, 3, 3)); - c.anchor = GridBagConstraints.WEST; - c.fill = GridBagConstraints.HORIZONTAL; - - int row = 0; - addRow(p, c, row++, new JLabel("Hotkey:"), keyButton); - addRow(p, c, row++, argumentLabel, argumentField); - addRow(p, c, row++, new JLabel("Trigger:"), triggerCombo); - - c.gridx = 1; - c.gridy = row++; - p.add(activeServerCheck, c); - c.gridx = 0; - c.gridy = row++; - c.gridwidth = 2; - p.add(hint, c); - - JPanel buttons = new JPanel(); - JButton ok = new JButton("OK"); - JButton cancel = new JButton("Cancel"); - ok.addActionListener(e -> confirm()); - cancel.addActionListener(e -> cancel()); - buttons.add(Box.createHorizontalGlue()); - buttons.add(ok); - buttons.add(cancel); - c.gridy = row; - p.add(buttons, c); - getRootPane().setDefaultButton(ok); - return p; - } - - private static void addRow(JPanel p, GridBagConstraints c, int row, JComponent left, JComponent right) { - c.gridwidth = 1; - c.gridx = 0; - c.gridy = row; - c.weightx = 0; - p.add(left, c); - c.gridx = 1; - c.weightx = 1; - p.add(right, c); - } - - /** - * Builds category → group → action → value, collapsing the groups TS3 leaves - * unnamed so their actions sit directly under the category. - */ - private void rebuildTree() { - boolean advanced = advancedCheck.isSelected(); - root.removeAllChildren(); - for (HotkeyAction.Category category : HotkeyAction.Category.values()) { - List actions = HotkeyAction.of(category, advanced); - if (actions.isEmpty()) continue; - DefaultMutableTreeNode categoryNode = - new DefaultMutableTreeNode(Node.heading(category.label())); - DefaultMutableTreeNode groupNode = null; - String groupName = null; - for (HotkeyAction action : actions) { - DefaultMutableTreeNode parent = categoryNode; - if (!action.group().isEmpty()) { - if (groupNode == null || !action.group().equals(groupName)) { - groupName = action.group(); - groupNode = new DefaultMutableTreeNode(Node.heading(groupName)); - categoryNode.add(groupNode); - } - parent = groupNode; - } - DefaultMutableTreeNode actionNode = new DefaultMutableTreeNode(Node.of(action)); - parent.add(actionNode); - for (String value : service.argumentChoices(action)) { - actionNode.add(new DefaultMutableTreeNode(Node.value(action, value))); - } - } - root.add(categoryNode); - } - treeModel.reload(); - // Categories open, groups closed: the whole action set at a glance, as in TS3. - for (int i = 0; i < root.getChildCount(); i++) { - tree.expandPath(new TreePath(((DefaultMutableTreeNode) root.getChildAt(i)).getPath())); - } - selectCurrent(); - } - - /** Reveals and selects the node matching the binding being edited. */ - private void selectCurrent() { - if (hotkey.action == null) return; - DefaultMutableTreeNode match = null; - var nodes = root.depthFirstEnumeration(); - while (nodes.hasMoreElements()) { - DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodes.nextElement(); - if (!(node.getUserObject() instanceof Node n) || n.action() != hotkey.action) continue; - boolean sameArgument = n.argument() != null && n.argument().equals(hotkey.argument); - if (sameArgument) { - match = node; - break; - } - if (n.argument() == null && match == null) match = node; - } - if (match == null) return; - TreePath path = new TreePath(match.getPath()); - tree.setSelectionPath(path); - SwingUtilities.invokeLater(() -> tree.scrollPathToVisible(path)); - } - - private void selectionChanged() { - if (!(tree.getLastSelectedPathComponent() instanceof DefaultMutableTreeNode node) - || !(node.getUserObject() instanceof Node selected)) { - return; - } - if (selected.isHeading()) { - // Headings only structure the tree; keep the action that was chosen before. - tree.clearSelection(); - selectCurrent(); - return; - } - hotkey.action = selected.action(); - if (selected.argument() != null) argumentField.setText(selected.argument()); - updateForAction(); - } - - /** Syncs the form to the selected action: parameter row, trigger, scope and hint. */ - private void updateForAction() { - HotkeyAction action = hotkey.action; - boolean takesArgument = action != null && action.argument() != HotkeyAction.Argument.NONE; - argumentLabel.setText(takesArgument ? argumentLabel(action) : ""); - argumentLabel.setVisible(takesArgument); - argumentField.setVisible(takesArgument); - - boolean momentary = action != null && action.momentary(); - triggerCombo.setEnabled(!momentary); - activeServerCheck.setEnabled(action != null && action.category() != HotkeyAction.Category.MISC); - - if (action != null && !action.supported()) { - hint.setText("This action is part of TeamSpeak's hotkey set but is not implemented yet."); - } else if (momentary) { - hint.setText("Held down: the action lasts as long as the hotkey is pressed."); - } else { - hint.setText(service.isRunning() ? " " : service.status()); - } - } - - private static String argumentLabel(HotkeyAction action) { - return switch (action.argument()) { - case BOOKMARK -> "Bookmark:"; - case CHANNEL -> "Channel path:"; - case PROFILE -> "Profile:"; - default -> "Parameter:"; - }; - } - - private void startRecording() { - if (recording) return; - if (!service.isRunning()) { - hint.setText(service.status()); - return; - } - recording = true; - keyButton.setText("Press hotkey combination…"); - service.record(new HotkeyEngine.Recorder() { - @Override - public void onRecording(HotkeyCombo partial) { - SwingUtilities.invokeLater(() -> keyButton.setText(service.display(partial) + "…")); - } - - @Override - public void onRecorded(HotkeyCombo recorded) { - SwingUtilities.invokeLater(() -> { - combo = recorded; - stopRecording(); - }); - } - }); - } - - private void stopRecording() { - if (!recording) return; - recording = false; - service.stopRecording(); - updateKeyButton(); - } - - private void updateKeyButton() { - keyButton.setText(combo == null || combo.isEmpty() - ? "No hotkey assigned" : service.display(combo)); - } - - private void confirm() { - stopRecording(); - if (hotkey.action == null || combo == null || combo.isEmpty()) { - hint.setText("Pick an action and press a key combination first."); - return; - } - if (!hotkey.action.supported()) { - hint.setText("This action is not implemented yet — pick another one."); - return; - } - hotkey.combo = combo; - hotkey.trigger = (Hotkey.Trigger) triggerCombo.getSelectedItem(); - hotkey.activeServerOnly = activeServerCheck.isSelected(); - hotkey.argument = argumentField.getText().trim(); - confirmed = true; - dispose(); - } - - private void cancel() { - stopRecording(); - dispose(); - } - - boolean isConfirmed() { - return confirmed; - } - - Hotkey result() { - return hotkey; - } - - /** Draws headings in bold and greys out the actions this client cannot perform. */ - private static final class NodeRenderer extends DefaultTreeCellRenderer { - @Override - public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, - boolean expanded, boolean leaf, int row, - boolean focused) { - super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, focused); - setIcon(null); - if (!(value instanceof DefaultMutableTreeNode node) - || !(node.getUserObject() instanceof Node n)) { - return this; - } - if (n.isHeading()) { - setFont(getFont().deriveFont(Font.BOLD)); - setToolTipText(null); - } else { - setEnabled(n.action().supported()); - setToolTipText(n.action().supported() ? null : "Not implemented by this client"); - } - return this; - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/HotkeyService.java b/ts3-client/swing/src/main/java/com/ts3client/ui/HotkeyService.java deleted file mode 100644 index 40dfb99..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/HotkeyService.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.hotkey.GlobalInputHook; -import com.ts3client.hotkey.Hotkey; -import com.ts3client.hotkey.HotkeyAction; -import com.ts3client.hotkey.HotkeyCombo; -import com.ts3client.hotkey.HotkeyEngine; -import com.ts3client.hotkey.HotkeyKey; -import com.ts3client.hotkey.Hotkeys; -import com.ts3client.hotkey.desktop.DesktopInputHooks; - -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -/** - * Owns the hotkey machinery for the UI: the stored bindings, the matching engine and - * the platform input hook they are fed from. Everything the dialogs need — recording a - * combination, naming keys, telling the user why hotkeys are dead — goes through here. - */ -final class HotkeyService { - - private final Hotkeys hotkeys = Hotkeys.load(); - private final HotkeyEngine engine; - private final GlobalInputHook hook; - private final HotkeyArguments arguments; - private final List keyPressListeners = new CopyOnWriteArrayList<>(); - - HotkeyService(HotkeyEngine.Handler handler, HotkeyArguments arguments) { - this.arguments = arguments; - engine = new HotkeyEngine(hotkeys, handler); - hook = DesktopInputHooks.start((key, pressed) -> { - engine.onInput(key, pressed); - if (pressed && key.device() == HotkeyKey.Device.KEYBOARD) { - for (Runnable l : keyPressListeners) l.run(); - } - }); - } - - /** - * Runs {@code l} on the input hook's thread for every key going down anywhere on the - * system, which is what typing attenuation listens for. Keep it cheap. - */ - void addKeyPressListener(Runnable l) { - keyPressListeners.add(l); - } - - void removeKeyPressListener(Runnable l) { - keyPressListeners.remove(l); - } - - /** The values this action's parameter can take right now, for the action tree. */ - List argumentChoices(HotkeyAction action) { - if (arguments == null || action.argument() == HotkeyAction.Argument.NONE) return List.of(); - try { - return arguments.choices(action); - } catch (RuntimeException e) { - return List.of(); - } - } - - List all() { - return hotkeys.all(); - } - - void replaceAll(List updated) { - engine.releaseAll(); - hotkeys.replaceAll(updated); - hotkeys.save(); - } - - /** The binding for an action with no argument, or {@code null} when unbound. */ - Hotkey find(HotkeyAction action) { - for (Hotkey h : hotkeys.all()) { - if (h.action == action) return h; - } - return null; - } - - boolean isRunning() { - return hook.isRunning(); - } - - /** One line for the options dialog: either working, or why it is not. */ - String status() { - return hook.isRunning() - ? "Global hotkeys are active." - : "Global hotkeys are unavailable (" + hook.unavailableReason() + ")."; - } - - String display(HotkeyCombo combo) { - return combo == null ? "No hotkey assigned" : combo.display(this::keyName); - } - - private String keyName(HotkeyKey key) { - return hook.keyName(key); - } - - /** Captures the next combination instead of firing bindings; see {@link #stopRecording()}. */ - void record(HotkeyEngine.Recorder recorder) { - engine.record(recorder); - } - - void stopRecording() { - engine.stopRecording(); - } - - void dispose() { - engine.releaseAll(); - hook.close(); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/HotkeysPanel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/HotkeysPanel.java deleted file mode 100644 index 9f38cf8..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/HotkeysPanel.java +++ /dev/null @@ -1,167 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.hotkey.Hotkey; - -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.ListSelectionModel; -import javax.swing.SwingUtilities; -import javax.swing.table.AbstractTableModel; -import java.awt.BorderLayout; -import java.awt.Font; -import java.awt.Window; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.List; - -/** - * The options dialog's hotkey tab: the list of bindings with the buttons to add, edit - * and remove them. Edits happen on a working copy and only reach the running engine - * when the dialog is applied. - */ -final class HotkeysPanel extends JPanel { - - private static final String[] COLUMNS = {"Action", "Hotkey", "Trigger", "Active server", "On"}; - - private final HotkeyService service; - private final List working = new ArrayList<>(); - private final Model model = new Model(); - private final JTable table = new JTable(model); - - HotkeysPanel(HotkeyService service) { - super(new BorderLayout(UIScale.scale(6), UIScale.scale(6))); - this.service = service; - setBorder(new ScaledEmptyBorder(8, 8, 8, 8)); - - for (Hotkey h : service.all()) working.add(h.copy()); - - table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - table.setRowHeight(table.getRowHeight() + UIScale.scale(4)); - table.getColumnModel().getColumn(0).setPreferredWidth(UIScale.scale(240)); - table.getColumnModel().getColumn(1).setPreferredWidth(UIScale.scale(150)); - table.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (e.getClickCount() == 2) edit(); - } - }); - - JButton add = new JButton("Add…"); - JButton edit = new JButton("Edit…"); - JButton remove = new JButton("Remove"); - add.addActionListener(e -> add()); - edit.addActionListener(e -> edit()); - remove.addActionListener(e -> remove()); - - JPanel buttons = new JPanel(); - buttons.add(add); - buttons.add(edit); - buttons.add(remove); - - JLabel status = new JLabel(service.status()); - status.setFont(status.getFont().deriveFont(Font.ITALIC, status.getFont().getSize2D() - 1f)); - - add(new JScrollPane(table), BorderLayout.CENTER); - JPanel south = new JPanel(new BorderLayout()); - south.add(buttons, BorderLayout.WEST); - south.add(status, BorderLayout.SOUTH); - add(south, BorderLayout.SOUTH); - } - - private void add() { - HotkeyDialog dlg = new HotkeyDialog(owner(), service, null); - dlg.setVisible(true); - if (!dlg.isConfirmed()) return; - working.add(dlg.result()); - model.fireTableDataChanged(); - } - - private void edit() { - int row = table.getSelectedRow(); - if (row < 0) return; - HotkeyDialog dlg = new HotkeyDialog(owner(), service, working.get(row)); - dlg.setVisible(true); - if (!dlg.isConfirmed()) return; - working.set(row, dlg.result()); - model.fireTableRowsUpdated(row, row); - } - - private void remove() { - int row = table.getSelectedRow(); - if (row < 0) return; - working.remove(row); - model.fireTableDataChanged(); - } - - private Window owner() { - return SwingUtilities.getWindowAncestor(this); - } - - /** Commits the edited list to the engine and to disk. */ - void apply() { - service.replaceAll(working); - } - - /** Picks the stored bindings up again after something else changed them. */ - void reload() { - working.clear(); - for (Hotkey h : service.all()) working.add(h.copy()); - model.fireTableDataChanged(); - } - - private final class Model extends AbstractTableModel { - - @Override - public int getRowCount() { - return working.size(); - } - - @Override - public int getColumnCount() { - return COLUMNS.length; - } - - @Override - public String getColumnName(int column) { - return COLUMNS[column]; - } - - @Override - public Class getColumnClass(int column) { - return column >= 3 ? Boolean.class : String.class; - } - - @Override - public boolean isCellEditable(int row, int column) { - return column == 4 || (column == 3 && working.get(row).isServerScoped()); - } - - @Override - public Object getValueAt(int row, int column) { - Hotkey h = working.get(row); - return switch (column) { - case 0 -> h.path(); - case 1 -> service.display(h.combo); - case 2 -> h.action.momentary() ? "While held" : h.trigger.label(); - case 3 -> h.isServerScoped() && h.activeServerOnly; - default -> h.enabled; - }; - } - - @Override - public void setValueAt(Object value, int row, int column) { - Hotkey h = working.get(row); - if (column == 3) { - h.activeServerOnly = Boolean.TRUE.equals(value); - } else if (column == 4) { - h.enabled = Boolean.TRUE.equals(value); - } - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/HtmlStyles.java b/ts3-client/swing/src/main/java/com/ts3client/ui/HtmlStyles.java deleted file mode 100644 index b4cc25c..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/HtmlStyles.java +++ /dev/null @@ -1,213 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.text.BBCode; -import com.ts3client.text.ChatHtml; - -import javax.swing.JEditorPane; -import javax.swing.JViewport; -import javax.swing.SwingUtilities; -import javax.swing.text.html.HTMLEditorKit; -import javax.swing.text.AttributeSet; -import javax.swing.text.Document; -import javax.swing.text.html.HTMLDocument; -import javax.swing.text.Element; -import javax.swing.text.View; -import javax.swing.text.ViewFactory; -import javax.swing.text.html.ImageView; -import javax.swing.text.html.StyleSheet; -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.Shape; - -/** - * The HTML panes showing TeamSpeak text — chat logs, client and channel information — - * and the theme-dependent stylesheet they share. - * - *

    Text that is already on screen keeps the colours its stylesheet was built with, so - * a look-and-feel change re-installs the editor kit and parses the pane's content again - * instead of only recolouring what is written afterwards. - */ -final class HtmlStyles { - - private static final String BODY_STYLE = "HtmlStyles.bodyStyle"; - - private HtmlStyles() { - } - - /** - * @param bodyStyle extra CSS for {@code body}, e.g. font and margins; the text colour - * is added by the theme - * @return a read-only HTML pane whose stylesheet follows the current theme - */ - static JEditorPane pane(String bodyStyle) { - JEditorPane pane = new JEditorPane() { - @Override - public void updateUI() { - super.updateUI(); - restyle(this); - } - }; - pane.putClientProperty(BODY_STYLE, bodyStyle); - pane.setEditable(false); - installKit(pane, null, false); - return pane; - } - - /** - * Paints the scroll pane {@code pane} sits in with the pane's own background: text - * only reaches as far as it goes, and the empty space below it would otherwise show - * the window's colour instead of the log's. - */ - static void fillViewport(JEditorPane pane) { - if (pane.getParent() instanceof JViewport viewport) { - viewport.setBackground(pane.getBackground()); - } - } - - /** Re-themes {@code pane}, keeping the text it shows. */ - private static void restyle(JEditorPane pane) { - // Also runs from JEditorPane's constructor, before the pane is one of ours. - if (pane.getClientProperty(BODY_STYLE) == null) return; - - int length = pane.getDocument().getLength(); - String html = length == 0 ? null : pane.getText(); - // A chat log sits at its newest line; keep it there rather than jumping to the top. - boolean atEnd = pane.getCaretPosition() >= length; - // Not during the look-and-feel update that got us here: the pane is rebuilding its - // views, and replacing the document underneath it would race with that. - SwingUtilities.invokeLater(() -> installKit(pane, html, atEnd)); - } - - private static void installKit(JEditorPane pane, String html, boolean atEnd) { - HTMLEditorKit kit = new ZoomedKit(pane); - StyleSheet css = new StyleSheet(); - css.addStyleSheet(kit.getStyleSheet()); - - Object bodyStyle = pane.getClientProperty(BODY_STYLE); - css.addRule("body { " + (bodyStyle == null ? "" : bodyStyle + " ") - + "color:" + hex(Theme.chatText()) + "; }"); - // Secondary text (timestamps, labels, placeholders), an author's name and the lines - // about what happened on the server. - css.addRule(".muted { color:" + hex(Theme.chatSystem()) + "; }"); - css.addRule(".name { color:" + hex(Theme.chatName()) + "; font-weight:bold; }"); - css.addRule(".event { color:" + hex(Theme.chatEvent()) + "; }"); - css.addRule("a { color:" + hex(Theme.chatName()) + "; text-decoration:none; }"); - // Client references look exactly like a message author's name. - css.addRule("a." + BBCode.IDENTITY_LINK_CLASS - + " { color:" + hex(Theme.chatName()) + "; font-weight:bold; text-decoration:none; }"); - // Channel (and other TeamSpeak protocol) references stand out of a line the same - // way a client's name does. - css.addRule("a." + BBCode.TS_LINK_CLASS - + " { color:" + hex(Theme.chatName()) + "; font-weight:bold; text-decoration:none; }"); - // External links are underlined so they can't be mistaken for an identity. - css.addRule("a." + BBCode.EXTERNAL_LINK_CLASS - + " { color:" + hex(Theme.link()) + "; text-decoration:underline; }"); - css.addRule("a." + ChatHtml.ATTACHMENT_CLASS - + " { color:" + hex(Theme.link()) + "; text-decoration:underline; }"); - kit.setStyleSheet(css); - - pane.setEditorKit(kit); - fillViewport(pane); - if (html != null) { - pane.setText(html); - pane.setCaretPosition(atEnd ? pane.getDocument().getLength() : 0); - } - } - - /** A CSS length of {@code px} at the interface scale. */ - static String px(int px) { - return UIScale.scale(px) + "px"; - } - - private static String hex(Color c) { - return String.format("#%02x%02x%02x", c.getRed(), c.getGreen(), c.getBlue()); - } - - /** Scales every font size by the pane's {@link TextZoom}; FlatLaf has already applied the interface scale. */ - private static final class ZoomedStyleSheet extends StyleSheet { - private final JEditorPane pane; - - ZoomedStyleSheet(JEditorPane pane) { - this.pane = pane; - } - - @Override - public Font getFont(AttributeSet a) { - Font font = super.getFont(a); - float zoom = TextZoom.of(pane); - return zoom == 1f ? font : font.deriveFont(font.getSize2D() * zoom); - } - } - - /** Zooms the text of the documents it makes, and draws their pictures at the pane's {@link TextZoom}. */ - private static final class ZoomedKit extends HTMLEditorKit { - private final JEditorPane pane; - private final ViewFactory factory = new HTMLFactory() { - @Override - public View create(Element elem) { - View view = super.create(elem); - return view instanceof ImageView ? new ZoomedImageView(elem) : view; - } - }; - - ZoomedKit(JEditorPane pane) { - this.pane = pane; - } - - /** As the default, but the document takes its fonts from a {@link ZoomedStyleSheet}. */ - @Override - public Document createDefaultDocument() { - StyleSheet css = new ZoomedStyleSheet(pane); - css.addStyleSheet(getStyleSheet()); - HTMLDocument doc = new HTMLDocument(css); - doc.setParser(getParser()); - doc.setAsynchronousLoadPriority(4); - doc.setTokenThreshold(100); - return doc; - } - - @Override - public ViewFactory getViewFactory() { - return factory; - } - } - - private static final class ZoomedImageView extends ImageView { - ZoomedImageView(Element elem) { - super(elem); - } - - private float zoom() { - return TextZoom.of(getContainer()); - } - - @Override - public float getPreferredSpan(int axis) { - return super.getPreferredSpan(axis) * zoom(); - } - - @Override - public void paint(Graphics g, Shape a) { - float zoom = zoom(); - if (zoom == 1f) { - super.paint(g, a); - return; - } - Rectangle r = a.getBounds(); - Graphics2D g2 = (Graphics2D) g.create(); - try { - g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); - g2.translate(r.x, r.y); - g2.scale(zoom, zoom); - super.paint(g2, new Rectangle(0, 0, Math.round(r.width / zoom), Math.round(r.height / zoom))); - } finally { - g2.dispose(); - } - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/IconChooserDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/IconChooserDialog.java deleted file mode 100644 index 68c3147..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/IconChooserDialog.java +++ /dev/null @@ -1,272 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.net.IconRepository; -import com.ts3client.net.TeamspeakConnection; - -import javax.swing.BorderFactory; -import javax.swing.DefaultListModel; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFileChooser; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSplitPane; -import javax.swing.ListSelectionModel; -import javax.swing.SwingUtilities; -import javax.swing.Timer; -import javax.swing.filechooser.FileNameExtensionFilter; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Window; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.io.File; - -/** - * TeamSpeak's icon viewer: the icons uploaded to this virtual server on one side (which - * can be added to and removed from here) and the ones the icon pack ships on the other. - * - *

    Server icons arrive through the {@link IconRepository}, which downloads them in the - * background, so the lists are simply repainted until every icon has turned up. - */ -final class IconChooserDialog extends JDialog { - - /** How often the lists are repainted while icons are still being downloaded. */ - private static final int REFRESH_MS = 300; - /** Give up repainting once nothing has arrived for this long. */ - private static final int REFRESH_TIMEOUT_MS = 20_000; - - private final TeamspeakConnection conn; - private final GroupIcons groupIcons; - - private final DefaultListModel remoteModel = new DefaultListModel<>(); - private final JList remoteList = new JList<>(remoteModel); - private final JList localList = new JList<>(new DefaultListModel<>()); - private final JButton deleteButton = new JButton("Delete"); - private final JButton selectButton = new JButton("Select"); - private final JLabel status = new JLabel(" "); - - private long chosenIconId; - private boolean accepted; - - IconChooserDialog(Window owner, TeamspeakConnection conn, GroupIcons groupIcons) { - super(owner, "Icons", ModalityType.APPLICATION_MODAL); - this.conn = conn; - this.groupIcons = groupIcons; - - configure(remoteList); - configure(localList); - DefaultListModel localModel = (DefaultListModel) localList.getModel(); - for (Long id : IconRepository.BUNDLED_IDS) localModel.addElement(id); - - JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, - group("Remote", remoteList, remoteButtons()), - group("Local", localList, localFooter())); - split.setResizeWeight(0.6); - - status.setBorder(new ScaledEmptyBorder(2, 8, 2, 8)); - status.setForeground(Theme.chatSystem()); - - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(split, BorderLayout.CENTER); - JPanel south = new JPanel(new BorderLayout()); - south.add(status, BorderLayout.NORTH); - south.add(buttons(), BorderLayout.SOUTH); - getContentPane().add(south, BorderLayout.SOUTH); - - Dialogs.closeOnEscape(this); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - setSize(UIScale.scale(new Dimension(520, 360))); - setLocationRelativeTo(owner); - - loadRemoteIcons(); - startRefreshing(); - } - - /** @return whether an icon was picked; {@link #getIconId()} then holds it */ - boolean isAccepted() { - return accepted; - } - - long getIconId() { - return chosenIconId; - } - - private void configure(JList list) { - list.setLayoutOrientation(JList.HORIZONTAL_WRAP); - list.setVisibleRowCount(-1); - list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - list.setFixedCellWidth(UIScale.scale(32)); - list.setFixedCellHeight(UIScale.scale(32)); - list.setCellRenderer(new IconCellRenderer()); - list.addListSelectionListener(e -> onSelectionChanged(list)); - list.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (e.getClickCount() == 2 && list.getSelectedValue() != null) choose(list.getSelectedValue()); - } - }); - } - - /** Keeps one list's selection exclusive: picking on one side clears the other. */ - private void onSelectionChanged(JList list) { - JList other = list == remoteList ? localList : remoteList; - if (list.getSelectedValue() != null) other.clearSelection(); - deleteButton.setEnabled(remoteList.getSelectedValue() != null); - selectButton.setEnabled(selectedIcon() != 0); - } - - private long selectedIcon() { - Long remote = remoteList.getSelectedValue(); - if (remote != null) return remote; - Long local = localList.getSelectedValue(); - return local == null ? 0 : local; - } - - private JPanel group(String title, JList list, Component footer) { - JPanel panel = new JPanel(new BorderLayout(0, UIScale.scale(4))); - panel.setBorder(BorderFactory.createTitledBorder(title)); - panel.add(new JScrollPane(list), BorderLayout.CENTER); - panel.add(footer, BorderLayout.SOUTH); - return panel; - } - - private Component remoteButtons() { - JButton upload = new JButton("Upload"); - upload.addActionListener(a -> uploadIcon()); - deleteButton.setEnabled(false); - deleteButton.addActionListener(a -> deleteSelectedIcon()); - JPanel row = new JPanel(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 4, 0)); - row.add(upload); - row.add(deleteButton); - return row; - } - - private Component localFooter() { - com.ts3client.gfx.IconPack active = IconTheme.get().activePack(); - JLabel pack = new JLabel("Icon Pack: " + (active == null ? "none" : active.name())); - pack.setBorder(new ScaledEmptyBorder(0, 4, 0, 4)); - return pack; - } - - private JPanel buttons() { - selectButton.setEnabled(false); - selectButton.addActionListener(a -> choose(selectedIcon())); - JButton cancel = new JButton("Cancel"); - cancel.addActionListener(a -> dispose()); - JPanel panel = new JPanel(new BorderLayout()); - JPanel right = new JPanel(); - right.add(selectButton); - right.add(cancel); - panel.add(right, BorderLayout.EAST); - getRootPane().setDefaultButton(selectButton); - return panel; - } - - private void choose(long iconId) { - if (iconId == 0) return; - chosenIconId = iconId; - accepted = true; - dispose(); - } - - private void loadRemoteIcons() { - status.setText("Loading icons…"); - conn.requestServerIcons((ids, error) -> SwingUtilities.invokeLater(() -> { - if (error != null) { - status.setText("Could not list the server's icons: " + error); - return; - } - status.setText(" "); - remoteModel.clear(); - for (Long id : ids) remoteModel.addElement(id); - })); - } - - private void uploadIcon() { - JFileChooser chooser = new JFileChooser(); - chooser.setDialogTitle("Select an image to upload"); - chooser.setFileFilter(new FileNameExtensionFilter("Images", "png", "jpg", "jpeg", "gif", "bmp", "svg")); - if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return; - File file = chooser.getSelectedFile(); - status.setText("Uploading " + file.getName() + "…"); - conn.uploadIcon(file, (iconId, error) -> SwingUtilities.invokeLater(() -> { - if (error != null) { - status.setText(" "); - JOptionPane.showMessageDialog(this, "Error uploading icon: " + error, - "Error", JOptionPane.ERROR_MESSAGE); - return; - } - loadRemoteIcons(); - startRefreshing(); - })); - } - - private void deleteSelectedIcon() { - Long id = remoteList.getSelectedValue(); - if (id == null) return; - int answer = JOptionPane.showConfirmDialog(this, - "Permanently delete this icon from the server?", "Confirmation", - JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); - if (answer != JOptionPane.YES_OPTION) return; - conn.deleteIcon(id, error -> SwingUtilities.invokeLater(() -> { - if (error != null) { - JOptionPane.showMessageDialog(this, "Failed to delete remote icon file: " + error, - "Error", JOptionPane.ERROR_MESSAGE); - return; - } - remoteModel.removeElement(id); - })); - } - - /** - * Repaints while the repository is still fetching icons; it hands them over silently, - * so the only way to show them as they land is to keep asking. - */ - private void startRefreshing() { - Timer timer = new Timer(REFRESH_MS, null); - long deadline = System.currentTimeMillis() + REFRESH_TIMEOUT_MS; - timer.addActionListener(e -> { - remoteList.repaint(); - localList.repaint(); - if (!isDisplayable() || System.currentTimeMillis() > deadline || allIconsLoaded()) timer.stop(); - }); - timer.start(); - } - - private boolean allIconsLoaded() { - for (int i = 0; i < remoteModel.size(); i++) { - if (groupIcons.icon(remoteModel.get(i)) == null) return false; - } - return true; - } - - /** Draws one icon, blank until the repository has it. */ - private final class IconCellRenderer extends javax.swing.DefaultListCellRenderer { - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, - boolean selected, boolean focused) { - super.getListCellRendererComponent(list, "", index, selected, focused); - long id = value instanceof Long ? (Long) value : 0; - ImageIcon icon = groupIcons.icon(id); - setIcon(icon); - setHorizontalAlignment(CENTER); - setToolTipText("Icon " + id); - return this; - } - } - - /** Convenience for callers that only need the picked id. */ - static long pick(Window owner, TeamspeakConnection conn, GroupIcons groupIcons, long current) { - IconChooserDialog dialog = new IconChooserDialog(owner, conn, groupIcons); - dialog.setVisible(true); - return dialog.isAccepted() ? dialog.getIconId() : current; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/IconFiles.java b/ts3-client/swing/src/main/java/com/ts3client/ui/IconFiles.java deleted file mode 100644 index 7c24bec..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/IconFiles.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.ts3client.ui; - -import javax.imageio.ImageIO; -import javax.swing.ImageIcon; -import java.awt.Graphics2D; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Icons of the active pack, and country flags, as PNG files, for HTML views, which only - * show pictures by URL. A pack change gives the theme new icons, and so new files. - */ -final class IconFiles { - - private static final Map FILES = new ConcurrentHashMap<>(); - private static File dir; - - private IconFiles() { - } - - /** @return the icon's file, or {@code null} if no pack has it or it could not be written */ - static File of(String key, int size) { - ImageIcon icon = IconTheme.icon(key, size); - if (icon == null) return null; - String name = key + '_' + size + '_' + Integer.toHexString(System.identityHashCode(icon)) + ".png"; - File file = FILES.computeIfAbsent(name, n -> write(icon, n)); - return file.isFile() ? file : null; - } - - /** @return the country's flag as drawn in the tree, or {@code null} for none */ - static File flag(String code) { - ImageIcon icon = CountryFlagIcons.of(code); - if (icon == null) return null; - File file = FILES.computeIfAbsent("flag_" + code + '_' + icon.getIconWidth() + ".png", n -> write(icon, n)); - return file.isFile() ? file : null; - } - - private static File write(ImageIcon icon, String name) { - try { - File file = new File(dir(), name); - BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB); - Graphics2D g = image.createGraphics(); - icon.paintIcon(null, g, 0, 0); - g.dispose(); - ImageIO.write(image, "png", file); - file.deleteOnExit(); - return file; - } catch (IOException e) { - return new File(name); // never a file, so asked for again next time - } - } - - private static synchronized File dir() throws IOException { - if (dir == null) { - dir = Files.createTempDirectory("ts3client-icons").toFile(); - dir.deleteOnExit(); - } - return dir; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/IconTheme.java b/ts3-client/swing/src/main/java/com/ts3client/ui/IconTheme.java deleted file mode 100644 index 283b75e..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/IconTheme.java +++ /dev/null @@ -1,194 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.UIScale; -import com.github.weisj.jsvg.SVGDocument; -import com.github.weisj.jsvg.parser.LoaderContext; -import com.github.weisj.jsvg.parser.SVGLoader; -import com.github.weisj.jsvg.view.ViewBox; -import com.ts3client.config.AppDirs; -import com.ts3client.config.Settings; -import com.ts3client.gfx.IconPack; -import com.ts3client.gfx.IconPacks; - -import javax.imageio.ImageIO; -import javax.swing.ImageIcon; -import javax.swing.UIManager; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.RenderingHints; -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CopyOnWriteArrayList; - -/** - * The icons the user interface draws itself with, taken from the active - * {@link IconPack}. - * - *

    Packs are TeamSpeak's, so an installed client's {@code gfx/} folder (and the - * packs from its add-on site) can be used as they are. A pack's own - * {@code FALLBACK} option decides whether icons it does not define are looked up - * in {@code default.zip}; whatever is still missing is drawn by {@link Icons} - * instead, so the client always has a complete set. - * - *

    Rendering is cached per key and size: vector art is rasterised at the size it - * is asked for, in the look-and-feel's text colour where it paints with - * {@code currentColor}; bitmaps are scaled from the closest resolution the pack ships. - * {@link #SIZE} and {@link #TOOLBAR_SIZE} are unscaled; sizes passed in are pixels. - */ -public final class IconTheme { - - /** The size of a tree row / menu item icon, as in the official client. */ - public static final int SIZE = 16; - /** The size of the toolbar's buttons. */ - public static final int TOOLBAR_SIZE = 24; - - private static final IconTheme INSTANCE = new IconTheme(); - - private final Map cache = new ConcurrentHashMap<>(); - private final List listeners = new CopyOnWriteArrayList<>(); - - private volatile List packs = List.of(); - private volatile IconPack active; - /** Where icons are looked up; what none of these has is drawn by {@link Icons}. */ - private volatile List lookupOrder = List.of(); - - private IconTheme() { - } - - public static IconTheme get() { - return INSTANCE; - } - - /** The packs found on this machine, in display order. */ - public List packs() { - return packs; - } - - public IconPack activePack() { - return active; - } - - /** Re-scans the pack folders and activates the one the settings name. */ - public void reload(Settings settings) { - packs = IconPacks.findAll(new File(AppDirs.profile(), "gfx"), settings.iconPackDir); - IconPack pack = IconPacks.select(packs, settings.iconPack); - // The shipped pack survives a re-scan as the same object, so setPack alone may not notice. - lookupOrder = IconPacks.lookupOrder(pack, packs, null); - setPack(pack); - } - - /** Switches to a pack (which may be {@code null} for the built-in icons). */ - public void setPack(IconPack pack) { - if (active == pack) return; - active = pack; - lookupOrder = IconPacks.lookupOrder(pack, packs, null); - cache.clear(); - for (Runnable listener : listeners) listener.run(); - } - - /** Re-renders the icons, which follow the look-and-feel's text colour. */ - public void refresh() { - cache.clear(); - for (Runnable listener : listeners) listener.run(); - } - - /** Registers a repaint to run whenever the icons change. */ - public void addListener(Runnable listener) { - listeners.add(listener); - } - - public void removeListener(Runnable listener) { - listeners.remove(listener); - } - - /** @return the icon for a TeamSpeak icon key at tree-row size, or {@code null} if no pack has it */ - public static ImageIcon icon(String key) { - return icon(key, UIScale.scale(SIZE)); - } - - /** @return the icon for a TeamSpeak icon key at {@code size} pixels, or {@code null} if no pack has it */ - public static ImageIcon icon(String key, int size) { - return INSTANCE.lookup(key, size); - } - - private ImageIcon lookup(String key, int size) { - if (key == null) return null; - String cacheKey = key + '@' + size; - ImageIcon cached = cache.get(cacheKey); - if (cached != null) return cached; - - ImageIcon icon = null; - for (IconPack pack : lookupOrder) { - icon = render(pack, key, size); - if (icon != null) break; - } - if (icon != null) cache.put(cacheKey, icon); - return icon; - } - - private static ImageIcon render(IconPack pack, String key, int size) { - byte[] data = pack.icon(key, size); - if (data == null || data.length == 0) return null; - BufferedImage image = pack.isVector(key, size) - ? rasterize(IconPack.withCurrentColor(data, textColor().getRGB()), size) - : decode(data, size); - return image == null ? null : new ImageIcon(image); - } - - private static Color textColor() { - Color c = UIManager.getColor("Label.foreground"); - return c != null ? c : Color.BLACK; - } - - static BufferedImage rasterize(byte[] data, int size) { - try { - SVGDocument document = new SVGLoader().load( - new ByteArrayInputStream(data), null, LoaderContext.createDefault()); - if (document == null) return null; - BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = image.createGraphics(); - try { - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); - document.render(null, g, new ViewBox(size, size)); - } finally { - g.dispose(); - } - return image; - } catch (Exception e) { - return null; - } - } - - private static BufferedImage decode(byte[] data, int size) { - try { - BufferedImage source = ImageIO.read(new ByteArrayInputStream(data)); - if (source == null) return null; - if (source.getWidth() == size && source.getHeight() == size) return source; - - BufferedImage scaled = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = scaled.createGraphics(); - try { - g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, - RenderingHints.VALUE_INTERPOLATION_BILINEAR); - g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - // Keep the aspect ratio of packs whose art is not square. - double factor = Math.min((double) size / source.getWidth(), (double) size / source.getHeight()); - int w = Math.max(1, (int) Math.round(source.getWidth() * factor)); - int h = Math.max(1, (int) Math.round(source.getHeight() * factor)); - g.drawImage(source.getScaledInstance(w, h, Image.SCALE_SMOOTH), - (size - w) / 2, (size - h) / 2, null); - } finally { - g.dispose(); - } - return scaled; - } catch (Exception e) { - return null; - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/Icons.java b/ts3-client/swing/src/main/java/com/ts3client/ui/Icons.java deleted file mode 100644 index 1bafb4a..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/Icons.java +++ /dev/null @@ -1,487 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.gfx.IconKeys; - -import javax.swing.ImageIcon; -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.RenderingHints; -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -/** - * The user interface's icons, taken from the active {@link IconTheme} pack and - * named by TeamSpeak's icon keys. - * - *

    The icons the client cannot do without are also drawn programmatically here, - * so a machine with no icon pack installed still gets a complete (if plain) set. - * Everything else — menu and dialog decoration — simply stays blank without a pack, - * which is why {@link #of(String)} may return {@code null}. - * - *

    Icons come at the interface's scale; the variants taking a size take it in pixels. - */ -public final class Icons { - - /** The box the built-in painters draw in. */ - private static final int SZ = IconTheme.SIZE; - - private Icons() { - } - - private static int small() { - return UIScale.scale(IconTheme.SIZE); - } - - private static int large() { - return UIScale.scale(IconTheme.TOOLBAR_SIZE); - } - - private interface Painter { - void paint(Graphics2D g); - } - - /** @return the pack's icon for a TeamSpeak icon key, or {@code null} when it has none */ - public static ImageIcon of(String key) { - return IconTheme.icon(key); - } - - /** - * @return the pack's icon for the first key it has, or {@code null} when it has none - * of them — packs differ in which variants they ship - */ - public static ImageIcon ofAny(String... keys) { - for (String key : keys) { - ImageIcon icon = IconTheme.icon(key); - if (icon != null) return icon; - } - return null; - } - - /** @return the pack's icon at {@code size} pixels, or {@code null} when it has none */ - public static ImageIcon of(String key, int size) { - return IconTheme.icon(key, size); - } - - private static ImageIcon themed(String key, Painter fallback) { - return themed(key, small(), fallback); - } - - private static ImageIcon themed(String key, int size, Painter fallback) { - ImageIcon icon = IconTheme.icon(key, size); - return icon != null ? icon : make(size, fallback); - } - - /** Like {@link #themed(String, Painter)}, but tries the keys in turn. */ - private static ImageIcon themed(String[] keys, Painter fallback) { - for (String key : keys) { - ImageIcon icon = IconTheme.icon(key, small()); - if (icon != null) return icon; - } - return make(fallback); - } - - private static ImageIcon make(Painter p) { - return make(small(), p); - } - - /** Runs a painter (which draws in a 16×16 box) scaled to {@code size}. */ - private static ImageIcon make(int size, Painter p) { - BufferedImage img = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = img.createGraphics(); - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); - g.scale(size / (double) SZ, size / (double) SZ); - p.paint(g); - g.dispose(); - return new ImageIcon(img); - } - - // ---- tree icons ---- - - public static ImageIcon server() { - return themed("SERVER_GREEN", Icons::paintServer); - } - - public static ImageIcon channel(boolean subscribed) { - return themed(IconKeys.channel(false, false, subscribed), - g -> paintChannel(g, new Color(0x3E7CB1), false, subscribed)); - } - - /** A channel nobody can join without its password. */ - public static ImageIcon channelLocked(boolean subscribed) { - return themed(IconKeys.channel(true, false, subscribed), - g -> paintChannel(g, new Color(0x8A6D3B), true, subscribed)); - } - - /** A channel that has reached its client limit. */ - public static ImageIcon channelFull(boolean subscribed) { - return themed(IconKeys.channel(false, true, subscribed), - g -> paintChannel(g, new Color(0xA53F3F), false, subscribed)); - } - - /** The chat tab for the current channel. */ - public static ImageIcon channelChat() { - ImageIcon icon = of("CHANNEL_CHAT"); - return icon != null ? icon : channel(true); - } - - /** The chat tab of a private conversation. */ - public static ImageIcon privateChat() { - ImageIcon icon = ofAny("PLAYER_CHAT", "NEW_CHAT"); - return icon != null ? icon : clientIdle(); - } - - // ---- client status icons ---- - - public static ImageIcon clientIdle() { - return clientIdle(small()); - } - - public static ImageIcon clientIdle(int size) { - return themed("PLAYER_OFF", size, g -> paintPerson(g, Theme.idleClient())); - } - - public static ImageIcon clientTalking() { - return clientTalking(small()); - } - - public static ImageIcon clientTalking(int size) { - return themed("PLAYER_ON", size, g -> paintPerson(g, Theme.talking())); - } - - public static ImageIcon clientAway() { - return clientAway(small()); - } - - public static ImageIcon clientAway(int size) { - return themed("AWAY", size, g -> paintPerson(g, Theme.away())); - } - - /** A channel commander that is not talking. */ - public static ImageIcon clientCommander() { - return clientCommander(small()); - } - - /** A channel commander that is talking. */ - public static ImageIcon clientCommanderTalking() { - return clientCommanderTalking(small()); - } - - public static ImageIcon clientQuery() { - return themed("SERVER_QUERY", g -> paintPerson(g, Theme.idleClient())); - } - - public static ImageIcon micMuted() { - return micMuted(small()); - } - - public static ImageIcon micMuted(int size) { - return themed("INPUT_MUTED", size, Icons::paintMicMuted); - } - - public static ImageIcon speakerMuted() { - return speakerMuted(small()); - } - - public static ImageIcon speakerMuted(int size) { - return themed("OUTPUT_MUTED", size, Icons::paintSpeakerMuted); - } - - /** The capture device is unavailable (another tab holds it), as opposed to muted. */ - public static ImageIcon micDisabled() { - return micDisabled(small()); - } - - public static ImageIcon micDisabled(int size) { - return themed("HARDWARE_INPUT_MUTED", size, Icons::paintMicDisabled); - } - - /** The playback device is unavailable, as opposed to muted/deafened. */ - public static ImageIcon speakerDisabled() { - return speakerDisabled(small()); - } - - public static ImageIcon speakerDisabled(int size) { - return themed("HARDWARE_OUTPUT_MUTED", size, Icons::paintSpeakerDisabled); - } - - /** TS3's "Local Mic Mute": silenced, but not reported as muted. */ - public static ImageIcon micLocalMuted() { - return micLocalMuted(small()); - } - - public static ImageIcon micLocalMuted(int size) { - return themed("INPUT_MUTED_LOCAL", size, Icons::paintMicLocalMuted); - } - - /** A channel commander that is not talking. */ - public static ImageIcon clientCommander(int size) { - return themed("PLAYER_COMMANDER_OFF", size, g -> paintPerson(g, Theme.idleClient())); - } - - /** A channel commander that is talking. */ - public static ImageIcon clientCommanderTalking(int size) { - return themed("PLAYER_COMMANDER_ON", size, g -> paintPerson(g, Theme.talking())); - } - - // ---- toolbar / action icons ---- - - public static ImageIcon connect() { - return themed("CONNECT", large(), Icons::paintConnect); - } - - public static ImageIcon disconnect() { - return themed("DISCONNECT", large(), Icons::paintDisconnect); - } - - public static ImageIcon mic() { - return themed("CAPTURE", large(), Icons::paintMic); - } - - public static ImageIcon speaker() { - return themed("PLAYBACK", large(), Icons::paintSpeaker); - } - - public static ImageIcon micMutedLarge() { - return themed("INPUT_MUTED", large(), Icons::paintMicMuted); - } - - public static ImageIcon speakerMutedLarge() { - return themed("OUTPUT_MUTED", large(), Icons::paintSpeakerMuted); - } - - /** Marks the server that currently owns the microphone. */ - public static ImageIcon micActive() { - return themed("ACTIVATE_MICROPHONE", large(), Icons::paintMicActive); - } - - /** The same marker at tab-label size. */ - public static ImageIcon micActiveSmall() { - return themed("ACTIVATE_MICROPHONE", Icons::paintMicActive); - } - - /** - * A fixed-width "channel icon / edit icon" label icon, used where a tab must not - * change width as the object it shows changes (e.g. the info-panel-in-chat tab). - */ - public static ImageIcon channelClientPair() { - ImageIcon channel = channel(true); - ImageIcon edit = themed("EDIT", Icons::paintEdit); - int gap = UIScale.scale(8); - int width = channel.getIconWidth() + gap + edit.getIconWidth(); - int height = Math.max(channel.getIconHeight(), edit.getIconHeight()); - BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = img.createGraphics(); - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.drawImage(channel.getImage(), 0, (height - channel.getIconHeight()) / 2, null); - g.setColor(Theme.idleClient()); - g.setFont(Theme.uiFont()); - java.awt.FontMetrics fm = g.getFontMetrics(); - int slashX = channel.getIconWidth() + (gap - fm.stringWidth("/")) / 2; - g.drawString("/", slashX, (height + fm.getAscent()) / 2 - 1); - g.drawImage(edit.getImage(), channel.getIconWidth() + gap, - (height - edit.getIconHeight()) / 2, null); - g.dispose(); - return new ImageIcon(img); - } - - /** The toolbar's away marker. */ - public static ImageIcon away() { - return themed("AWAY", large(), g -> paintPerson(g, Theme.away())); - } - - public static ImageIcon settings() { - return themed("SETTINGS", large(), Icons::paintSettings); - } - - public static ImageIcon app() { - return app(small()); - } - - /** Below 32 pixels a variant with a bolder headset, whose thin lines would blur away. */ - public static ImageIcon app(int size) { - String name = size < 32 ? "app-icon-small.svg" : "app-icon.svg"; - try (InputStream in = Icons.class.getResourceAsStream(name)) { - BufferedImage image = IconTheme.rasterize(in.readAllBytes(), size); - if (image != null) return new ImageIcon(image); - } catch (IOException | RuntimeException ignored) { - } - return new ImageIcon(new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB)); - } - - /** The window icon at the sizes task bars and switchers pick from. */ - public static List appImages() { - return List.of(16, 24, 32, 48, 64, 128).stream() - .map(size -> app(size).getImage()) - .toList(); - } - - // ---- built-in painters ---- - - private static void paintServer(Graphics2D g) { - g.setColor(new Color(0x2C6EA5)); - g.fillRoundRect(2, 3, 12, 4, 2, 2); - g.fillRoundRect(2, 9, 12, 4, 2, 2); - g.setColor(new Color(0x9FD0F0)); - g.fillOval(4, 4, 2, 2); - g.fillOval(4, 10, 2, 2); - } - - /** - * The speaker-cone glyph. An unsubscribed channel is drawn hollow and without the - * sound waves, so the two states stay apart even without an icon pack. - */ - private static void paintChannel(Graphics2D g, Color c, boolean lock, boolean subscribed) { - int[] xs = {5, 9, 9, 5}; - int[] ys = {6, 3, 13, 10}; - g.setColor(c); - g.setStroke(new BasicStroke(subscribed ? 1.6f : 1.2f)); - if (subscribed) { - g.fillRect(2, 6, 3, 4); - g.fillPolygon(xs, ys, 4); - g.setStroke(new BasicStroke(1.4f)); - g.drawArc(9, 5, 4, 6, -60, 120); - } else { - g.drawRect(2, 6, 3, 4); - g.drawPolygon(xs, ys, 4); - } - if (lock) { - g.setColor(new Color(0xB8860B)); - g.fillRoundRect(10, 9, 5, 5, 1, 1); - g.setColor(Color.WHITE); - g.fillRect(12, 10, 1, 2); - } - } - - private static void paintPerson(Graphics2D g, Color c) { - g.setColor(c); - g.fillOval(5, 2, 6, 6); // head - g.fillRoundRect(3, 9, 10, 6, 4, 4); // shoulders - } - - private static void paintMicMuted(Graphics2D g) { - g.setColor(Theme.muted()); - g.fillRoundRect(6, 2, 4, 7, 2, 2); - g.setStroke(new BasicStroke(1.4f)); - g.drawArc(4, 6, 8, 6, 200, 140); - g.drawLine(8, 12, 8, 14); - g.setStroke(new BasicStroke(2f)); - g.drawLine(2, 2, 14, 14); // slash - } - - private static void paintSpeakerMuted(Graphics2D g) { - g.setColor(Theme.muted()); - g.fillRect(2, 6, 3, 4); - int[] xs = {5, 9, 9, 5}; - int[] ys = {6, 3, 13, 10}; - g.fillPolygon(xs, ys, 4); - g.setStroke(new BasicStroke(2f)); - g.drawLine(2, 2, 14, 14); - } - - /** Same shape as {@link #paintMicMuted}, but grey: unavailable, not muted by choice. */ - private static void paintMicDisabled(Graphics2D g) { - g.setColor(Theme.idleClient()); - g.fillRoundRect(6, 2, 4, 7, 2, 2); - g.setStroke(new BasicStroke(1.4f)); - g.drawArc(4, 6, 8, 6, 200, 140); - g.drawLine(8, 12, 8, 14); - g.setStroke(new BasicStroke(2f)); - g.drawLine(2, 2, 14, 14); - } - - /** Same shape as {@link #paintSpeakerMuted}, but grey: unavailable, not muted by choice. */ - private static void paintSpeakerDisabled(Graphics2D g) { - g.setColor(Theme.idleClient()); - g.fillRect(2, 6, 3, 4); - int[] xs = {5, 9, 9, 5}; - int[] ys = {6, 3, 13, 10}; - g.fillPolygon(xs, ys, 4); - g.setStroke(new BasicStroke(2f)); - g.drawLine(2, 2, 14, 14); - } - - /** {@link #paintMicMuted}, marked with a small dot: silenced, but not reported as muted. */ - private static void paintMicLocalMuted(Graphics2D g) { - paintMicMuted(g); - g.setColor(Theme.accent()); - g.fillOval(11, 10, 4, 4); - } - - private static void paintConnect(Graphics2D g) { - g.setColor(new Color(0x2E8B57)); - g.setStroke(new BasicStroke(2f)); - g.drawLine(3, 8, 8, 8); - g.fillRoundRect(8, 5, 5, 6, 2, 2); - g.drawLine(10, 3, 10, 5); - g.drawLine(12, 3, 12, 5); - } - - private static void paintDisconnect(Graphics2D g) { - g.setColor(Theme.muted()); - g.setStroke(new BasicStroke(2f)); - g.drawLine(3, 8, 8, 8); - g.fillRoundRect(8, 5, 5, 6, 2, 2); - g.drawLine(2, 3, 6, 13); - } - - private static void paintMic(Graphics2D g) { - g.setColor(new Color(0x37474F)); - g.fillRoundRect(6, 2, 4, 7, 2, 2); - g.setStroke(new BasicStroke(1.4f)); - g.drawArc(4, 6, 8, 6, 200, 140); - g.drawLine(8, 12, 8, 14); - g.drawLine(6, 14, 10, 14); - } - - private static void paintSpeaker(Graphics2D g) { - g.setColor(new Color(0x37474F)); - g.fillRect(2, 6, 3, 4); - int[] xs = {5, 9, 9, 5}; - int[] ys = {6, 3, 13, 10}; - g.fillPolygon(xs, ys, 4); - g.setStroke(new BasicStroke(1.4f)); - g.drawArc(9, 5, 4, 6, -60, 120); - } - - private static void paintMicActive(Graphics2D g) { - g.setColor(Theme.talking()); - g.fillOval(1, 1, 14, 14); - g.setColor(Color.WHITE); - g.fillRoundRect(6, 3, 4, 6, 2, 2); - g.setStroke(new BasicStroke(1.4f)); - g.drawArc(4, 6, 8, 6, 200, 140); - g.drawLine(8, 11, 8, 13); - } - - /** A pencil glyph, drawn when no icon pack ships an "EDIT" icon. */ - private static void paintEdit(Graphics2D g) { - g.setColor(new Color(0x37474F)); - g.setStroke(new BasicStroke(1.4f)); - g.drawLine(3, 13, 11, 5); - g.drawLine(3, 13, 4, 10); - g.drawLine(4, 10, 11, 3); - g.drawLine(11, 3, 13, 5); - g.drawLine(13, 5, 11, 7); - g.drawLine(11, 5, 13, 7); - } - - private static void paintSettings(Graphics2D g) { - g.setColor(new Color(0x37474F)); - g.setStroke(new BasicStroke(2f)); - g.drawOval(5, 5, 6, 6); - for (int a = 0; a < 360; a += 45) { - double r = Math.toRadians(a); - int x1 = (int) (8 + Math.cos(r) * 5); - int y1 = (int) (8 + Math.sin(r) * 5); - int x2 = (int) (8 + Math.cos(r) * 7); - int y2 = (int) (8 + Math.sin(r) * 7); - g.drawLine(x1, y1, x2, y2); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/IdentitiesDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/IdentitiesDialog.java deleted file mode 100644 index 53087f5..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/IdentitiesDialog.java +++ /dev/null @@ -1,432 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.config.Bookmarks; -import com.ts3client.config.IdentityEntry; -import com.ts3client.config.IdentityStore; -import com.ts3client.config.Settings; -import com.ts3client.teamspeak.TeamSpeakImporter; -import com.ts3client.teamspeak.TeamSpeakSettingsDb; - -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.DefaultListCellRenderer; -import javax.swing.DefaultListModel; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFileChooser; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextField; -import javax.swing.SwingUtilities; -import javax.swing.filechooser.FileNameExtensionFilter; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Frame; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.FocusAdapter; -import java.awt.event.FocusEvent; -import java.io.File; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Consumer; - -/** - * Identity manager, mirroring the TeamSpeak 3 client's Tools → Identities: - * create, import, export, rename and delete identities, mark one as the default - * and raise an identity's security level. - */ -public final class IdentitiesDialog extends JDialog { - - private final IdentityStore identities; - private final Settings settings; - private final Bookmarks bookmarks; - private final Runnable onChanged; - - private final DefaultListModel listModel = new DefaultListModel<>(); - private final JList list = new JList<>(listModel); - - private final JTextField nameField = new JTextField(); - private final JTextField uidField = new JTextField(); - private final JTextField levelField = new JTextField(); - private final JTextField nicknameField = new JTextField(); - private final JTextField phoneticField = new JTextField(); - /** The identity the nickname fields belong to, which the list may already have moved off. */ - private IdentityEntry shown; - - public IdentitiesDialog(Frame owner, IdentityStore identities, Settings settings, - Bookmarks bookmarks, Runnable onChanged) { - super(owner, "Identities", true); - this.identities = identities; - this.settings = settings; - this.bookmarks = bookmarks; - this.onChanged = onChanged; - - list.setCellRenderer(new DefaultListCellRenderer() { - @Override - public Component getListCellRendererComponent(JList l, Object value, int index, - boolean isSelected, boolean cellHasFocus) { - String text = value instanceof IdentityEntry ? label((IdentityEntry) value) : String.valueOf(value); - return super.getListCellRendererComponent(l, text, index, isSelected, cellHasFocus); - } - }); - list.addListSelectionListener(e -> showDetails(list.getSelectedValue())); - list.setVisibleRowCount(10); - - JScrollPane scroll = new JScrollPane(list); - scroll.setBorder(new ScaledEmptyBorder(8, 8, 8, 8)); - scroll.setPreferredSize(UIScale.scale(new Dimension(220, 260))); - - JPanel buttons = new JPanel(); - buttons.setLayout(new BoxLayout(buttons, BoxLayout.Y_AXIS)); - buttons.setBorder(new ScaledEmptyBorder(8, 0, 8, 8)); - addButton(buttons, "New…", this::newIdentity); - addButton(buttons, "Import…", this::importIdentity); - if (TeamSpeakSettingsDb.locate() != null) { - addButton(buttons, "Import from TeamSpeak 3…", this::importFromTeamSpeak); - } - addButton(buttons, "Export…", this::exportSelected); - addButton(buttons, "Rename…", this::renameSelected); - addButton(buttons, "Set as default", this::setSelectedDefault); - addButton(buttons, "Improve security…", this::improveSelected); - addButton(buttons, "Remove", this::removeSelected); - buttons.add(Box.createVerticalGlue()); - addButton(buttons, "Close", this::dispose); - - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(scroll, BorderLayout.WEST); - getContentPane().add(buildDetails(), BorderLayout.CENTER); - getContentPane().add(buttons, BorderLayout.EAST); - - reload(); - if (!listModel.isEmpty()) list.setSelectedIndex(0); - - Dialogs.closeOnEscape(this); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - pack(); - setMinimumSize(UIScale.scale(new Dimension(640, 320))); - setLocationRelativeTo(owner); - } - - private JPanel buildDetails() { - JPanel form = new JPanel(new GridBagLayout()); - form.setBorder(new ScaledEmptyBorder(12, 4, 12, 8)); - GridBagConstraints c = new GridBagConstraints(); - c.insets = UIScale.scale(new Insets(4, 4, 4, 4)); - c.anchor = GridBagConstraints.NORTHWEST; - c.fill = GridBagConstraints.HORIZONTAL; - - nameField.setEditable(false); - uidField.setEditable(false); - levelField.setEditable(false); - - int row = 0; - addRow(form, c, row++, "Name:", nameField); - addRow(form, c, row++, "Unique ID:", uidField); - addRow(form, c, row++, "Security level:", levelField); - addRow(form, c, row++, "Nickname:", nicknameField); - addRow(form, c, row++, "Phonetic nickname:", phoneticField); - - nicknameField.setToolTipText("Empty: the global nickname"); - for (JTextField field : new JTextField[]{nicknameField, phoneticField}) { - field.addActionListener(e -> applyNicknames()); - field.addFocusListener(new FocusAdapter() { - @Override - public void focusLost(FocusEvent e) { - applyNicknames(); - } - }); - } - - c.gridx = 0; - c.gridy = row; - c.gridwidth = 2; - c.weighty = 1; - c.fill = GridBagConstraints.BOTH; - form.add(Box.createGlue(), c); - return form; - } - - private void addRow(JPanel form, GridBagConstraints c, int row, String label, Component field) { - c.gridx = 0; - c.gridy = row; - c.weightx = 0; - form.add(new JLabel(label), c); - c.gridx = 1; - c.weightx = 1; - form.add(field, c); - } - - private void addButton(JPanel panel, String text, Runnable action) { - JButton b = new JButton(text); - b.setAlignmentX(LEFT_ALIGNMENT); - b.setMaximumSize(new Dimension(Integer.MAX_VALUE, b.getPreferredSize().height)); - b.addActionListener(e -> action.run()); - panel.add(b); - panel.add(Box.createVerticalStrut(UIScale.scale(4))); - } - - private String label(IdentityEntry e) { - return e.getId().equals(settings.defaultIdentityId) ? e.getName() + " (default)" : e.getName(); - } - - private void reload() { - IdentityEntry selected = list.getSelectedValue(); - listModel.clear(); - for (IdentityEntry e : identities.all()) listModel.addElement(e); - if (selected != null && listModel.contains(selected)) { - list.setSelectedValue(selected, true); - } else if (!listModel.isEmpty()) { - list.setSelectedIndex(0); - } else { - showDetails(null); - } - if (onChanged != null) onChanged.run(); - } - - private void showDetails(IdentityEntry e) { - applyNicknames(); - shown = e; - nicknameField.setEnabled(e != null); - phoneticField.setEnabled(e != null); - nicknameField.setText(e == null ? "" : e.getNickname()); - phoneticField.setText(e == null ? "" : e.getPhoneticNickname()); - nameField.setText(e == null ? "" : e.getName()); - uidField.setText(e == null ? "" : e.getUniqueId()); - levelField.setText(e == null ? "" : Integer.toString(e.getSecurityLevel())); - } - - @Override - public void dispose() { - // Escape closes without the field losing focus first. - applyNicknames(); - super.dispose(); - } - - // ---- actions ---- - - private void applyNicknames() { - IdentityEntry e = shown; - if (e == null || identities.byId(e.getId()) == null) return; - String nickname = nicknameField.getText().trim(); - String phonetic = phoneticField.getText().trim(); - if (nickname.equals(e.getNickname()) && phonetic.equals(e.getPhoneticNickname())) return; - try { - identities.setNicknames(e, nickname, phonetic); - } catch (Exception ex) { - error("Could not save the nicknames", ex); - } - } - - private void newIdentity() { - String name = JOptionPane.showInputDialog(this, "Name for the new identity:", "New identity"); - if (name == null || name.trim().isEmpty()) return; - - int level = askLevel("Security level to generate:", IdentityStore.DEFAULT_SECURITY_LEVEL); - if (level < 0) return; - - runWithProgress("Generating identity…", (cancelled, status) -> { - IdentityEntry created = identities.generate(name.trim(), level); - if (settings.defaultIdentityId == null || identities.byId(settings.defaultIdentityId) == null) { - settings.defaultIdentityId = created.getId(); - settings.save(); - } - return created; - }, false); - } - - private void importIdentity() { - JFileChooser chooser = new JFileChooser(); - chooser.setDialogTitle("Import identity"); - chooser.setFileFilter(new FileNameExtensionFilter("TeamSpeak identity (*.ini)", "ini")); - if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return; - File file = chooser.getSelectedFile(); - try { - IdentityEntry imported = identities.importFile(file, null); - if (identities.byId(settings.defaultIdentityId) == null) { - settings.defaultIdentityId = imported.getId(); - settings.save(); - } - reload(); - list.setSelectedValue(imported, true); - } catch (Exception e) { - error("Could not import identity", e); - } - } - - private void importFromTeamSpeak() { - File db = TeamSpeakSettingsDb.locate(); - if (db == null) return; - try { - TeamSpeakImporter.Result result = new TeamSpeakImporter(identities, bookmarks, settings).importIdentities(db); - reload(); - JOptionPane.showMessageDialog(this, result.identities() + " identit" + (result.identities() == 1 ? "y" : "ies") - + " read from " + db + "\n" + result.identitiesAdded() + " new, " - + result.identitiesKnown() + " already present.", - "Import from TeamSpeak 3", JOptionPane.INFORMATION_MESSAGE); - } catch (Exception e) { - error("Could not read " + db, e); - } - } - - private void exportSelected() { - IdentityEntry e = list.getSelectedValue(); - if (e == null) return; - JFileChooser chooser = new JFileChooser(); - chooser.setDialogTitle("Export identity"); - chooser.setFileFilter(new FileNameExtensionFilter("TeamSpeak identity (*.ini)", "ini")); - chooser.setSelectedFile(new File(e.getName().replaceAll("[^\\w.-]+", "_") + ".ini")); - if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return; - - File target = chooser.getSelectedFile(); - if (target.exists() && JOptionPane.showConfirmDialog(this, - target.getName() + " already exists. Overwrite?", "Export identity", - JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) { - return; - } - try { - identities.exportTo(e, target); - JOptionPane.showMessageDialog(this, "Identity exported to\n" + target.getAbsolutePath(), - "Export identity", JOptionPane.INFORMATION_MESSAGE); - } catch (Exception ex) { - error("Could not export identity", ex); - } - } - - private void renameSelected() { - IdentityEntry e = list.getSelectedValue(); - if (e == null) return; - String name = JOptionPane.showInputDialog(this, "Identity name:", e.getName()); - if (name == null || name.trim().isEmpty()) return; - try { - identities.rename(e, name.trim()); - reload(); - } catch (Exception ex) { - error("Could not rename identity", ex); - } - } - - private void setSelectedDefault() { - IdentityEntry e = list.getSelectedValue(); - if (e == null) return; - settings.defaultIdentityId = e.getId(); - settings.save(); - reload(); - } - - private void removeSelected() { - IdentityEntry e = list.getSelectedValue(); - if (e == null) return; - int result = JOptionPane.showConfirmDialog(this, - "Delete identity \"" + e.getName() + "\"?\n\n" - + "Server groups and permissions tied to it will be lost.\n" - + "Export it first if you may need it again.", - "Remove identity", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); - if (result != JOptionPane.YES_OPTION) return; - identities.remove(e, settings, bookmarks); - reload(); - } - - private void improveSelected() { - IdentityEntry e = list.getSelectedValue(); - if (e == null) return; - int level = askLevel("Target security level (current: " + e.getSecurityLevel() + "):", - Math.max(e.getSecurityLevel() + 1, IdentityStore.DEFAULT_SECURITY_LEVEL)); - if (level < 0) return; - if (level <= e.getSecurityLevel()) { - JOptionPane.showMessageDialog(this, "The identity already reaches that level."); - return; - } - runWithProgress("Improving security level…", - (cancelled, status) -> { - identities.improveSecurity(e, level, (best, offset) -> { - status.accept("Improving security level… reached " + best + " of " + level); - return !cancelled.get(); - }); - return e; - }, true); - } - - private int askLevel(String prompt, int suggestion) { - String s = JOptionPane.showInputDialog(this, prompt, Integer.toString(suggestion)); - if (s == null) return -1; - try { - int level = Integer.parseInt(s.trim()); - if (level < 0 || level > 40) throw new NumberFormatException(); - return level; - } catch (NumberFormatException e) { - JOptionPane.showMessageDialog(this, "Enter a security level between 0 and 40."); - return -1; - } - } - - /** Work that produces the identity to select once it finishes. */ - private interface IdentityTask { - IdentityEntry run(AtomicBoolean cancelled, Consumer status) throws Exception; - } - - /** - * Runs a long identity computation off the EDT behind a modal progress dialog. - * Both generating and improving an identity are proof-of-work searches whose - * duration grows exponentially with the security level. - */ - private void runWithProgress(String message, IdentityTask task, boolean cancellable) { - AtomicBoolean cancelled = new AtomicBoolean(false); - - JDialog progress = new JDialog(this, "Please wait", true); - JLabel status = new JLabel(message); - JPanel panel = new JPanel(new BorderLayout(UIScale.scale(8), UIScale.scale(8))); - panel.setBorder(new ScaledEmptyBorder(16, 16, 12, 16)); - panel.add(status, BorderLayout.CENTER); - if (cancellable) { - JButton cancel = new JButton("Stop"); - cancel.setToolTipText("Keep the best level found so far"); - cancel.addActionListener(e -> cancelled.set(true)); - JPanel south = new JPanel(); - south.add(cancel); - panel.add(south, BorderLayout.SOUTH); - } - progress.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); - progress.getContentPane().add(panel); - progress.pack(); - progress.setLocationRelativeTo(this); - - Consumer report = text -> SwingUtilities.invokeLater(() -> status.setText(text)); - Thread worker = new Thread(() -> { - IdentityEntry result = null; - Exception failure = null; - try { - result = task.run(cancelled, report); - } catch (Exception e) { - failure = e; - } - IdentityEntry selected = result; - Exception thrown = failure; - SwingUtilities.invokeLater(() -> { - progress.dispose(); - if (thrown != null) { - error("Identity operation failed", thrown); - return; - } - reload(); - if (selected != null) list.setSelectedValue(selected, true); - }); - }, "identity-work"); - - // Start only once the modal dialog is up, so a fast task can't dispose it - // before it becomes visible (which would leave it on screen forever). - SwingUtilities.invokeLater(worker::start); - progress.setVisible(true); - } - - private void error(String what, Exception e) { - String detail = e.getMessage() == null ? e.toString() : e.getMessage(); - JOptionPane.showMessageDialog(this, what + ":\n" + detail, "Identities", JOptionPane.ERROR_MESSAGE); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/IdentityChooser.java b/ts3-client/swing/src/main/java/com/ts3client/ui/IdentityChooser.java deleted file mode 100644 index b7a4846..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/IdentityChooser.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.config.IdentityEntry; -import com.ts3client.config.IdentityStore; - -import javax.swing.DefaultListCellRenderer; -import javax.swing.JComboBox; -import javax.swing.JList; -import java.awt.Component; - -/** - * Drop-down for picking the identity to connect with. Optionally offers a - * "use the default identity" entry for places where the choice may stay unset - * (bookmarks), so changing the default later applies retroactively. - */ -final class IdentityChooser extends JComboBox { - - private static final String USE_DEFAULT = "‹Default identity›"; - - private final IdentityStore identities; - private final boolean allowDefault; - - IdentityChooser(IdentityStore identities, boolean allowDefault, String selectedId) { - this.identities = identities; - this.allowDefault = allowDefault; - reload(); - setSelectedIdentityId(selectedId); - - setRenderer(new DefaultListCellRenderer() { - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, - boolean isSelected, boolean cellHasFocus) { - String text = value instanceof IdentityEntry - ? ((IdentityEntry) value).getName() - : String.valueOf(value); - return super.getListCellRendererComponent(list, text, index, isSelected, cellHasFocus); - } - }); - } - - /** Re-reads the store's identities, keeping the selection where it still exists. */ - void reload() { - String selected = getSelectedIdentityId(); - removeAllItems(); - if (allowDefault) addItem(USE_DEFAULT); - for (IdentityEntry e : identities.all()) addItem(e); - setSelectedIdentityId(selected); - } - - /** Selected identity id, or an empty string when the default is to be used. */ - String getSelectedIdentityId() { - Object v = getSelectedItem(); - return v instanceof IdentityEntry ? ((IdentityEntry) v).getId() : ""; - } - - /** Selects the identity with the given id, falling back to the default entry. */ - void setSelectedIdentityId(String id) { - IdentityEntry selected = identities.byId(id); - if (selected != null) { - setSelectedItem(selected); - } else if (allowDefault) { - setSelectedItem(USE_DEFAULT); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/InfoPanel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/InfoPanel.java deleted file mode 100644 index e262851..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/InfoPanel.java +++ /dev/null @@ -1,479 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.config.Settings; -import com.ts3client.contacts.Contact; -import com.ts3client.net.ChannelNode; -import com.ts3client.net.ClientEntry; -import com.ts3client.net.Details; -import com.ts3client.net.Group; -import com.ts3client.net.IconRepository; -import com.ts3client.net.PictureDownloads; -import com.ts3client.net.ServerModel; -import com.ts3client.net.avatar.Avatar; -import com.ts3client.text.BBCode; - -import javax.swing.BorderFactory; -import javax.swing.JEditorPane; -import javax.swing.JFileChooser; -import javax.swing.JLabel; -import javax.swing.JLayeredPane; -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.JScrollPane; -import javax.swing.SwingUtilities; -import javax.swing.text.AttributeSet; -import javax.swing.text.BadLocationException; -import javax.swing.text.StyleConstants; -import javax.swing.text.html.HTML; -import javax.swing.text.html.HTMLDocument; -import java.awt.BorderLayout; -import java.awt.Cursor; -import java.awt.Dimension; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.geom.Rectangle2D; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.List; - -/** - * Read-only detail view for the server, channel or client selected, mirroring the - * TeamSpeak 3 info box; what it says comes from {@link Details}. - */ -public final class InfoPanel extends JPanel { - - /** Moves the whole info panel's content out to a persistent chat tab. */ - public interface DescriptionHandler { - /** Shows/updates {@code html} in the info chat tab, creating it if needed. */ - void showInfoTab(String html, Runnable onClose); - - /** Closes the info chat tab (the user chose to show details in the panel again). */ - void closeInfoTab(); - - /** Hides (or restores) the panel itself, freeing its space, while its content lives in the chat tab. */ - void setPanelHidden(boolean hidden); - } - - /** What the avatar's menu does. */ - public interface AvatarHandler { - /** Takes someone else's avatar as ours. */ - void steal(Avatar avatar); - - /** Whether we may upload an avatar. */ - boolean canSet(); - - /** Whether we may delete other clients' avatars. */ - boolean canDeleteOthers(); - - void deleteOf(ClientEntry client); - - /** Asks for an image to upload as our avatar. */ - void set(); - - void delete(); - } - - private static final int AVATAR_MIN_SIZE = 64; - private static final int AVATAR_BOX_STEP = 16; - /** Pictures in a chat tab have no panel to fit, so they get this much. */ - private static final int CHAT_TAB_PICTURE_WIDTH = 480; - private static final int PICTURE_WIDTH_STEP = 32; - - private final JEditorPane pane = HtmlStyles.pane("font-family:sans-serif; font-size:11px;"); - private final JScrollPane scroll = new JScrollPane(pane); - /** Floats over the bottom-right corner of the details, out of the text's way. */ - private final JLabel toggle = new JLabel("Show in chat tab"); - private DescriptionHandler descriptionHandler; - private AvatarHandler avatarHandler; - private ChannelNode shownChannel; - private ClientEntry shownClient; - /** The server's address while the server itself is shown. */ - private String shownServer; - private ServerModel shownModel; - private IconRepository shownIcons; - private Contact shownContact; - private Avatar shownAvatar; - private boolean inChatTab; - /** The avatar box the current HTML was built for; a resize that changes it re-renders. */ - private int renderedAvatarBox; - private final PictureDownloads downloads; - private final DescriptionPictures pictures; - /** Whether the description shown has pictures, which re-render it as they come or the panel resizes. */ - private boolean showsPictures; - private int renderedPictureWidth; - private final Runnable onPicture = () -> SwingUtilities.invokeLater(() -> { - if (showsPictures) keepingScroll(this::render); - }); - - public InfoPanel(Settings settings, PictureDownloads downloads, TextZoom zoom) { - super(new BorderLayout()); - zoom.attach(pane); - this.downloads = downloads; - this.pictures = new DescriptionPictures(downloads, settings); - pane.setBorder(new ScaledEmptyBorder(6, 8, 6, 8)); - pane.addHyperlinkListener(e -> { - if (e.getEventType() != javax.swing.event.HyperlinkEvent.EventType.ACTIVATED) return; - Links.open(e.getDescription(), this); - }); - pane.addMouseListener(new MouseAdapter() { - @Override - public void mousePressed(MouseEvent e) { - if (e.isPopupTrigger()) showAvatarMenu(e); - } - - @Override - public void mouseReleased(MouseEvent e) { - if (e.isPopupTrigger()) showAvatarMenu(e); - } - }); - HtmlStyles.fillViewport(pane); - scroll.getViewport().addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent e) { - if (inChatTab) return; - boolean avatar = shownAvatar != null && avatarBox() != renderedAvatarBox; - boolean pictures = showsPictures && pictureWidth() != renderedPictureWidth; - if (avatar || pictures) keepingScroll(InfoPanel.this::render); - } - }); - - toggle.setFont(Theme.uiSmall()); - toggle.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - toggle.setToolTipText("Show these details in a chat tab instead"); - toggle.setOpaque(true); - toggle.setBorder(new ScaledEmptyBorder(1, 4, 1, 4)); - toggle.addMouseListener(new MouseAdapter() { - @Override - public void mousePressed(MouseEvent e) { - inChatTab = true; - render(); - } - }); - - // The link floats on top of the text rather than following it, so it stays - // in the corner however long the description is. - JLayeredPane layers = new JLayeredPane() { - @Override - public void doLayout() { - scroll.setBounds(0, 0, getWidth(), getHeight()); - // Lay the scroll pane out first: the link goes in the corner of the - // viewport, which is where the scroll bars have already been taken out. - scroll.doLayout(); - Rectangle view = scroll.getViewport().getBounds(); - Dimension d = toggle.getPreferredSize(); - toggle.setBounds(view.x + view.width - d.width, view.y + view.height - d.height, - d.width, d.height); - } - - // Without a layout manager we have no size of our own, and the split pane - // above us sizes the panel from it. - @Override - public Dimension getPreferredSize() { - return scroll.getPreferredSize(); - } - - @Override - public Dimension getMinimumSize() { - return scroll.getMinimumSize(); - } - }; - layers.add(scroll, JLayeredPane.DEFAULT_LAYER); - layers.add(toggle, JLayeredPane.PALETTE_LAYER); - add(layers, BorderLayout.CENTER); - applyTheme(); - clear(); - } - - @Override - public void addNotify() { - super.addNotify(); - downloads.addListener(onPicture); - } - - @Override - public void removeNotify() { - downloads.removeListener(onPicture); - super.removeNotify(); - } - - /** Runs {@code change}, which renders again, without the view jumping back to the top. */ - private void keepingScroll(Runnable change) { - Point at = scroll.getViewport().getViewPosition(); - change.run(); - SwingUtilities.invokeLater(() -> scroll.getViewport().setViewPosition(at)); - } - - @Override - public void updateUI() { - super.updateUI(); - // Runs from the superclass constructor too, before our own fields exist. - if (scroll != null) applyTheme(); - } - - private void applyTheme() { - scroll.setBorder(BorderFactory.createLineBorder(Theme.border())); - toggle.setBackground(pane.getBackground()); - toggle.setForeground(Theme.link()); - } - - public void clear() { - shownChannel = null; - shownClient = null; - shownServer = null; - inChatTab = false; - render(); - } - - public void setDescriptionHandler(DescriptionHandler handler) { - this.descriptionHandler = handler; - } - - public void setAvatarHandler(AvatarHandler handler) { - this.avatarHandler = handler; - } - - /** Runs when the user closes the info chat tab; shows details in the panel again. */ - private void onInfoTabClosed() { - inChatTab = false; - render(); - } - - public void showServer(ServerModel model, String address) { - shownServer = address; - shownModel = model; - shownChannel = null; - shownClient = null; - render(); - } - - public void showChannel(ChannelNode ch) { - shownChannel = ch; - shownClient = null; - shownServer = null; - render(); - } - - /** @param avatar the client's avatar, or {@code null} while there is none to show */ - public void showClient(ClientEntry cl, ServerModel model, IconRepository icons, Contact contact, - Avatar avatar) { - shownClient = cl; - shownChannel = null; - shownServer = null; - shownModel = model; - shownIcons = icons; - shownContact = contact; - shownAvatar = avatar; - render(); - } - - private void render() { - boolean selected = shownChannel != null || shownClient != null || shownServer != null; - boolean hide = inChatTab && selected; - if (descriptionHandler != null) descriptionHandler.setPanelHidden(hide); - toggle.setVisible(selected && !hide); - if (hide) { - descriptionHandler.showInfoTab(body(), this::onInfoTabClosed); - } else { - setHtml(body()); - } - } - - private String body() { - showsPictures = false; - if (shownServer != null) return html(Details.server(shownModel, shownServer), "", "", null, null); - if (shownChannel != null) return html(Details.channel(shownChannel), "", "", null, "No description."); - if (shownClient != null) { - renderedAvatarBox = inChatTab ? UIScale.scale(AvatarHtml.MAX_SIZE) : avatarBox(); - return clientBody(shownClient, shownModel, shownIcons, shownContact, shownAvatar, renderedAvatarBox); - } - return "Select the server, a channel or a client to see details."; - } - - /** - * How large an avatar may be drawn beside the details: a share of the panel's - * width, so a narrow panel keeps room for the text. Rounded to steps so that - * dragging a divider does not rebuild the HTML on every pixel. - */ - private int avatarBox() { - int width = scroll.getViewport().getWidth(); - int max = UIScale.scale(AvatarHtml.MAX_SIZE); - if (width <= 0) return max; - int step = UIScale.scale(AVATAR_BOX_STEP); - int box = width * 2 / 5 / step * step; - return Math.max(UIScale.scale(AVATAR_MIN_SIZE), Math.min(max, box)); - } - - private void showAvatarMenu(MouseEvent e) { - Avatar avatar = shownClient == null ? null : shownAvatar; - if (avatar == null || !overAvatar(avatar, e.getPoint())) return; - JPopupMenu menu = new JPopupMenu(); - String name = "avatar_" + shownClient.nickname; - menu.add(item("Save…", null, () -> saveAvatar(avatar, name))); - if (avatarHandler != null && !shownClient.self) { - if (avatarHandler.canSet()) menu.add(item("Steal for avatar", null, () -> avatarHandler.steal(avatar))); - ClientEntry client = shownClient; - if (avatarHandler.canDeleteOthers()) { - menu.add(item("Delete avatar", "DELETE_AVATAR_OTHER", () -> avatarHandler.deleteOf(client))); - } - } else if (avatarHandler != null) { - if (avatarHandler.canSet()) menu.add(item("Set avatar…", "UPLOAD_AVATAR", avatarHandler::set)); - menu.add(item("Delete avatar", "DELETE_AVATAR", avatarHandler::delete)); - } - menu.show(pane, e.getX(), e.getY()); - } - - private static JMenuItem item(String text, String icon, Runnable action) { - JMenuItem item = new JMenuItem(text, icon == null ? null : Icons.of(icon)); - item.addActionListener(e -> action.run()); - return item; - } - - /** Whether {@code point} falls on the avatar's {@code }. */ - private boolean overAvatar(Avatar avatar, Point point) { - if (avatar.file() == null) return false; - String src = avatar.file().toURI().toString(); - int pos = pane.viewToModel2D(point); - for (int at : new int[]{pos, pos - 1}) { - if (at < 0) continue; - var el = ((HTMLDocument) pane.getDocument()).getCharacterElement(at); - AttributeSet attrs = el.getAttributes(); - if (attrs.getAttribute(StyleConstants.NameAttribute) != HTML.Tag.IMG - || !src.equals(attrs.getAttribute(HTML.Attribute.SRC))) continue; - try { - Rectangle2D start = pane.modelToView2D(el.getStartOffset()); - Rectangle2D end = pane.modelToView2D(el.getEndOffset()); - if (start != null && end != null && start.createUnion(end).contains(point)) return true; - } catch (BadLocationException ignored) { - } - } - return false; - } - - private void saveAvatar(Avatar avatar, String name) { - JFileChooser chooser = new JFileChooser(); - chooser.setDialogTitle("Save avatar"); - chooser.setSelectedFile(new File(name + "." + avatar.format().extension)); - if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return; - try { - Files.write(chooser.getSelectedFile().toPath(), avatar.data()); - } catch (IOException ex) { - JOptionPane.showMessageDialog(this, "Could not save the avatar: " + ex.getMessage(), - "Error", JOptionPane.ERROR_MESSAGE); - } - } - - private String clientBody(ClientEntry cl, ServerModel model, IconRepository icons, Contact contact, - Avatar avatar, int avatarBox) { - String details = clientDetails(cl, model, icons, contact); - String picture = AvatarHtml.imgTag(avatar, avatarBox); - if (picture.isEmpty()) return details; - // The avatar sits top-right beside the details, like the official client's info frame. - return "" - + "" - + "" - + "
    " + details + "" + picture + "
    "; - } - - private String clientDetails(ClientEntry cl, ServerModel model, IconRepository icons, Contact contact) { - String you = cl.self ? " (you)" : ""; - // The country's flag goes before the name, as in TeamSpeak's info frame. - return html(Details.client(cl, model, contact), flagTag(cl.country), you, icons, null); - } - - /** - * @param titlePrefix HTML before the title - * @param titleSuffix HTML after the title - * @param icons for the icons of the groups a field names; null for none - * @param none what to say when there is no description; null to say nothing - */ - private String html(Details details, String titlePrefix, String titleSuffix, IconRepository icons, String none) { - StringBuilder sb = new StringBuilder(); - sb.append(heading(titlePrefix + esc(details.title()) + titleSuffix)); - for (Details.Field f : details.fields()) row(sb, esc(f.label()), value(f, icons)); - if (!details.description().isEmpty()) { - sb.append("
    ").append(description(details.description())).append("
    "); - } else if (details.pending()) { - sb.append("
    Loading description…"); - } else if (none != null) { - sb.append("
    ").append(none).append(""); - } - return sb.toString(); - } - - private static String value(Details.Field field, IconRepository icons) { - if (field.groups().isEmpty() || icons == null) return esc(field.value()); - StringBuilder sb = new StringBuilder(); - for (Group g : field.groups()) { - if (sb.length() > 0) sb.append(", "); - sb.append(iconTag(g, icons)).append(esc(g.name)); - } - return sb.toString(); - } - - private void setHtml(String body) { - pane.setText("" + body + ""); - pane.setCaretPosition(0); - } - - /** - * An inline {@code } for a group's icon, or nothing while the icon is missing - * or still downloading. Swing's HTML renderer only loads images by URL, so the icon - * is served from the repository's on-disk cache. - */ - private static String iconTag(Group group, IconRepository icons) { - if (group.iconId == 0) return ""; - File file = icons.file(group.iconId); - if (file == null) return ""; - return " "; - } - - /** An inline {@code } for a country's flag, or nothing for no country. */ - private static String flagTag(String country) { - File file = IconFiles.flag(country); - if (file == null) return ""; - return " "; - } - - private static String heading(String text) { - return "
    " + text + "
    "; - } - - private static void row(StringBuilder sb, String label, String value) { - sb.append("
    ") - .append(label).append(": ").append(value).append("
    "); - } - - /** Descriptions may carry BBCode markup, pictures included. */ - private String description(String bbcode) { - String html = BBCode.toHtml(bbcode, true); - if (!DescriptionPictures.hasPictures(html)) return html; - showsPictures = true; - renderedPictureWidth = pictureWidth(); - return pictures.html(html, renderedPictureWidth); - } - - /** - * How wide a picture may be: the panel's width inside its padding, in steps so that - * dragging a divider does not rebuild the HTML on every pixel. - */ - private int pictureWidth() { - if (inChatTab) return UIScale.scale(CHAT_TAB_PICTURE_WIDTH); - int step = UIScale.scale(PICTURE_WIDTH_STEP); - int width = scroll.getViewport().getWidth() - UIScale.scale(24); - return Math.max(step, width / step * step); - } - - private static String esc(String s) { - return BBCode.escape(s); - } - -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/InstanceChannel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/InstanceChannel.java deleted file mode 100644 index 580eaa8..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/InstanceChannel.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.config.AppDirs; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.StandardProtocolFamily; -import java.net.UnixDomainSocketAddress; -import java.nio.channels.Channels; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.function.Consumer; - -/** - * Lets a second launch of the client hand what it was started with (a {@code ts3server://} - * link a browser opened) to the instance already running on the same profile, over a Unix - * domain socket. - */ -public final class InstanceChannel { - - private static final int MAX_MESSAGE = 8192; - - private InstanceChannel() { - } - - /** - * In the user's private runtime directory where there is one, as a socket path may not be - * much over 100 bytes and a profile's can be longer; named after the profile, so each - * profile has an instance of its own. - */ - private static Path socketPath() { - String runtime = System.getenv("XDG_RUNTIME_DIR"); - if (runtime == null || runtime.isBlank()) return AppDirs.file("instance.sock").toPath(); - String profile = AppDirs.profile().getAbsolutePath(); - return Path.of(runtime, "ts3j-" + Integer.toHexString(profile.hashCode()) + ".sock"); - } - - /** Sends {@code message} to the running instance; false when there is none to take it. */ - public static boolean send(String message) { - try (SocketChannel channel = SocketChannel.open(UnixDomainSocketAddress.of(socketPath())); - OutputStream out = Channels.newOutputStream(channel)) { - out.write(message.getBytes(StandardCharsets.UTF_8)); - return true; - } catch (IOException | UnsupportedOperationException e) { - return false; - } - } - - /** Takes the messages later launches send, each on a thread of its own; quietly does nothing where it cannot. */ - public static void listen(Consumer onMessage) { - Path path = socketPath(); - ServerSocketChannel server; - try { - AppDirs.createProfile(); - // Left behind by an instance that did not exit cleanly; a live one answered send() already. - Files.deleteIfExists(path); - server = ServerSocketChannel.open(StandardProtocolFamily.UNIX); - server.bind(UnixDomainSocketAddress.of(path)); - path.toFile().deleteOnExit(); - } catch (IOException | UnsupportedOperationException e) { - System.err.println("Cannot take links from other launches: " + e); - return; - } - Thread accept = new Thread(() -> { - while (server.isOpen()) { - try (SocketChannel client = server.accept(); InputStream in = Channels.newInputStream(client)) { - String message = new String(in.readNBytes(MAX_MESSAGE), StandardCharsets.UTF_8).trim(); - if (!message.isEmpty()) onMessage.accept(message); - } catch (IOException e) { - if (!server.isOpen()) return; - } - } - }, "instance-channel"); - accept.setDaemon(true); - accept.start(); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/LevelMeter.java b/ts3-client/swing/src/main/java/com/ts3client/ui/LevelMeter.java deleted file mode 100644 index 1490238..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/LevelMeter.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.UIScale; - -import javax.swing.JComponent; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.RenderingHints; - -/** - * Horizontal audio level meter with an optional VAD threshold marker. The filled portion - * turns green once the level crosses the threshold, giving immediate visual feedback while - * tuning voice activation. - * - *

    Scaled to {@link com.ts3client.audio.InputLevel}, matching the TS3 client's slider. - */ -public final class LevelMeter extends JComponent { - - private static final double MIN_DB = com.ts3client.audio.InputLevel.MIN_DB; - private static final double MAX_DB = com.ts3client.audio.InputLevel.MAX_DB; - - private volatile double levelDb = MIN_DB; - private volatile double thresholdDb = -40.0; - private volatile boolean showThreshold = true; - private volatile boolean transmitting; - - public LevelMeter() { - setPreferredSize(UIScale.scale(new Dimension(240, 18))); - // A bare JComponent reports no minimum of its own, so a layout tight on space - // collapses the bar to nothing. Keep the height and let only the width give. - setMinimumSize(UIScale.scale(new Dimension(60, 18))); - setMaximumSize(new Dimension(Integer.MAX_VALUE, UIScale.scale(18))); - } - - public void setLevel(double db) { - this.levelDb = db; - repaint(); - } - - public void setThreshold(double db) { - this.thresholdDb = db; - repaint(); - } - - public void setShowThreshold(boolean show) { - this.showThreshold = show; - repaint(); - } - - /** - * Whether the gate is currently open. This is the real transmit decision, which in the - * Automatic and Hybrid modes depends on the speech detector and the hangover as well as - * on the level, so the bar cannot infer it from the threshold alone. - */ - public void setTransmitting(boolean transmitting) { - this.transmitting = transmitting; - repaint(); - } - - private int dbToX(double db, int w) { - double clamped = Math.max(MIN_DB, Math.min(MAX_DB, db)); - return (int) ((clamped - MIN_DB) / (MAX_DB - MIN_DB) * w); - } - - @Override - protected void paintComponent(Graphics g0) { - Graphics2D g = (Graphics2D) g0; - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - int w = getWidth(); - int h = getHeight(); - - g.setColor(new Color(0x2B2B2B)); - int arc = UIScale.scale(6); - g.fillRoundRect(0, 0, w - 1, h - 1, arc, arc); - - int level = dbToX(levelDb, w - 2); - g.setColor(transmitting ? Theme.talking() : new Color(0x5A9BD4)); - g.fillRoundRect(1, 1, Math.max(0, level), h - 3, arc - 1, arc - 1); - - if (showThreshold) { - int tx = dbToX(thresholdDb, w - 2); - g.setColor(new Color(0xF0C419)); - g.fillRect(tx, 1, UIScale.scale(2), h - 3); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/Links.java b/ts3-client/swing/src/main/java/com/ts3client/ui/Links.java deleted file mode 100644 index ff5f514..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/Links.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.session.ServerLink; - -import javax.swing.JOptionPane; -import java.awt.Component; -import java.awt.Desktop; -import java.net.URI; -import java.util.function.Consumer; - -/** - * Opens http(s) links from chat messages and descriptions in the system browser, and - * {@code ts3server://} links in the client itself. - */ -final class Links { - - private static volatile Consumer serverLinks; - - private Links() { - } - - /** Where {@code ts3server://} links go. */ - static void setServerLinkHandler(Consumer handler) { - serverLinks = handler; - } - - static void open(String href, Component parent) { - ServerLink link = ServerLink.parse(href); - Consumer handler = serverLinks; - if (link != null && handler != null) { - handler.accept(link); - return; - } - try { - URI uri = new URI(href); - String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(); - if (!scheme.equals("http") && !scheme.equals("https") && !scheme.equals("ftp")) return; - if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { - Desktop.getDesktop().browse(uri); - return; - } - } catch (Exception ignored) { - } - JOptionPane.showInputDialog(parent, "Could not open the link. Copy it instead:", href); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ListEditorDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ListEditorDialog.java deleted file mode 100644 index 593df11..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ListEditorDialog.java +++ /dev/null @@ -1,184 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; - -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.DefaultListModel; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JList; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ListSelectionModel; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.Window; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * A small modal editor for a list of text-keyed items: Add, Remove, optionally Move up and - * down, and OK/Cancel. Edits a copy and writes it back only on OK. - */ -abstract class ListEditorDialog extends JDialog { - - protected final DefaultListModel model = new DefaultListModel<>(); - protected final JList list = new JList<>(model); - private final String itemPrompt; - private final JPanel south = new JPanel(new BorderLayout(0, UIScale.scale(8))); - private boolean accepted; - - /** - * @param intro text above the list, or {@code null} - * @param itemPrompt what Add and a double-click ask for - * @param movable whether the order matters, offering Move up and down - */ - ListEditorDialog(Window owner, String title, String intro, String itemPrompt, List items, boolean movable) { - super(owner, title, ModalityType.APPLICATION_MODAL); - this.itemPrompt = itemPrompt; - items.forEach(model::addElement); - - list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - list.addListSelectionListener(e -> { - if (!e.getValueIsAdjusting()) selectionChanged(); - }); - list.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (e.getClickCount() == 2 && list.getSelectedIndex() >= 0) rename(list.getSelectedIndex()); - } - }); - JScrollPane scroll = new JScrollPane(list); - scroll.setPreferredSize(UIScale.scale(new Dimension(260, 200))); - - JPanel buttons = new JPanel(); - buttons.setLayout(new BoxLayout(buttons, BoxLayout.Y_AXIS)); - buttons.setOpaque(false); - addButton(buttons, "Add", this::add); - JButton remove = addButton(buttons, "Remove", this::remove); - JButton up = movable ? addButton(buttons, "Move Up", () -> move(-1)) : null; - JButton down = movable ? addButton(buttons, "Move Down", () -> move(1)) : null; - list.addListSelectionListener(e -> { - int i = list.getSelectedIndex(); - remove.setEnabled(i >= 0); - if (up != null) up.setEnabled(i > 0); - if (down != null) down.setEnabled(i >= 0 && i < model.size() - 1); - }); - remove.setEnabled(false); - if (up != null) up.setEnabled(false); - if (down != null) down.setEnabled(false); - - JPanel center = new JPanel(new BorderLayout(UIScale.scale(8), UIScale.scale(6))); - center.setOpaque(false); - if (intro != null) center.add(ReasonDialog.label(intro), BorderLayout.NORTH); - center.add(scroll, BorderLayout.CENTER); - center.add(buttons, BorderLayout.EAST); - - JButton ok = new JButton("OK"); - ok.addActionListener(e -> { - accepted = true; - dispose(); - }); - JButton cancel = new JButton("Cancel"); - cancel.addActionListener(e -> dispose()); - JPanel okCancel = new JPanel(new FlowLayout(FlowLayout.RIGHT, UIScale.scale(6), 0)); - okCancel.setOpaque(false); - okCancel.add(ok); - okCancel.add(cancel); - - south.setOpaque(false); - south.add(okCancel, BorderLayout.SOUTH); - - JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(8))); - content.setBackground(Theme.windowBg()); - content.setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); - content.add(center, BorderLayout.CENTER); - content.add(south, BorderLayout.SOUTH); - setContentPane(content); - getRootPane().setDefaultButton(ok); - Dialogs.closeOnEscape(this); - } - - /** Controls under the list acting on the selected item, or {@code null}. */ - protected JComponent extraControls() { - return null; - } - - protected void selectionChanged() { - } - - /** The item that {@code text} names, typed into Add, or a rename of {@code old} ({@code null} on Add). */ - protected abstract T item(String text, T old); - - protected abstract String text(T item); - - /** Shows the dialog; on OK copies the edited list into {@code target}. */ - protected boolean showAndApply(List target) { - JComponent extra = extraControls(); - if (extra != null) south.add(extra, BorderLayout.NORTH); - selectionChanged(); - pack(); - setLocationRelativeTo(getOwner()); - setVisible(true); - if (!accepted) return false; - target.clear(); - target.addAll(Collections.list(model.elements())); - return true; - } - - private JButton addButton(JPanel column, String text, Runnable action) { - JButton b = new JButton(text); - b.setAlignmentX(Component.LEFT_ALIGNMENT); - b.setMaximumSize(new Dimension(Integer.MAX_VALUE, b.getPreferredSize().height)); - b.addActionListener(e -> action.run()); - if (column.getComponentCount() > 0) column.add(Box.createVerticalStrut(UIScale.scale(4))); - column.add(b); - return b; - } - - private void add() { - String text = ask(itemPrompt, ""); - if (text == null) return; - model.addElement(item(text, null)); - list.setSelectedIndex(model.size() - 1); - } - - private void rename(int index) { - String text = ask(itemPrompt, text(model.get(index))); - if (text != null) model.set(index, item(text, model.get(index))); - } - - private String ask(String prompt, String initial) { - Object answer = JOptionPane.showInputDialog(this, prompt, getTitle(), JOptionPane.PLAIN_MESSAGE, - null, null, initial); - String text = answer == null ? null : answer.toString().trim(); - return text == null || text.isEmpty() ? null : text; - } - - private void remove() { - int i = list.getSelectedIndex(); - if (i < 0) return; - model.remove(i); - if (!model.isEmpty()) list.setSelectedIndex(Math.min(i, model.size() - 1)); - } - - private void move(int delta) { - int i = list.getSelectedIndex(); - int j = i + delta; - if (i < 0 || j < 0 || j >= model.size()) return; - List items = new ArrayList<>(Collections.list(model.elements())); - Collections.swap(items, i, j); - model.clear(); - items.forEach(model::addElement); - list.setSelectedIndex(j); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/LookAndFeelManager.java b/ts3-client/swing/src/main/java/com/ts3client/ui/LookAndFeelManager.java deleted file mode 100644 index 11ca10d..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/LookAndFeelManager.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.FlatDarkLaf; -import com.formdev.flatlaf.FlatLaf; -import com.formdev.flatlaf.FlatLightLaf; -import com.ts3client.config.Settings; - -import java.awt.Window; - -/** - * Installs FlatLaf in the requested variant and keeps {@link Theme} in step with it. - * - *

    The client's own look-and-feel defaults — rounded controls, and the darker palette - * the dark theme is built on — live beside this class as FlatLaf properties files, which - * FlatLaf loads on top of the theme's own. - */ -public final class LookAndFeelManager { - - /** Where our own FlatLaf properties files sit. */ - private static final String DEFAULTS_PACKAGE = "com.ts3client.ui.laf"; - - static { - // Registered once: FlatLaf keeps every registration, and install() runs again on - // each theme switch. - FlatLaf.registerCustomDefaultsSource(DEFAULTS_PACKAGE); - } - - private LookAndFeelManager() { - } - - /** Installs the look-and-feel for {@code appearance}. Call before building any window. */ - public static void install(Settings.Appearance appearance) { - FlatLaf laf = appearance == Settings.Appearance.DARK ? new FlatDarkLaf() : new FlatLightLaf(); - // Whatever look-and-feel stays installed on failure, Theme falls back to its own palette. - FlatLaf.setup(laf); - Theme.refresh(); - } - - /** - * Switches the look-and-feel of the running client. Components that read {@link Theme} - * while painting follow immediately; the ones that copied a colour when they were built - * are refreshed by the look-and-feel update. - */ - public static void switchTo(Settings.Appearance appearance) { - install(appearance); - IconTheme.get().refresh(); - FlatLaf.updateUI(); - for (Window w : Window.getWindows()) { - w.repaint(); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/MainFrame.java b/ts3-client/swing/src/main/java/com/ts3client/ui/MainFrame.java deleted file mode 100644 index 10dbcff..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/MainFrame.java +++ /dev/null @@ -1,1170 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.audio.AudioBackend; -import com.ts3client.audio.desktop.DesktopAudioBackend; -import com.ts3client.config.AppDirs; -import com.ts3client.config.AwayMessages; -import com.ts3client.config.BanReasonPresets; -import com.ts3client.config.Bookmark; -import com.ts3client.config.Bookmarks; -import com.ts3client.session.ServerLink; -import com.ts3client.config.IdentityStore; -import com.ts3client.config.Settings; -import com.ts3client.myts.ChatAttachments; -import com.ts3client.myts.MyTeamSpeakLogin; -import com.ts3client.teamspeak.TeamSpeakImporter; -import com.ts3client.contacts.ContactStore; -import com.ts3client.net.ChannelNode; -import com.ts3client.net.HostButton; -import com.ts3client.net.PictureDownloads; -import com.ts3client.session.SelfState; -import com.ts3client.session.ServerSession; -import com.ts3client.session.Sessions; -import com.ts3client.sound.SoundNotifier; -import com.ts3client.sound.SoundPlayer; -import com.ts3client.ui.tray.TrayBackend; - -import javax.swing.AbstractAction; -import javax.swing.JCheckBox; -import javax.swing.JCheckBoxMenuItem; -import javax.swing.JComponent; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.JTextField; -import javax.swing.KeyStroke; -import javax.swing.SwingUtilities; -import java.io.File; -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.GridLayout; -import java.awt.KeyboardFocusManager; -import java.awt.Taskbar; -import java.awt.event.ActionEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * The main application window: toolbar, tab bar, status bar and menus, hosting - * one {@link ServerTab} per open server connection. - * - *

    Several servers can be connected at once — their incoming voice is mixed - * into the same output — but only one of them owns the microphone at a time - * ("active" tab, marked in the tab strip and switched from the toolbar). - */ -public final class MainFrame extends JFrame implements ServerTabPane.Listener { - - private final Settings settings; - private final RecordingActions recordings; - private final Bookmarks bookmarks = Bookmarks.load(); - private final AwayMessages awayMessages = AwayMessages.load(); - private final IdentityStore identities; - private final MyTeamSpeakLogin myTeamSpeak = MyTeamSpeakLogin.load(); - /** Friends and blocked clients, shared by every connection. */ - private final ContactStore contacts = ContactStore.load(); - private final AudioBackend audio = new DesktopAudioBackend(); - private final PictureDownloads pictures = new PictureDownloads(new File(AppDirs.profile(), "pictures"), true); - /** Files shared in chat, kept in the myTeamSpeak account's cloud storage. */ - private final ChatAttachments attachments = new ChatAttachments(myTeamSpeak); - private final TextZoom chatZoom; - private final TextZoom infoZoom; - /** Sound pack playback, shared by every connection. */ - private final SoundNotifier sounds; - private final SoundPlayer soundPlayer; - - private final List tabs = new ArrayList<>(); - /** The tabs' sessions: who holds the microphone, and the state shared by every server. */ - private final Sessions sessions = new Sessions(() -> { - refreshTabs(); - updateTray(); - }); - private final ServerTabPane tabPane = new ServerTabPane(this); - - /** The tab whose views are on screen. */ - private ServerTab selected; - private BanReasonPresets banReasonPresets; - - private MainMenuBar menuBar; - private javax.swing.Timer statusTimer; - - /** Mirrors the active server's own client state next to the clock; set once the window is up. */ - private volatile TrayController tray; - private GiantPttWindow giantPtt; - private final DesktopNotifier notifier; - - private MainToolbar toolbar; - private StatusBar statusBar; - - /** Global hotkeys: the bindings, the matching engine and the platform input hook. */ - private final HotkeyService hotkeys; - - /** Guards {@link #shutdown()} so the window listener and JVM hook don't both run it. */ - private final AtomicBoolean shuttingDown = new AtomicBoolean(false); - private final Thread shutdownHook = new Thread(this::shutdown, "ts3j-shutdown"); - - public MainFrame(Settings settings) { - super("TS3J — TeamSpeak 3 Java Client"); - this.settings = settings; - this.recordings = new RecordingActions(this, settings); - this.chatZoom = new TextZoom(settings.chatZoom, z -> { - settings.chatZoom = z; - settings.save(); - }); - this.infoZoom = new TextZoom(settings.infoZoom, z -> { - settings.infoZoom = z; - settings.save(); - }); - this.identities = IdentityStore.load(settings); - new TeamSpeakImporter(identities, bookmarks, settings).seedIfFresh(); - this.sounds = new SoundNotifier(settings); - this.soundPlayer = audio.createSoundPlayer(settings); - this.sounds.setPlayer(soundPlayer); - this.notifier = new DesktopNotifier(this, settings); - pictures.addSource("tsattach:", attachments::fetchPicture); - // Any of the client's windows coming to the front counts, a dialog included. - KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("activeWindow", e -> { - if (e.getNewValue() != null) notifier.windowActivated(); - }); - this.hotkeys = new HotkeyService(new HotkeyActions(this), this::hotkeyArgumentChoices); - hotkeys.addKeyPressListener(() -> SwingUtilities.invokeLater(sessions::keyPressed)); - contacts.addListener(() -> SwingUtilities.invokeLater(this::contactsChanged)); - - setIconImages(Icons.appImages()); - // The macOS dock ignores window icons. - if (Taskbar.isTaskbarSupported() && Taskbar.getTaskbar().isSupported(Taskbar.Feature.ICON_IMAGE)) { - Taskbar.getTaskbar().setIconImage(Icons.app(256).getImage()); - } - // We tear the connections down ourselves on close, so don't let Swing kill the JVM. - setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); - addWindowListener(new WindowAdapter() { - @Override - public void windowClosing(WindowEvent e) { - quit(); - } - - @Override - public void windowOpened(WindowEvent e) { - // Docking waits for the panel to adopt the icon, so it must not hold up the window. - SwingUtilities.invokeLater(MainFrame.this::installTray); - } - }); - // Catches Ctrl+C / SIGTERM so we still leave the servers cleanly. - Runtime.getRuntime().addShutdownHook(shutdownHook); - setMinimumSize(UIScale.scale(new Dimension(720, 480))); - - menuBar = buildMenuBar(); - setJMenuBar(menuBar); - - toolbar = buildToolbar(); - add(toolbar, BorderLayout.NORTH); - // Switching the icon pack in the options dialog re-decorates the whole window. - IconTheme.get().addListener(() -> SwingUtilities.invokeLater(this::rebuildIcons)); - add(tabPane, BorderLayout.CENTER); - // The tree and the chat each claim Ctrl+F for themselves while they have the focus; - // from anywhere else it searches the chat. - getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) - .put(KeyStroke.getKeyStroke("control F"), "ts3-find"); - getRootPane().getActionMap().put("ts3-find", new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - if (selected != null) selected.chat().openFind(); - } - }); - statusBar = new StatusBar(() -> { - if (selected != null) selected.session().stopRecording(); - }, () -> { - if (selected != null) selected.showOfflineMessages(); - }); - statusBar.setVisible(settings.showStatusBar); - add(statusBar, BorderLayout.SOUTH); - - statusBar.setCodec(audio.description()); - - ServerTab first = newTab(); - selectTab(first); - first.chat().appendSystem("Welcome to the TS3J Swing client."); - first.chat().appendSystem("Use Connections → Connect to join a server."); - - Links.setServerLinkHandler(this::openServerLink); - - statusTimer = new javax.swing.Timer(3000, e -> updateConnectionStatus()); - statusTimer.start(); - setSize(UIScale.scale(new Dimension(880, 560))); - setLocationRelativeTo(null); - - // Deferred so the window is on screen before we start connecting. - List startup = bookmarks.startupBookmarks(); - if (!startup.isEmpty()) { - SwingUtilities.invokeLater(() -> { - for (Bookmark b : startup) connectToBookmark(b); - }); - } - } - - // ---- UI construction ---- - - private MainMenuBar buildMenuBar() { - return new MainMenuBar(bookmarks, new MainMenuBar.Listener() { - @Override - public void onConnect() { - showConnectDialog(); - } - - @Override - public void onDisconnect() { - doDisconnect(); - } - - @Override - public void onCloseTab() { - closeTab(selected); - } - - @Override - public void onQuit() { - quit(); - } - - @Override - public void onActivate() { - moveMicrophoneToSelectedTab(); - } - - @Override - public void onToggleMic() { - toolbar.clickMic(); - } - - @Override - public void onToggleSpeaker() { - toolbar.clickSpeaker(); - } - - @Override - public void onAwayToggle(boolean away) { - toggleAway(away); - } - - @Override - public void onAwayStatus() { - setAwayStatus(); - } - - @Override - public JPopupMenu buildAwayMenu() { - return MainFrame.this.buildAwayMenu(); - } - - @Override - public void onCommanderToggle(boolean commander) { - if (selected != null) selected.session().setCommander(commander); - } - - @Override - public void onChangeNickname() { - changeNickname(); - } - - @Override - public boolean isTalkPowerRequested() { - return selected != null && selected.session().isTalkRequested(); - } - - @Override - public void onRequestTalkPower() { - requestTalkPower(); - } - - @Override - public void onSetPhoneticNickname() { - setPhoneticNickname(); - } - - @Override - public boolean canSetAvatar() { - return selected != null && selected.session().canSetAvatar(); - } - - @Override - public void onSetAvatar() { - if (selected != null) selected.avatar().choose(); - } - - @Override - public boolean hasAvatar() { - return selected != null && selected.session().hasAvatar(); - } - - @Override - public void onDeleteAvatar() { - if (selected != null) selected.avatar().delete(); - } - - @Override - public void onGiantPtt() { - showGiantPtt(); - } - - @Override - public void onShowIdentities() { - showIdentities(); - } - - @Override - public void onShowContacts() { - showContacts(null); - } - - @Override - public boolean isRecording() { - return selected != null && selected.session().isRecording(); - } - - @Override - public void onStartRecording(boolean multitrack) { - if (selected != null) recordings.choose(selected.session(), multitrack); - } - - @Override - public void onStopRecording() { - if (selected != null) selected.session().stopRecording(); - } - - @Override - public void onShowOfflineMessages() { - if (selected != null) selected.showOfflineMessages(); - } - - @Override - public boolean canViewBanList() { - return selected != null && selected.session().canViewBanList(); - } - - @Override - public void onShowBanList() { - if (selected != null) selected.showBanList(banReasonPresets()); - } - - @Override - public boolean canViewComplaints() { - return selected != null && selected.session().canViewComplaints(); - } - - @Override - public void onShowComplaints() { - if (selected != null) selected.showComplaints(); - } - - @Override - public boolean canViewServerLog() { - return selected != null && selected.session().canViewServerLog(); - } - - @Override - public void onShowServerLog() { - if (selected != null) selected.showServerLog(); - } - - @Override - public boolean canListPrivilegeKeys() { - return selected != null && selected.session().canListPrivilegeKeys(); - } - - @Override - public void onShowPrivilegeKeys() { - if (selected != null) selected.showPrivilegeKeys(); - } - - @Override - public void onUsePrivilegeKey() { - if (selected != null) selected.usePrivilegeKey(); - } - - @Override - public void onShowSettings() { - showSettings(); - } - - @Override - public void onShowAbout() { - showAbout(); - } - - @Override - public void onConnectBookmark(Bookmark bookmark, boolean newTab) { - if (newTab) selectTab(newTab()); - connectToBookmark(bookmark); - } - - @Override - public void onAddCurrentServerBookmark() { - addCurrentServerBookmark(); - } - - @Override - public void onManageBookmarks() { - new BookmarksDialog(MainFrame.this, bookmarks, identities, settings, - MainFrame.this::connectToBookmark, menuBar::rebuildBookmarks).setVisible(true); - } - }); - } - - private MainToolbar buildToolbar() { - return new MainToolbar(settings, new MainToolbar.Listener() { - @Override - public void onConnect() { - showConnectDialog(); - } - - @Override - public void onDisconnect() { - doDisconnect(); - } - - @Override - public void onActivate() { - moveMicrophoneToSelectedTab(); - } - - @Override - public void onMicMuteToggle(boolean muted) { - if (selected == null) return; - selected.session().setMicMuted(muted); - updateToolbar(); - } - - @Override - public void onDeafenToggle(boolean deafened) { - if (selected == null) return; - selected.session().setDeafened(deafened); - updateToolbar(); - } - - @Override - public void onAwayToggle(boolean away) { - toggleAway(away); - } - - @Override - public JPopupMenu buildAwayMenu() { - return MainFrame.this.buildAwayMenu(); - } - - @Override - public void onSettings() { - showSettings(); - } - - @Override - public void onMasterVolumeChanged() { - applyOutputSettingsToAllTabs(); - } - - @Override - public void onStatusBarVisibilityChanged(boolean visible) { - statusBar.setVisible(visible); - revalidate(); - repaint(); - } - }, pictures); - } - - /** Rebuilds the icon-bearing chrome after the active icon pack changed. */ - private void rebuildIcons() { - setIconImages(Icons.appImages()); - menuBar = buildMenuBar(); - setJMenuBar(menuBar); - remove(toolbar); - toolbar = buildToolbar(); - add(toolbar, BorderLayout.NORTH); - updateToolbar(); - refreshTabs(); - if (tray != null) tray.refreshIcon(); - revalidate(); - repaint(); - } - - // ---- tab management ---- - - private ServerTab newTab() { - ServerTab tab = new ServerTab(this, settings, identities, audio, sounds, contacts, pictures); - tabs.add(tab); - sessions.add(tab.session()); - tabPane.addTab(tab); - refreshTabs(); - return tab; - } - - /** The tab a new connection should use: the current one if it is free, else a new one. */ - private ServerTab tabForNewConnection() { - if (selected != null && !selected.session().isBusy()) return selected; - ServerTab tab = newTab(); - selectTab(tab); - return tab; - } - - @Override - public void selectTab(ServerTab tab) { - if (tab == null || !tabs.contains(tab)) return; - selected = tab; - tabPane.setSelected(tab); - refreshTabs(); - updateToolbar(); - updateStatusLabel(); - } - - @Override - public void closeTab(ServerTab tab) { - if (tab == null) return; - tab.session().disconnect(); - if (tabs.size() == 1) return; // always keep one view around - - tabs.remove(tab); - tab.session().dispose(); - tabPane.removeTab(tab); - if (selected == tab) { - selected = null; - selectTab(tabs.get(0)); - } else { - selectTab(selected); // the pane rebuilt itself; restore the selection - } - sessions.remove(tab.session()); - } - - /** The tab that holds the capture device; null when nobody is capturing. */ - private ServerTab micTab() { - ServerSession owner = sessions.microphoneOwner(); - for (ServerTab tab : tabs) { - if (tab.session() == owner) return tab; - } - return null; - } - - /** Repaints the tab labels (title, microphone marker). */ - private void refreshTabs() { - tabPane.refresh(micTab()); - } - - // ---- callbacks from ServerTab ---- - - /** A tab's title, status or connection state changed. */ - void tabUpdated(ServerTab tab) { - if (!tabs.contains(tab)) return; - refreshTabs(); - if (tab == selected) { - updateToolbar(); - updateStatusLabel(); - } - updateTray(); - } - - /** The server on {@code tab} may have changed its host button. */ - void refreshHostButton(ServerTab tab) { - if (tab == selected) toolbar.showHostButton(hostButtonOf(tab)); - } - - /** Bookmarks leading to the server on {@code tab} take on its icon. */ - void serverIconChanged(ServerTab tab, long iconId) { - if (!bookmarks.rememberServerIcon(tab.session().address(), tab.session().port(), iconId)) return; - bookmarks.save(); - menuBar.rebuildBookmarks(); - } - - /** The local client on {@code tab} started or stopped talking, muted itself, … */ - void selfStateChanged(ServerTab tab) { - if (!tabs.contains(tab)) return; - updateTray(); - if (giantPtt != null) giantPtt.refresh(); - } - - void tabConnected(ServerTab tab) { - if (!tabs.contains(tab)) return; - sessions.connected(tab.session()); - tabUpdated(tab); - } - - void tabDisconnected(ServerTab tab) { - if (!tabs.contains(tab)) return; - sessions.disconnected(tab.session()); - notifier.forget(tab); - tabUpdated(tab); - } - - /** Tells the user of a poke or a private message while the client is in the background. */ - TextZoom chatZoom() { - return chatZoom; - } - - TextZoom infoZoom() { - return infoZoom; - } - - DesktopNotifier notifier() { - return notifier; - } - - /** The tray icon when AWT docked it, whose messages are the notifications on Windows and macOS. */ - TrayBackend awtTray() { - TrayController current = tray; - return current == null ? null : current.backend(); - } - - // ---- hotkeys ---- - - /** - * Which connections a fired hotkey reaches: with "on active server" ticked only the - * selected tab, otherwise every connected one. - */ - List hotkeyTargets(boolean activeServerOnly) { - List out = new ArrayList<>(); - if (activeServerOnly) { - if (selected != null && selected.session().isConnected()) out.add(selected); - return out; - } - for (ServerTab tab : tabs) { - if (tab.session().isConnected()) out.add(tab); - } - return out; - } - - RecordingActions recordings() { - return recordings; - } - - ServerTab selectedTab() { - return selected; - } - - List allTabs() { - return new ArrayList<>(tabs); - } - - /** Opens the microphone while a push-to-talk hotkey is held. */ - void setPushToTalk(boolean talking) { - sessions.setPushToTalk(talking); - } - - private void showGiantPtt() { - if (giantPtt == null || !giantPtt.isDisplayable()) { - giantPtt = new GiantPttWindow(this, sessions::setForceTransmit, () -> { - ServerSession owner = sessions.microphoneOwner(); - SelfState state = owner == null ? null : owner.selfState(); - return state == SelfState.TALKING || state == SelfState.COMMANDER_TALKING; - }); - } - giantPtt.setVisible(true); - giantPtt.toFront(); - } - - void moveMicrophoneToSelectedTab() { - if (selected != null && selected.session().isConnected()) sessions.giveMicrophoneTo(selected.session()); - updateToolbar(); - } - - /** Connects to the bookmark with this label; no label means the first one. */ - void connectBookmark(String label, boolean newTab) { - Bookmark match = null; - for (Bookmark b : bookmarks.all()) { - if (label == null || label.isBlank() || label.equalsIgnoreCase(b.label)) { - match = b; - break; - } - } - if (match == null) return; - if (newTab) selectTab(newTab()); - connectToBookmark(match); - } - - /** Selects the tab with this 1-based number, as the "Select Server Tab" action names it. */ - void selectTabNumber(int number) { - if (number >= 1 && number <= tabs.size()) selectTab(tabs.get(number - 1)); - } - - void stepTab(int delta) { - if (tabs.isEmpty()) return; - int index = Math.max(0, tabs.indexOf(selected)); - selectTab(tabs.get(Math.floorMod(index + delta, tabs.size()))); - } - - void setSoundsMuted(boolean muted) { - sounds.setMuted(muted); - } - - boolean areSoundsMuted() { - return sounds.isMuted(); - } - - void adjustMasterVolume(double delta) { - settings.outputVolume = Math.max(0, Math.min(2.0, settings.outputVolume + delta)); - settings.save(); - applyOutputSettingsToAllTabs(); - updateStatusLabel(); - } - - /** Applies a new nickname, or asks for one when the hotkey carries none. */ - void changeNickname(String nickname) { - if (nickname == null || nickname.isBlank()) { - changeNickname(); - return; - } - settings.nickname = nickname.trim(); - settings.save(); - sessions.setNickname(settings.nickname); - } - - void browseCurrentChannel() { - if (selected == null || !selected.session().isConnected()) return; - ChannelNode channel = selected.session().currentChannel(); - if (channel != null) selected.browseFiles(channel); - } - - void reloadSkin() { - IconTheme.get().reload(settings); - } - - /** Brings the window back from the tray, the taskbar or behind other windows. */ - void bringToFront() { - TrayController current = tray; - if (current != null) { - // The tray can ask the window manager in a way it honours for a window without focus. - current.show(); - return; - } - setVisible(true); - setExtendedState(getExtendedState() & ~JFrame.ICONIFIED); - toFront(); - requestFocus(); - } - - void sendToBack() { - setExtendedState(getExtendedState() | JFrame.ICONIFIED); - } - - /** - * The values a parameterised hotkey action can take, for the tree in the hotkey - * dialog: the saved bookmarks, the installed sound packs and the channels of the - * server on screen. - */ - private List hotkeyArgumentChoices(com.ts3client.hotkey.HotkeyAction action) { - List out = new ArrayList<>(); - switch (action.argument()) { - case BOOKMARK -> { - for (Bookmark b : bookmarks.all()) { - if (b.label != null && !b.label.isBlank()) out.add(b.label); - } - } - case PROFILE -> { - if (action == com.ts3client.hotkey.HotkeyAction.SOUNDPACK_ACTIVATE) { - for (com.ts3client.sound.SoundPack pack : sounds.availablePacks()) out.add(pack.name()); - } - } - case CHANNEL -> { - if (selected != null && selected.session().isConnected()) { - out.addAll(selected.session().channelPaths()); - } - } - default -> { - } - } - return out; - } - - /** Repaints the chrome after a hotkey changed the local client's state. */ - void refreshAfterHotkey() { - updateToolbar(); - updateTray(); - refreshTabs(); - } - - // ---- actions ---- - - private void showConnectDialog() { - ConnectDialog dlg = new ConnectDialog(this, settings, identities); - dlg.setVisible(true); - if (!dlg.isConfirmed()) return; - startConnection(dlg.getAddress(), dlg.getPort(), dlg.getNickname(), dlg.getPassword(), - dlg.getIdentityId(), "", ""); - } - - /** - * Opens a connection in the current tab when it is free, otherwise in a new one. - * - * @param identityId identity to use, or empty for the default one - * @param channel channel path to join on connect, or empty for the default channel - * @param channelPassword password for that channel, if any - */ - private void startConnection(String address, int port, String nickname, String password, String identityId, - String channel, String channelPassword) { - startConnection(address, port, nickname, password, identityId, channel, channelPassword, false); - } - - /** - * @param replaceCurrent connect on the current tab, leaving the server it is on, instead of - * moving to a free tab - */ - private void startConnection(String address, int port, String nickname, String password, String identityId, - String channel, String channelPassword, boolean replaceCurrent) { - settings.lastAddress = address + ":" + port; - if (!nickname.isBlank()) settings.nickname = nickname; - settings.serverPassword = password; - settings.save(); - - ServerTab tab = (replaceCurrent && selected != null) ? selected : tabForNewConnection(); - // The first connection to come up takes the microphone; later ones are muted - // until the user activates them. - if (sessions.microphoneOwner() == null) sessions.giveMicrophoneTo(tab.session()); - tab.session().switchTo(address, port, nickname, password, identityId, channel, channelPassword); - } - - /** Opens a {@code ts3server://} link handed over by the system or a later launch. */ - public void openLink(String href) { - ServerLink link = ServerLink.parse(href); - if (link == null) return; - bringToFront(); - openServerLink(link); - } - - /** Goes where a link leads: on a server we are on already, to its channel; else connects there. */ - private void openServerLink(ServerLink link) { - if (!link.bookmarkLabel.isEmpty()) { - bookmarks.add(link.toBookmark()); - bookmarks.save(); - menuBar.rebuildBookmarks(); - } - for (ServerTab tab : tabs) { - if (tab.session().isOn(link)) { - selectTab(tab); - tab.session().follow(link); - return; - } - } - ServerTab tab = tabForNewConnection(); - if (sessions.microphoneOwner() == null) sessions.giveMicrophoneTo(tab.session()); - tab.session().open(link, ""); - } - - /** Connects on the current tab, leaving whatever server it is on. */ - private void connectToBookmark(Bookmark b) { - startConnection(b.address, b.port, b.nickname == null ? "" : b.nickname, b.password, b.identityId, b.channel, b.channelPassword, true); - } - - private void addCurrentServerBookmark() { - if (selected == null || !selected.session().isConnected()) { - JOptionPane.showMessageDialog(this, "Connect to a server first.", - "Add bookmark", JOptionPane.INFORMATION_MESSAGE); - return; - } - String channelPath = selected.session().currentChannelPath(); - - JTextField labelField = new JTextField(selected.session().title()); - JCheckBox joinChannel = new JCheckBox("Join \"" + channelPath + "\" on connect", !channelPath.isEmpty()); - JPanel form = new JPanel(new GridLayout(0, 1, 0, UIScale.scale(2))); - form.add(new JLabel("Bookmark label:")); - form.add(labelField); - if (!channelPath.isEmpty()) form.add(joinChannel); - if (JOptionPane.showConfirmDialog(this, form, "Add bookmark", - JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) != JOptionPane.OK_OPTION) { - return; - } - Bookmark bookmark = selected.session().toBookmark(joinChannel.isSelected() ? channelPath : ""); - bookmark.label = labelField.getText().trim(); - bookmarks.add(bookmark); - bookmarks.save(); - menuBar.rebuildBookmarks(); - } - - /** The away button's drop-down: the global actions, the presets and their editor. */ - private JPopupMenu buildAwayMenu() { - JPopupMenu menu = new JPopupMenu(); - boolean anyConnected = sessions.anyConnected(); - - JCheckBoxMenuItem globally = new JCheckBoxMenuItem("Set Globally Away", Icons.of("AWAY"), - sessions.isAwayEverywhere()); - globally.setEnabled(anyConnected); - globally.addActionListener(e -> setAwayEverywhere(globally.isSelected(), null)); - - JMenuItem globalStatus = new JMenuItem("Set Globally Away Status…", Icons.of("EDIT")); - globalStatus.setEnabled(anyConnected); - globalStatus.addActionListener(e -> { - String message = askAwayMessage(sessions.awayMessage(selected == null ? null : selected.session())); - if (message != null) setAwayEverywhere(true, message); - }); - - menu.add(globally); - menu.add(globalStatus); - menu.addSeparator(); - - for (String preset : awayMessages.all()) { - JMenuItem item = new JMenuItem(preset); - item.setEnabled(anyConnected); - item.addActionListener(e -> setAwayEverywhere(true, preset)); - menu.add(item); - } - if (!awayMessages.all().isEmpty()) menu.addSeparator(); - - JMenuItem manage = new JMenuItem("Manage away messages…", Icons.of("EDIT")); - manage.addActionListener(e -> new AwayMessagesDialog(this, awayMessages, null).setVisible(true)); - menu.add(manage); - return menu; - } - - private void toggleAway(boolean away) { - if (selected == null) return; - selected.session().setAway(away, ""); - updateToolbar(); - } - - /** Sets the away message on the selected server only. */ - private void setAwayStatus() { - if (selected == null) return; - String message = askAwayMessage(selected.session().awayMessage()); - if (message == null) return; - selected.session().setAway(true, message); - updateToolbar(); - } - - private void setAwayEverywhere(boolean away, String message) { - sessions.setAwayEverywhere(away, message); - updateToolbar(); - } - - /** @return the entered message (possibly empty), or null when cancelled */ - private String askAwayMessage(String initial) { - return (String) JOptionPane.showInputDialog(this, "Away message (optional):", "Away status", - JOptionPane.PLAIN_MESSAGE, Icons.of("AWAY"), null, initial); - } - - private void doDisconnect() { - if (selected != null) selected.session().disconnect(); - } - - /** - * Tear everything down before the process exits: disconnect from every server - * synchronously (so the "Leaving" notification actually reaches them) and stop - * background timers. Idempotent and safe to call from any thread — the window - * close handler, the Quit menu and the JVM shutdown hook may all invoke it. - */ - private void shutdown() { - if (!shuttingDown.compareAndSet(false, true)) return; - if (statusTimer != null) statusTimer.stop(); - settings.save(); // keeps the layout the user left behind (info panel height, …) - try { - Runtime.getRuntime().removeShutdownHook(shutdownHook); - } catch (IllegalStateException ignored) { - // Already shutting down (hook itself is running); nothing to remove. - } - sessions.shutdown(); - contacts.flush(); - soundPlayer.shutdown(); - hotkeys.dispose(); - if (tray != null) tray.dispose(); - notifier.shutdown(); - // Ends the sharing session if myTeamSpeak answers soon; it expires on its own otherwise. - try { - Thread.ofVirtual().start(attachments::close).join(2000); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - } - - /** Leaves every server and ends the process. */ - private void quit() { - shutdown(); - System.exit(0); - } - - /** Loaded the first time a ban dialog needs them, and shared by every tab from then on. */ - private BanReasonPresets banReasonPresets() { - if (banReasonPresets == null) banReasonPresets = BanReasonPresets.load(); - return banReasonPresets; - } - - private void showIdentities() { - new IdentitiesDialog(this, identities, settings, bookmarks, null).setVisible(true); - } - - Settings settings() { - return settings; - } - - /** The one contacts window, kept so a second request brings it forward instead of doubling it. */ - private ContactsDialog contactsDialog; - - /** - * Opens the contact list, or brings it forward. - * - * @param uniqueId the contact to select, or {@code null} to keep the current selection - */ - void showContacts(String uniqueId) { - if (contactsDialog == null || !contactsDialog.isDisplayable()) { - contactsDialog = new ContactsDialog(this, contacts, settings); - } - if (uniqueId != null) contactsDialog.select(uniqueId); - contactsDialog.setVisible(true); - contactsDialog.toFront(); - } - - /** The contact list changed somewhere: every open server follows. */ - private void contactsChanged() { - for (ServerTab tab : tabs) tab.contactsChanged(); - } - - private void showSettings() { - // Device and voice-gating changes apply to the capturing connection and the - // playback of the visible one; the rest pick the new settings up on connect. - SettingsDialog dlg = new SettingsDialog(this, settings, audio, - sessions.microphoneOwner() == null ? null : sessions.microphoneOwner().connection().getMicrophone(), - selected == null ? null : selected.connection().getPlayback(), - sounds, hotkeys, - new MyTeamSpeakPanel(myTeamSpeak, new TeamSpeakImporter(identities, bookmarks, settings), - menuBar::rebuildBookmarks, this::myTeamSpeakChanged), - () -> { - applyOutputSettingsToAllTabs(); - contactsChanged(); - }); - dlg.setVisible(true); - } - - /** Signed in to or out of myTeamSpeak: sharing in chat follows. */ - private void myTeamSpeakChanged() { - boolean signedIn = myTeamSpeak.isSignedIn(); - for (ServerTab tab : tabs) tab.chat().setSharingAvailable(signedIn); - if (signedIn) { - pictures.retryFailed(); - } else { - Thread.ofVirtual().name("myteamspeak-sign-out").start(attachments::close); - } - } - - ChatAttachments attachments() { - return attachments; - } - - /** Whether files can be shared in chat: that needs a myTeamSpeak account. */ - boolean canShareFiles() { - return myTeamSpeak.isSignedIn(); - } - - /** Master volume, output device and receive buffer are global, so push them to every open connection. */ - private void applyOutputSettingsToAllTabs() { - soundPlayer.setOutputDevice(settings.outputDevice); - for (ServerTab tab : tabs) { - if (tab.connection().getPlayback() == null) continue; - tab.connection().getPlayback().setMasterVolume(settings.effectiveOutputVolume()); - tab.connection().getPlayback().setOutputDevice(settings.outputDevice); - tab.connection().getPlayback().setReceiveBuffer(settings.receiveBuffer); - } - } - - private void changeNickname() { - String n = JOptionPane.showInputDialog(this, "New nickname:", settings.nickname); - if (n != null && !n.trim().isEmpty()) { - settings.nickname = n.trim(); - settings.save(); - for (ServerTab tab : tabs) tab.session().setNickname(settings.nickname); - } - } - - /** Asks for a reason and requests talk power, or withdraws the pending request. */ - private void requestTalkPower() { - if (selected == null) return; - if (selected.session().isTalkRequested()) { - selected.session().cancelTalkRequest(); - return; - } - String message = (String) JOptionPane.showInputDialog(this, "Reason:", "Request Talk Power", - JOptionPane.PLAIN_MESSAGE, Icons.of("TALK_POWER_REQUEST"), null, ""); - if (message != null) selected.session().requestTalkPower(message.trim()); - } - - private void setPhoneticNickname() { - if (selected == null) return; - String phonetic = (String) JOptionPane.showInputDialog(this, "Phonetic nickname:", "Set Phonetic Nickname", - JOptionPane.PLAIN_MESSAGE, Icons.of("PHONETICSNICKNAME"), null, - selected.session().phoneticNickname()); - if (phonetic != null) selected.session().setPhoneticNickname(phonetic.trim()); - } - - private void showAbout() { - JOptionPane.showMessageDialog(this, - "TS3J Swing Client\n\n" + - "An open-source TeamSpeak 3 desktop client built on the ts3j\n" + - "reverse-engineered protocol library, with native Opus voice,\n" + - "voice-activation detection and push-to-talk.\n\n" + - statusBar.codecText(), - "About TS3J", JOptionPane.INFORMATION_MESSAGE); - } - - // ---- toolbar / status ---- - - private void updateToolbar() { - boolean connected = selected != null && selected.session().isConnected(); - boolean anyConnected = sessions.anyConnected(); - - boolean micMuted = connected && selected.session().isMicMuted(); - boolean deaf = connected && selected.session().isDeafened(); - boolean active = selected != null && selected == micTab(); - boolean away = connected && selected.session().isAway(); - boolean commander = connected && selected.session().isCommander(); - toolbar.refresh(connected, anyConnected, micMuted, deaf, active, away); - toolbar.showHostButton(hostButtonOf(selected)); - menuBar.refresh(connected, anyConnected, micMuted, deaf, active, away, commander); - statusBar.showRecording(connected && selected.session().isRecording()); - statusBar.showUnreadMessages(connected ? selected.connection().unreadOfflineMessages() : 0); - updateTray(); - } - - private static HostButton hostButtonOf(ServerTab tab) { - return tab != null && tab.session().isConnected() ? tab.connection().getModel().hostButton() : null; - } - - /** - * The server the tray icon speaks for: the one holding the microphone, or the - * visible one when nobody is capturing. - */ - private ServerTab trayTab() { - ServerTab micTab = micTab(); - if (micTab != null && micTab.session().isConnected()) return micTab; - return selected != null && selected.session().isConnected() ? selected : null; - } - - private void installTray() { - if (shuttingDown.get()) return; - tray = new TrayController(this, this::quit); - updateTray(); - } - - private void updateTray() { - if (tray == null) return; - ServerTab tab = trayTab(); - if (tab == null) { - tray.update(SelfState.DISCONNECTED, null); - } else { - tray.update(tab.session().selfState(), tab.session().title()); - } - } - - private void updateStatusLabel() { - statusBar.setStatus(selected == null ? "Not connected" : selected.session().status()); - } - - private void updateConnectionStatus() { - ServerTab tab = selected; - if (tab == null || !tab.session().isConnected()) return; - int users = tab.connection().getModel().clientCount(); - StringBuilder s = new StringBuilder("Connected to ") - .append(tab.connection().getModel().getServerName()) - .append(" | ").append(users).append(users == 1 ? " user" : " users"); - double ping = tab.connection().getPingMillis(); - if (ping >= 0) s.append(" | ping ").append(Math.round(ping)).append(" ms"); - if (tab != micTab()) s.append(" | microphone on another tab"); - statusBar.setStatus(s.toString()); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/MainMenuBar.java b/ts3-client/swing/src/main/java/com/ts3client/ui/MainMenuBar.java deleted file mode 100644 index f67bf3e..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/MainMenuBar.java +++ /dev/null @@ -1,449 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.config.Bookmark; -import com.ts3client.config.Bookmarks; - -import javax.swing.ImageIcon; -import javax.swing.JCheckBoxMenuItem; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; -import javax.swing.KeyStroke; -import javax.swing.MenuSelectionManager; -import javax.swing.SwingUtilities; -import javax.swing.event.MenuEvent; -import javax.swing.event.MenuListener; -import java.awt.Component; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; - -/** - * The main window's menu bar: Connections, Bookmarks, Self, Permissions, Tools and Help. - * Talks to {@link MainFrame} only through {@link Listener}; the away/commander - * item states are pushed in by {@link #refresh}, mirroring how {@link MainToolbar} - * is kept in sync. - */ -final class MainMenuBar extends JMenuBar { - - interface Listener { - void onConnect(); - - void onDisconnect(); - - void onCloseTab(); - - void onQuit(); - - /** Moves the microphone to the tab on screen. */ - void onActivate(); - - void onToggleMic(); - - void onToggleSpeaker(); - - /** The plain toggle carries no message; "Set away status…" is where messages are chosen. */ - void onAwayToggle(boolean away); - - void onAwayStatus(); - - /** The away button's drop-down, which the "Set Away" submenu mirrors. */ - JPopupMenu buildAwayMenu(); - - void onCommanderToggle(boolean commander); - - void onChangeNickname(); - - /** Whether our talk power request is pending; asked as the Self menu opens. */ - boolean isTalkPowerRequested(); - - /** Requests talk power, or withdraws a pending request. */ - void onRequestTalkPower(); - - void onSetPhoneticNickname(); - - /** Whether the current server lets us upload an avatar; asked as the Self menu opens. */ - boolean canSetAvatar(); - - void onSetAvatar(); - - /** Whether we have an avatar on the current server to delete; asked as the Self menu opens. */ - boolean hasAvatar(); - - void onDeleteAvatar(); - - void onGiantPtt(); - - void onShowIdentities(); - - void onShowContacts(); - - void onShowOfflineMessages(); - - /** Whether the current tab is recording; asked as the Tools menu opens. */ - boolean isRecording(); - - void onStartRecording(boolean multitrack); - - void onStopRecording(); - - /** Whether the current server lets us read its ban list; asked as the Tools menu opens. */ - boolean canViewBanList(); - - void onShowBanList(); - - /** Whether the current server lets us read its complaints; asked as the Tools menu opens. */ - boolean canViewComplaints(); - - void onShowComplaints(); - - /** Whether the current server lets us read its log; asked as the Tools menu opens. */ - boolean canViewServerLog(); - - void onShowServerLog(); - - /** Whether the current server lets us list its privilege keys; asked as the Permissions menu opens. */ - boolean canListPrivilegeKeys(); - - void onShowPrivilegeKeys(); - - void onUsePrivilegeKey(); - - void onShowSettings(); - - void onShowAbout(); - - /** @param newTab open the server in a new tab instead of replacing the current one */ - void onConnectBookmark(Bookmark bookmark, boolean newTab); - - void onAddCurrentServerBookmark(); - - void onManageBookmarks(); - } - - private final Bookmarks bookmarks; - private final Listener listener; - - private JMenu bookmarksMenu; - private JMenu awayMenu; - private JMenuItem activateItem; - private JMenuItem muteItem; - private JMenuItem deafItem; - private JCheckBoxMenuItem awayItem; - private JMenuItem awayStatusItem; - private JCheckBoxMenuItem commanderItem; - private JMenuItem talkPowerItem; - private JMenuItem phoneticItem; - private JMenuItem avatarItem; - private JMenuItem deleteAvatarItem; - private JMenuItem startRecordingItem; - private JMenuItem startMultitrackItem; - private JMenuItem stopRecordingItem; - private JMenuItem offlineMessagesItem; - private JMenuItem banListItem; - private JMenuItem complaintsItem; - private JMenuItem serverLogItem; - private JMenuItem privilegeKeysItem; - private JMenuItem usePrivilegeKeyItem; - - MainMenuBar(Bookmarks bookmarks, Listener listener) { - this.bookmarks = bookmarks; - this.listener = listener; - - JMenu connections = new JMenu("Connections"); - JMenuItem connect = new JMenuItem("Connect…", Icons.of("CONNECT")); - connect.setAccelerator(KeyStroke.getKeyStroke("control S")); - connect.addActionListener(e -> listener.onConnect()); - JMenuItem disconnect = new JMenuItem("Disconnect", Icons.of("DISCONNECT")); - disconnect.setAccelerator(KeyStroke.getKeyStroke("control D")); - disconnect.addActionListener(e -> listener.onDisconnect()); - JMenuItem closeTab = new JMenuItem("Close tab", Icons.of("CLOSE_BUTTON")); - closeTab.setAccelerator(KeyStroke.getKeyStroke("control W")); - closeTab.addActionListener(e -> listener.onCloseTab()); - JMenuItem quit = new JMenuItem("Quit", Icons.of("QUIT")); - quit.setAccelerator(KeyStroke.getKeyStroke("control Q")); - quit.addActionListener(e -> listener.onQuit()); - connections.add(connect); - connections.add(disconnect); - connections.add(closeTab); - connections.addSeparator(); - connections.add(quit); - - bookmarksMenu = new JMenu("Bookmarks"); - rebuildBookmarks(); - // A server's icon may have finished downloading since the menu was built. - bookmarksMenu.addMenuListener(new MenuListener() { - @Override - public void menuSelected(MenuEvent e) { - rebuildBookmarks(); - } - - @Override - public void menuDeselected(MenuEvent e) { - } - - @Override - public void menuCanceled(MenuEvent e) { - } - }); - - JMenu self = new JMenu("Self"); - awayMenu = new JMenu("Set Away"); - awayMenu.setIcon(Icons.of("AWAY")); - awayMenu.addMenuListener(new MenuListener() { - @Override - public void menuSelected(MenuEvent e) { - rebuildAwayMenu(); - } - - @Override - public void menuDeselected(MenuEvent e) { - } - - @Override - public void menuCanceled(MenuEvent e) { - } - }); - activateItem = new JMenuItem("Activate Microphone", Icons.of("ACTIVATE_MICROPHONE")); - activateItem.addActionListener(e -> listener.onActivate()); - muteItem = new JMenuItem(); - muteItem.addActionListener(e -> listener.onToggleMic()); - deafItem = new JMenuItem(); - deafItem.addActionListener(e -> listener.onToggleSpeaker()); - showMuted(false, false); - awayItem = new JCheckBoxMenuItem("Away", Icons.of("AWAY"), false); - awayItem.addActionListener(e -> listener.onAwayToggle(awayItem.isSelected())); - awayStatusItem = new JMenuItem("Set away status…", Icons.of("EDIT")); - awayStatusItem.addActionListener(e -> listener.onAwayStatus()); - commanderItem = new JCheckBoxMenuItem("Channel commander", Icons.of("CHANNEL_COMMANDER"), false); - commanderItem.addActionListener(e -> listener.onCommanderToggle(commanderItem.isSelected())); - JMenuItem nick = new JMenuItem("Change nickname…", Icons.of("CHANGE_NICKNAME")); - nick.addActionListener(e -> listener.onChangeNickname()); - talkPowerItem = new JMenuItem(); - talkPowerItem.addActionListener(e -> listener.onRequestTalkPower()); - showTalkPowerRequested(false); - phoneticItem = new JMenuItem("Set Phonetic Nickname…", Icons.of("PHONETICSNICKNAME")); - phoneticItem.addActionListener(e -> listener.onSetPhoneticNickname()); - avatarItem = new JMenuItem("Set avatar…", Icons.of("UPLOAD_AVATAR")); - avatarItem.addActionListener(e -> listener.onSetAvatar()); - deleteAvatarItem = new JMenuItem("Delete avatar", Icons.of("DELETE_AVATAR")); - deleteAvatarItem.addActionListener(e -> listener.onDeleteAvatar()); - JMenuItem giantPtt = new JMenuItem("Giant PTT", Icons.of("CAPTURE")); - giantPtt.addActionListener(e -> listener.onGiantPtt()); - self.add(awayMenu); - self.add(activateItem); - self.add(muteItem); - self.add(deafItem); - self.add(giantPtt); - self.addSeparator(); - self.add(commanderItem); - self.addSeparator(); - self.add(nick); - self.add(talkPowerItem); - self.add(phoneticItem); - self.add(avatarItem); - self.add(deleteAvatarItem); - self.addMenuListener(new MenuListener() { - @Override - public void menuSelected(MenuEvent e) { - showTalkPowerRequested(listener.isTalkPowerRequested()); - avatarItem.setVisible(!avatarItem.isEnabled() || listener.canSetAvatar()); - deleteAvatarItem.setVisible(listener.hasAvatar()); - } - - @Override - public void menuDeselected(MenuEvent e) { - } - - @Override - public void menuCanceled(MenuEvent e) { - } - }); - - JMenu permissions = new JMenu("Permissions"); - privilegeKeysItem = new JMenuItem("Privilege Keys", Icons.of("TOKEN")); - privilegeKeysItem.addActionListener(e -> listener.onShowPrivilegeKeys()); - usePrivilegeKeyItem = new JMenuItem("Use Privilege Key", Icons.of("TOKEN_USE")); - usePrivilegeKeyItem.addActionListener(e -> listener.onUsePrivilegeKey()); - permissions.add(privilegeKeysItem); - permissions.add(usePrivilegeKeyItem); - permissions.addMenuListener(new MenuListener() { - @Override - public void menuSelected(MenuEvent e) { - privilegeKeysItem.setVisible(!privilegeKeysItem.isEnabled() || listener.canListPrivilegeKeys()); - } - - @Override - public void menuDeselected(MenuEvent e) { - } - - @Override - public void menuCanceled(MenuEvent e) { - } - }); - - JMenu tools = new JMenu("Tools"); - JMenuItem identitiesItem = new JMenuItem("Identities…", Icons.of("IDENTITY_MANAGER")); - identitiesItem.setAccelerator(KeyStroke.getKeyStroke("control I")); - identitiesItem.addActionListener(e -> listener.onShowIdentities()); - JMenuItem contactsItem = new JMenuItem("Contacts…", Icons.ofAny("CONTACT", "EDIT_FRIEND_FOE_STATUS")); - contactsItem.setAccelerator(KeyStroke.getKeyStroke("control shift O")); - contactsItem.addActionListener(e -> listener.onShowContacts()); - offlineMessagesItem = new JMenuItem("Offline Messages", Icons.of("OFFLINE_MESSAGES")); - offlineMessagesItem.setAccelerator(KeyStroke.getKeyStroke("control O")); - offlineMessagesItem.addActionListener(e -> listener.onShowOfflineMessages()); - startRecordingItem = new JMenuItem("Start Recording", Icons.of("RECORDING_START")); - startRecordingItem.addActionListener(e -> listener.onStartRecording(false)); - startMultitrackItem = new JMenuItem("Start Multitrack Recording", Icons.of("RECORDING_START")); - startMultitrackItem.addActionListener(e -> listener.onStartRecording(true)); - stopRecordingItem = new JMenuItem("Stop Recording", Icons.of("RECORDING_STOP")); - stopRecordingItem.addActionListener(e -> listener.onStopRecording()); - banListItem = new JMenuItem("Ban List", Icons.of("BAN_LIST")); - banListItem.setAccelerator(KeyStroke.getKeyStroke("control shift B")); - // The shortcut works while the item is hidden, so it asks for itself. - banListItem.addActionListener(e -> { - if (listener.canViewBanList()) listener.onShowBanList(); - }); - complaintsItem = new JMenuItem("Complaints List", Icons.of("COMPLAINT_LIST")); - complaintsItem.setAccelerator(KeyStroke.getKeyStroke("control shift C")); - complaintsItem.addActionListener(e -> { - if (listener.canViewComplaints()) listener.onShowComplaints(); - }); - serverLogItem = new JMenuItem("Server Log", Icons.of("SERVER_LOG")); - serverLogItem.setAccelerator(KeyStroke.getKeyStroke("control shift L")); - serverLogItem.addActionListener(e -> { - if (listener.canViewServerLog()) listener.onShowServerLog(); - }); - JMenuItem options = new JMenuItem("Options…", Icons.of("SETTINGS")); - options.setAccelerator(KeyStroke.getKeyStroke("alt P")); - options.addActionListener(e -> listener.onShowSettings()); - JPopupMenu.Separator adminSeparator = new JPopupMenu.Separator(); - tools.add(identitiesItem); - tools.add(contactsItem); - tools.add(offlineMessagesItem); - tools.addSeparator(); - tools.add(startRecordingItem); - tools.add(startMultitrackItem); - tools.add(stopRecordingItem); - tools.addSeparator(); - tools.add(banListItem); - tools.add(complaintsItem); - tools.add(serverLogItem); - tools.add(adminSeparator); - tools.add(options); - // Permissions arrive after the connection does, so the item is judged as the menu opens - // rather than on a fixed refresh. - tools.addMenuListener(new MenuListener() { - @Override - public void menuSelected(MenuEvent e) { - boolean bans = banListItem.isEnabled() && listener.canViewBanList(); - boolean complaints = complaintsItem.isEnabled() && listener.canViewComplaints(); - boolean serverLog = serverLogItem.isEnabled() && listener.canViewServerLog(); - banListItem.setVisible(bans); - complaintsItem.setVisible(complaints); - serverLogItem.setVisible(serverLog); - adminSeparator.setVisible(bans || complaints || serverLog); - boolean recording = listener.isRecording(); - startRecordingItem.setVisible(!recording); - startMultitrackItem.setVisible(!recording); - stopRecordingItem.setVisible(recording); - } - - @Override - public void menuDeselected(MenuEvent e) { - } - - @Override - public void menuCanceled(MenuEvent e) { - } - }); - - JMenu help = new JMenu("Help"); - JMenuItem about = new JMenuItem("About", Icons.of("ABOUT")); - about.addActionListener(e -> listener.onShowAbout()); - help.add(about); - - add(connections); - add(bookmarksMenu); - add(self); - add(permissions); - add(tools); - add(help); - } - - /** Reflects the current tab's state on the menu items. */ - void refresh(boolean connected, boolean anyConnected, boolean micMuted, boolean deafened, - boolean active, boolean away, boolean commander) { - awayMenu.setEnabled(anyConnected); - activateItem.setEnabled(connected && !active); - muteItem.setEnabled(connected); - deafItem.setEnabled(connected); - showMuted(micMuted, deafened); - awayItem.setEnabled(connected); - awayStatusItem.setEnabled(connected); - commanderItem.setEnabled(connected); - talkPowerItem.setEnabled(connected); - phoneticItem.setEnabled(connected); - avatarItem.setEnabled(connected); - deleteAvatarItem.setEnabled(connected); - startRecordingItem.setEnabled(connected); - startMultitrackItem.setEnabled(connected); - offlineMessagesItem.setEnabled(connected); - banListItem.setEnabled(connected); - complaintsItem.setEnabled(connected); - serverLogItem.setEnabled(connected); - privilegeKeysItem.setEnabled(connected); - usePrivilegeKeyItem.setEnabled(connected); - awayItem.setSelected(away); - commanderItem.setSelected(commander); - } - - private void showTalkPowerRequested(boolean requested) { - talkPowerItem.setText(requested ? "Cancel Talk Power Request" : "Request Talk Power…"); - talkPowerItem.setIcon(Icons.of(requested ? "TALK_POWER_CANCEL_REQUEST" : "TALK_POWER_REQUEST")); - } - - private void showMuted(boolean micMuted, boolean deafened) { - muteItem.setText(micMuted ? "Unmute Microphone" : "Mute Microphone"); - muteItem.setIcon(Icons.of(micMuted ? "CAPTURE" : "INPUT_MUTED")); - deafItem.setText(deafened ? "Unmute Speakers/Headphones" : "Mute Speakers/Headphones"); - deafItem.setIcon(Icons.of(deafened ? "PLAYBACK" : "OUTPUT_MUTED")); - } - - /** The toolbar button's toggle and status for this server, then its drop-down's global items. */ - private void rebuildAwayMenu() { - awayMenu.removeAll(); - awayMenu.add(awayItem); - awayMenu.add(awayStatusItem); - awayMenu.addSeparator(); - for (Component c : listener.buildAwayMenu().getComponents()) awayMenu.getPopupMenu().add(c); - } - - /** Re-lists the saved bookmarks; called after they change (add, remove, manage…). */ - void rebuildBookmarks() { - bookmarksMenu.removeAll(); - JMenuItem addCurrent = new JMenuItem("Add to Bookmarks…", Icons.of("BOOKMARK_ADD")); - addCurrent.addActionListener(e -> listener.onAddCurrentServerBookmark()); - JMenuItem manage = new JMenuItem("Manage Bookmarks…", Icons.of("BOOKMARK_MANAGER")); - manage.setAccelerator(KeyStroke.getKeyStroke("control B")); - manage.addActionListener(e -> listener.onManageBookmarks()); - bookmarksMenu.add(addCurrent); - bookmarksMenu.add(manage); - if (!bookmarks.all().isEmpty()) bookmarksMenu.addSeparator(); - for (Bookmark b : bookmarks.all()) { - ImageIcon serverIcon = GroupIcons.cached(b.iconId); - JMenuItem item = new JMenuItem(b.displayName(), serverIcon != null ? serverIcon : Icons.of("SERVER_GREEN")); - item.setToolTipText("Connect here (middle-click to open a new tab)"); - item.addActionListener(e -> listener.onConnectBookmark(b, false)); - item.addMouseListener(new MouseAdapter() { - @Override - public void mousePressed(MouseEvent e) { - if (!SwingUtilities.isMiddleMouseButton(e)) return; - MenuSelectionManager.defaultManager().clearSelectedPath(); - listener.onConnectBookmark(b, true); - } - }); - bookmarksMenu.add(item); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/MainToolbar.java b/ts3-client/swing/src/main/java/com/ts3client/ui/MainToolbar.java deleted file mode 100644 index f06f15a..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/MainToolbar.java +++ /dev/null @@ -1,237 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.config.Settings; -import com.ts3client.net.HostButton; -import com.ts3client.net.PictureDownloads; - -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JCheckBoxMenuItem; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.JSlider; -import javax.swing.JToggleButton; -import javax.swing.JToolBar; -import javax.swing.event.PopupMenuEvent; -import javax.swing.event.PopupMenuListener; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.FlowLayout; - -/** - * The main window's toolbar: connect/disconnect, the per-tab mic/speaker/away - * controls, and the Master Volume slider and the server's host button on the - * right. A right-click anywhere on the bar opens a customization menu for the - * window's optional chrome (this toolbar has no say over the status bar's own - * visibility beyond reporting the toggle). - * - *

    Talks to {@link MainFrame} only through {@link Listener}, so it owns no - * connection/tab state itself — {@link #refresh} is handed everything it - * needs to redraw each time the selection changes. - */ -final class MainToolbar extends JToolBar { - - interface Listener { - void onConnect(); - - void onDisconnect(); - - /** Moves the microphone to the tab on screen. */ - void onActivate(); - - void onMicMuteToggle(boolean muted); - - void onDeafenToggle(boolean deafened); - - /** The plain toggle carries no message; the drop-down arrow is where messages are chosen. */ - void onAwayToggle(boolean away); - - JPopupMenu buildAwayMenu(); - - void onSettings(); - - /** The slider changed; push the new master volume to every open connection. */ - void onMasterVolumeChanged(); - - void onStatusBarVisibilityChanged(boolean visible); - } - - private final Settings settings; - private final Listener listener; - - private final JButton connectButton; - private final JButton disconnectButton; - private final JToggleButton activeButton; - private final JToggleButton micButton; - private final JToggleButton speakerButton; - private final DropDownToggleButton awayButton; - private final JComponent masterVolumePanel; - private final HostButtonView hostButton; - - MainToolbar(Settings settings, Listener listener, PictureDownloads pictures) { - this.settings = settings; - this.listener = listener; - - setFloatable(false); - setBackground(Theme.toolbarBg()); - setBorder(new ScaledEmptyBorder(4, 6, 4, 6)); - setComponentPopupMenu(buildContextMenu()); - - connectButton = new JButton(Icons.connect()); - connectButton.setToolTipText("Connect to a server"); - connectButton.addActionListener(e -> listener.onConnect()); - - disconnectButton = new JButton(Icons.disconnect()); - disconnectButton.setToolTipText("Disconnect"); - disconnectButton.addActionListener(e -> listener.onDisconnect()); - - activeButton = new JToggleButton(Icons.micActive()); - activeButton.setToolTipText("Speak on this server (moves the microphone to this tab)"); - activeButton.addActionListener(e -> listener.onActivate()); - - micButton = new JToggleButton(Icons.mic()); - micButton.setToolTipText("Mute / unmute microphone on this server"); - micButton.addActionListener(e -> listener.onMicMuteToggle(micButton.isSelected())); - - speakerButton = new JToggleButton(Icons.speaker()); - speakerButton.setToolTipText("Deafen / undeafen (mute speakers) on this server"); - speakerButton.addActionListener(e -> listener.onDeafenToggle(speakerButton.isSelected())); - - awayButton = new DropDownToggleButton(Icons.away(), - "Away on this server (the arrow offers the global actions and presets)", - listener::buildAwayMenu); - awayButton.addActionListener(e -> listener.onAwayToggle(awayButton.isSelected())); - - JButton settingsButton = new JButton(Icons.settings()); - settingsButton.setToolTipText("Options"); - settingsButton.addActionListener(e -> listener.onSettings()); - - add(connectButton); - add(disconnectButton); - addSeparator(); - add(activeButton); - add(micButton); - add(speakerButton); - add(awayButton); - addSeparator(); - add(settingsButton); - add(Box.createHorizontalGlue()); - masterVolumePanel = buildMasterVolumeControl(); - masterVolumePanel.setVisible(settings.showMasterVolumeSlider); - add(masterVolumePanel); - hostButton = new HostButtonView(pictures); - add(hostButton); - } - - /** Shows the selected server's host button; {@code null} hides it. */ - void showHostButton(HostButton button) { - hostButton.show(button); - } - - /** Reflects the current tab's state on the buttons. */ - void refresh(boolean connected, boolean anyConnected, boolean micMuted, boolean deafened, - boolean active, boolean away) { - disconnectButton.setEnabled(connected); - micButton.setEnabled(connected); - speakerButton.setEnabled(connected); - activeButton.setEnabled(connected); - // The away menu's actions are global, so the arrow stays live while any server is up. - awayButton.setEnabled(anyConnected); - awayButton.setToggleEnabled(connected); - - micButton.setSelected(micMuted); - micButton.setIcon(micMuted ? Icons.micMutedLarge() : Icons.mic()); - speakerButton.setSelected(deafened); - speakerButton.setIcon(deafened ? Icons.speakerMutedLarge() : Icons.speaker()); - activeButton.setSelected(active); - awayButton.setSelected(away); - } - - /** Simulates a click, for the "Mute Microphone" menu item. */ - void clickMic() { - micButton.doClick(); - } - - /** Simulates a click, for the "Mute Speakers/Headphones" menu item. */ - void clickSpeaker() { - speakerButton.doClick(); - } - - /** The Master Volume slider: multiplies both voice and notification volume. */ - private JComponent buildMasterVolumeControl() { - JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT, UIScale.scale(4), 0)); - panel.setOpaque(false); - panel.setAlignmentY(Component.CENTER_ALIGNMENT); - - JLabel icon = new JLabel(Icons.speaker()); - icon.setToolTipText("Master volume (voice + notifications)"); - icon.setAlignmentY(Component.CENTER_ALIGNMENT); - - JSlider slider = new JSlider(0, 200, (int) Math.round(settings.masterVolume * 100)); - slider.setOpaque(false); - slider.setToolTipText("Master volume (voice + notifications) — scroll to adjust"); - slider.setAlignmentY(Component.CENTER_ALIGNMENT); - slider.setPreferredSize(new Dimension(UIScale.scale(135), slider.getPreferredSize().height)); - slider.addChangeListener(e -> { - settings.masterVolume = slider.getValue() / 100.0; - listener.onMasterVolumeChanged(); - // Only touch the disk once the drag (or a wheel step) has settled. - if (!slider.getValueIsAdjusting()) settings.save(); - }); - slider.addMouseWheelListener(e -> { - int step = e.getWheelRotation() < 0 ? 5 : -5; - slider.setValue(slider.getValue() + step); - e.consume(); - }); - - panel.add(icon); - panel.add(slider); - return panel; - } - - /** Right-click on the toolbar: toggles for the window's optional chrome. */ - private JPopupMenu buildContextMenu() { - JPopupMenu menu = new JPopupMenu(); - - JCheckBoxMenuItem statusBarItem = new JCheckBoxMenuItem("Show Status Bar", settings.showStatusBar); - statusBarItem.addActionListener(e -> { - settings.showStatusBar = statusBarItem.isSelected(); - settings.save(); - listener.onStatusBarVisibilityChanged(settings.showStatusBar); - }); - - JCheckBoxMenuItem volumeItem = new JCheckBoxMenuItem("Show Master Volume Slider", settings.showMasterVolumeSlider); - volumeItem.addActionListener(e -> { - settings.showMasterVolumeSlider = volumeItem.isSelected(); - settings.save(); - masterVolumePanel.setVisible(settings.showMasterVolumeSlider); - revalidate(); - repaint(); - }); - - menu.add(statusBarItem); - menu.add(volumeItem); - // Either toggle can also be flipped elsewhere (or via settings.properties), so - // re-sync the ticks each time the menu is about to be shown. - menu.addPopupMenuListener(new PopupMenuListener() { - @Override - public void popupMenuWillBecomeVisible(PopupMenuEvent e) { - statusBarItem.setSelected(settings.showStatusBar); - volumeItem.setSelected(settings.showMasterVolumeSlider); - } - - @Override - public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { - } - - @Override - public void popupMenuCanceled(PopupMenuEvent e) { - } - }); - return menu; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/MicrophoneTest.java b/ts3-client/swing/src/main/java/com/ts3client/ui/MicrophoneTest.java deleted file mode 100644 index 7aecf10..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/MicrophoneTest.java +++ /dev/null @@ -1,182 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.audio.AudioBackend; -import com.ts3client.audio.AudioPlayback; -import com.ts3client.audio.VoiceInput; -import com.ts3client.config.Settings; - -import javax.swing.SwingUtilities; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.function.Consumer; - -/** - * Drives the settings dialog's microphone test from a real capture chain. - * - *

    The dialog runs its own {@link VoiceInput} rather than borrowing the connected - * one, whose listeners belong to the connection. Because it is the same class that feeds - * the server, the level and the gate shown here are exactly what would be transmitted — - * pre-processing, voice detection, hangover and pre-roll included. - * - *

    Loopback is optional: when enabled, the frames that would be sent are played back - * locally so you can hear precisely what the other side would. - */ -final class MicrophoneTest { - - /** Frames buffered for loopback before the oldest is dropped (~100 ms). */ - private static final int LOOPBACK_QUEUE_FRAMES = 5; - - private final Consumer onLevel; - private final Consumer onTransmitting; - - private final AudioBackend audio; - private VoiceInput mic; - - private final ArrayBlockingQueue loopbackQueue = - new ArrayBlockingQueue<>(LOOPBACK_QUEUE_FRAMES); - private volatile boolean loopbackEnabled; - private volatile boolean loopbackRunning; - private Thread loopbackThread; - private String outputDevice = ""; - - MicrophoneTest(AudioBackend audio, Consumer onLevel, Consumer onTransmitting) { - this.audio = audio; - this.onLevel = onLevel; - this.onTransmitting = onTransmitting; - } - - /** Whether a capture chain is currently running. */ - boolean isRunning() { - return mic != null; - } - - /** - * (Re)starts the test chain against {@code settings}' devices and voice options. - * - * @return false if the capture device could not be opened - */ - boolean start(Settings settings) { - stop(); - VoiceInput input = audio.createInput(settings); - input.setLevelListener(db -> SwingUtilities.invokeLater(() -> onLevel.accept(db))); - input.setTalkListener(talking -> SwingUtilities.invokeLater(() -> onTransmitting.accept(talking))); - input.setMonitorListener(this::enqueueForLoopback); - this.outputDevice = settings.outputDevice; - try { - input.start(); - } catch (RuntimeException e) { - return false; // Device busy or gone; leave the test switched off. - } - this.mic = input; - return true; - } - - /** - * Stops the capture chain. The caller owns the UI reset: doing it here would race with - * a restart, whose own state has already been put on screen. - */ - void stop() { - setLoopback(false); - if (mic != null) { - mic.stop(); - mic = null; - } - } - - /** Applies a change to the test chain, if it is running. */ - void configure(Consumer change) { - VoiceInput m = mic; - if (m != null) change.accept(m); - } - - /** The playback device to loop back through; takes effect on the next enable. */ - void setOutputDevice(String deviceId) { - this.outputDevice = deviceId == null ? "" : deviceId; - } - - void setLoopback(boolean enabled) { - if (enabled == loopbackEnabled) { - return; - } - loopbackEnabled = enabled; - if (enabled) { - loopbackRunning = true; - loopbackThread = new Thread(this::loopbackLoop, "settings-loopback"); - loopbackThread.setDaemon(true); - loopbackThread.start(); - } else { - loopbackRunning = false; - if (loopbackThread != null) { - loopbackThread.interrupt(); - loopbackThread = null; - } - loopbackQueue.clear(); - } - } - - /** - * Converts a transmitted frame to 16-bit PCM and queues it. Runs on the capture thread, - * so it must not block: a full queue means playback has fallen behind and the oldest - * frame is dropped instead. - */ - private void enqueueForLoopback(float[] interleaved, int channels) { - if (!loopbackEnabled) { - return; - } - byte[] pcm = toPcm16(interleaved); - if (!loopbackQueue.offer(pcm)) { - loopbackQueue.poll(); - loopbackQueue.offer(pcm); - } - } - - private void loopbackLoop() { - AudioPlayback line = null; - try { - // The monitored frames are mono for voice; ask for a matching line so no - // channel juggling is needed, and up-mix only if the device insists on stereo. - line = audio.io().openPlayback(outputDevice, 1); - line.start(); - int channels = line.channels(); - while (loopbackRunning) { - byte[] frame = loopbackQueue.poll(100, java.util.concurrent.TimeUnit.MILLISECONDS); - if (frame == null) { - continue; - } - byte[] out = (channels == 1) ? frame : upmix(frame, channels); - line.write(out, 0, out.length); - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } catch (Exception ignored) { - // The device may be busy or gone; the test simply runs without loopback. - } finally { - if (line != null) line.close(); - } - } - - /** Converts float samples in [-1, 1] to 16-bit little-endian PCM. */ - static byte[] toPcm16(float[] samples) { - byte[] pcm = new byte[samples.length * 2]; - for (int i = 0; i < samples.length; i++) { - float f = samples[i]; - if (f > 1f) f = 1f; - else if (f < -1f) f = -1f; - int s = Math.round(f * 32767f); - pcm[2 * i] = (byte) (s & 0xFF); - pcm[2 * i + 1] = (byte) ((s >> 8) & 0xFF); - } - return pcm; - } - - /** Copies a mono frame across {@code channels} interleaved channels. */ - static byte[] upmix(byte[] mono, int channels) { - byte[] out = new byte[mono.length * channels]; - for (int i = 0, frames = mono.length / 2; i < frames; i++) { - for (int c = 0; c < channels; c++) { - out[2 * (i * channels + c)] = mono[2 * i]; - out[2 * (i * channels + c) + 1] = mono[2 * i + 1]; - } - } - return out; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/MyTeamSpeakPanel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/MyTeamSpeakPanel.java deleted file mode 100644 index 811ec7f..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/MyTeamSpeakPanel.java +++ /dev/null @@ -1,394 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.myts.AccountInfo; -import com.ts3client.myts.MyTeamSpeak; -import com.ts3client.myts.MyTeamSpeakLogin; -import com.ts3client.myts.MyTsException; -import com.ts3client.teamspeak.SyncItem; -import com.ts3client.teamspeak.TeamSpeakImporter; - -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JPasswordField; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.JTextField; -import javax.swing.SwingUtilities; -import javax.swing.UIManager; -import javax.swing.table.AbstractTableModel; -import java.awt.BorderLayout; -import java.awt.CardLayout; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.io.IOException; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.time.format.FormatStyle; -import java.util.ArrayList; -import java.util.List; - -/** - * Options page for the myTeamSpeak account: sign in and out, and see what the - * account synchronises and import it. Everything here takes effect at once rather - * than on OK, as signing in is not a setting to be cancelled. - */ -final class MyTeamSpeakPanel extends JPanel { - - private static final String SIGNED_OUT = "out"; - private static final String SIGNED_IN = "in"; - - private final MyTeamSpeakLogin login; - private final TeamSpeakImporter importer; - private final Runnable onImported; - /** Runs when the client signs in or out, the saved sign-in being turned away included. */ - private final Runnable onSignInChanged; - - private final CardLayout cards = new CardLayout(); - - private final JTextField email = new JTextField(24); - private final JPasswordField password = new JPasswordField(24); - private final JButton signIn = new JButton("Sign in"); - private final JLabel signInStatus = new JLabel(" "); - - private final JLabel account = new JLabel(); - private final JPanel details = new JPanel(new GridBagLayout()); - private final ItemTable items = new ItemTable(); - private final JButton refresh = new JButton("Refresh"); - private final JButton importButton = new JButton("Import selected"); - private final JLabel dataStatus = new JLabel(" "); - - private List accountItems = List.of(); - private boolean fetched; - - MyTeamSpeakPanel(MyTeamSpeakLogin login, TeamSpeakImporter importer, Runnable onImported, - Runnable onSignInChanged) { - this.login = login; - this.importer = importer; - this.onImported = onImported; - this.onSignInChanged = onSignInChanged; - setLayout(cards); - add(buildSignedOut(), SIGNED_OUT); - add(buildSignedIn(), SIGNED_IN); - showState(); - // Reads the account the first time the page is looked at, not with every Options dialog. - addHierarchyListener(e -> { - if (isShowing() && login.isSignedIn() && !fetched) fetch(); - }); - } - - private JPanel buildSignedOut() { - JPanel form = new JPanel(new GridBagLayout()); - form.setBorder(new ScaledEmptyBorder(12, 12, 12, 12)); - GridBagConstraints c = FormPanel.gbc(); - c.gridwidth = 2; - c.gridy = 0; - form.add(new JLabel("Sign in to your myTeamSpeak account to bring over the bookmarks and " - + "identities it synchronises. The client stays signed in; your password itself is not kept."), c); - c.gridwidth = 1; - FormPanel.addRow(form, c, 1, new JLabel("Email:"), email); - FormPanel.addRow(form, c, 2, new JLabel("Password:"), password); - c.gridx = 1; - c.gridy = 3; - c.fill = GridBagConstraints.NONE; - c.anchor = GridBagConstraints.EAST; - form.add(signIn, c); - c.gridx = 0; - c.gridy = 4; - c.gridwidth = 2; - c.fill = GridBagConstraints.HORIZONTAL; - form.add(signInStatus, c); - c.gridy = 5; - c.weighty = 1; - form.add(Box.createVerticalGlue(), c); - - signIn.addActionListener(e -> signIn()); - password.addActionListener(e -> signIn()); - return form; - } - - private JPanel buildSignedIn() { - JPanel header = new JPanel(new BorderLayout()); - JButton signOut = new JButton("Sign out"); - signOut.addActionListener(e -> signOut()); - header.add(account, BorderLayout.CENTER); - header.add(signOut, BorderLayout.EAST); - JPanel top = new JPanel(new BorderLayout(0, UIScale.scale(8))); - top.add(header, BorderLayout.NORTH); - top.add(details, BorderLayout.CENTER); - - JPanel buttons = new JPanel(); - buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS)); - buttons.add(dataStatus); - buttons.add(Box.createHorizontalGlue()); - buttons.add(refresh); - buttons.add(Box.createHorizontalStrut(UIScale.scale(4))); - buttons.add(importButton); - refresh.addActionListener(e -> fetch()); - importButton.addActionListener(e -> importSelected()); - - JPanel data = new JPanel(new BorderLayout(0, UIScale.scale(4))); - data.add(new JLabel("Synchronised by the account:"), BorderLayout.NORTH); - data.add(new JScrollPane(items.table), BorderLayout.CENTER); - data.add(buttons, BorderLayout.SOUTH); - - JPanel panel = new JPanel(new BorderLayout(0, UIScale.scale(12))); - panel.setBorder(new ScaledEmptyBorder(12, 12, 12, 12)); - panel.add(top, BorderLayout.NORTH); - panel.add(data, BorderLayout.CENTER); - return panel; - } - - private void showState() { - if (login.isSignedIn()) { - account.setText("Signed in as " + escape(login.username()) + "
    " - + escape(login.email()) + ""); - cards.show(this, SIGNED_IN); - } else { - password.setText(""); - cards.show(this, SIGNED_OUT); - } - } - - private void signIn() { - String address = email.getText().trim(); - String secret = new String(password.getPassword()); - if (address.isEmpty() || secret.isEmpty() || !signIn.isEnabled()) return; - setSignInBusy(true); - status(signInStatus, "Signing in…", false); - background(() -> { - MyTeamSpeak.Account result = login.signIn(address, secret); - SwingUtilities.invokeLater(() -> { - setSignInBusy(false); - status(signInStatus, " ", false); - showState(); - showItems(result); - onSignInChanged.run(); - }); - }, message -> { - setSignInBusy(false); - status(signInStatus, message, true); - password.selectAll(); - password.requestFocusInWindow(); - }); - } - - private void signOut() { - login.signOut(); - accountItems = List.of(); - details.removeAll(); - items.set(List.of()); - fetched = false; - email.setText(""); - showState(); - onSignInChanged.run(); - } - - private void fetch() { - fetched = true; - setDataBusy(true); - status(dataStatus, "Reading the account…", false); - background(() -> { - MyTeamSpeak.Account result = login.fetch(); - SwingUtilities.invokeLater(() -> { - setDataBusy(false); - showState(); - showItems(result); - }); - }, message -> { - setDataBusy(false); - status(dataStatus, message, true); - // A rejected sign-in has signed out. - showState(); - if (!login.isSignedIn()) { - status(signInStatus, message, true); - onSignInChanged.run(); - } - }); - } - - private void showDetails(AccountInfo info) { - details.removeAll(); - GridBagConstraints c = FormPanel.gbc(); - int row = 0; - if (!info.userId().isEmpty()) FormPanel.addRow(details, c, row++, new JLabel("ID:"), selectable(info.userId())); - if (!info.uuid().isEmpty()) FormPanel.addRow(details, c, row++, new JLabel("UUID:"), selectable(info.uuid())); - if (info.created() != null) { - String date = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM) - .format(info.created().atZone(ZoneId.systemDefault())); - FormPanel.addRow(details, c, row, new JLabel("Created:"), selectable(date)); - } - details.revalidate(); - details.repaint(); - } - - /** A value that can be selected and copied but not edited. */ - private static JTextField selectable(String value) { - JTextField field = new JTextField(value); - field.setEditable(false); - field.setCaretPosition(0); - return field; - } - - private void showItems(MyTeamSpeak.Account result) { - fetched = true; - showDetails(result.info()); - accountItems = result.items(); - List rows = new ArrayList<>(); - for (SyncItem item : accountItems) { - if (item instanceof SyncItem.Folder) continue; - boolean present = importer.isPresent(item); - rows.add(new Row(item, present, !present)); - } - items.set(rows); - status(dataStatus, rows.isEmpty() ? "The account holds no bookmarks or identities." : " ", false); - updateImportButton(); - } - - private void importSelected() { - List chosen = items.rows.stream().filter(Row::selected).map(Row::item).toList(); - if (chosen.isEmpty()) return; - try { - TeamSpeakImporter.Result r = importer.importSelected(accountItems, chosen); - status(dataStatus, "Imported " + count(r.identitiesAdded(), "identity", "identities") + " and " - + count(r.bookmarksAdded(), "bookmark", "bookmarks") + ".", false); - if (onImported != null) onImported.run(); - } catch (IOException e) { - status(dataStatus, "Could not import: " + e.getMessage(), true); - } - List rows = new ArrayList<>(); - for (Row row : items.rows) rows.add(new Row(row.item(), importer.isPresent(row.item()), false)); - items.set(rows); - updateImportButton(); - } - - private interface Work { - void run() throws IOException, MyTsException; - } - - /** Runs account work off the event thread; a failure's message reaches {@code onError} on it. */ - private static void background(Work work, java.util.function.Consumer onError) { - Thread.ofVirtual().name("myteamspeak").start(() -> { - try { - work.run(); - } catch (MyTsException e) { - SwingUtilities.invokeLater(() -> onError.accept(e.getMessage())); - } catch (IOException e) { - SwingUtilities.invokeLater(() -> onError.accept("Could not reach myTeamSpeak: " + e.getMessage())); - } - }); - } - - private void setSignInBusy(boolean busy) { - email.setEnabled(!busy); - password.setEnabled(!busy); - signIn.setEnabled(!busy); - } - - private void setDataBusy(boolean busy) { - refresh.setEnabled(!busy); - importButton.setEnabled(!busy); - if (!busy) updateImportButton(); - } - - private void updateImportButton() { - importButton.setEnabled(refresh.isEnabled() && items.rows.stream().anyMatch(Row::selected)); - } - - private static void status(JLabel label, String text, boolean error) { - label.setText(text.isBlank() ? " " : "" + escape(text) + ""); - label.setForeground(UIManager.getColor(error ? "Actions.Red" : "Label.foreground")); - } - - private static String escape(String s) { - return s.replace("&", "&").replace("<", "<"); - } - - private static String count(long n, String one, String many) { - return n + " " + (n == 1 ? one : many); - } - - private record Row(SyncItem item, boolean present, boolean selected) { - } - - /** The account's items, each with a box to pick it for importing and whether it is here already. */ - private final class ItemTable extends AbstractTableModel { - - private static final String[] COLUMNS = {"", "Type", "Name", "Details", "Imported"}; - - final JTable table = new JTable(this); - List rows = List.of(); - - ItemTable() { - table.setFillsViewportHeight(true); - table.getTableHeader().setReorderingAllowed(false); - table.getColumnModel().getColumn(0).setMaxWidth(UIScale.scale(28)); - table.getColumnModel().getColumn(1).setPreferredWidth(UIScale.scale(60)); - table.getColumnModel().getColumn(4).setPreferredWidth(UIScale.scale(60)); - } - - void set(List rows) { - this.rows = rows; - fireTableDataChanged(); - } - - @Override - public int getRowCount() { - return rows.size(); - } - - @Override - public int getColumnCount() { - return COLUMNS.length; - } - - @Override - public String getColumnName(int column) { - return COLUMNS[column]; - } - - @Override - public Class getColumnClass(int column) { - return column == 0 ? Boolean.class : String.class; - } - - @Override - public boolean isCellEditable(int row, int column) { - return column == 0; - } - - @Override - public Object getValueAt(int row, int column) { - Row r = rows.get(row); - return switch (column) { - case 0 -> r.selected(); - case 1 -> r.item() instanceof SyncItem.Bookmark ? "Bookmark" : "Identity"; - case 2 -> switch (r.item()) { - case SyncItem.Bookmark b -> b.name(); - case SyncItem.Identity i -> i.name(); - default -> ""; - }; - case 3 -> switch (r.item()) { - case SyncItem.Bookmark b -> b.address() + ":" + b.port(); - case SyncItem.Identity i -> i.nickname(); - default -> ""; - }; - default -> r.present() ? "Yes" : ""; - }; - } - - @Override - public void setValueAt(Object value, int row, int column) { - Row r = rows.get(row); - List updated = new ArrayList<>(rows); - updated.set(row, new Row(r.item(), r.present(), Boolean.TRUE.equals(value))); - rows = updated; - fireTableRowsUpdated(row, row); - updateImportButton(); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/NetworkPanel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/NetworkPanel.java deleted file mode 100644 index 9dd7867..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/NetworkPanel.java +++ /dev/null @@ -1,150 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.audio.VoiceInput; -import com.ts3client.config.Settings; - -import javax.swing.JCheckBox; -import javax.swing.JLabel; -import javax.swing.JSlider; -import java.awt.GridBagConstraints; - -/** - * Options page for what voice costs and survives on the wire: the encoder, duplicate voice - * packets, and how long incoming voice is buffered. Transmit changes preview live on the - * connected microphone. - */ -final class NetworkPanel extends FormPanel { - - private static final int MIN_BITRATE_KBITS = 8; - private static final int MAX_BITRATE_KBITS = 160; - - private final VoiceInput liveMic; - - private final JSlider bitrateSlider; - private final JCheckBox vbrCheck; - private final JCheckBox fecCheck; - private final JSlider complexitySlider; - private final JCheckBox musicCheck; - private final JSlider delaySlider; - private final JSlider copiesSlider; - private final JSlider receiveBufferSlider; - - /** @param pushEncoder puts the encoder settings on screen, across pages, into effect */ - NetworkPanel(Settings settings, VoiceInput liveMic, Runnable pushEncoder) { - this.liveMic = liveMic; - GridBagConstraints c = gbc(); - - int kbits = Math.max(MIN_BITRATE_KBITS, Math.min(MAX_BITRATE_KBITS, settings.bitrate / 1000)); - bitrateSlider = new JSlider(MIN_BITRATE_KBITS, MAX_BITRATE_KBITS, kbits); - JLabel bitrateLabel = new JLabel(kbits + " kbit/s"); - bitrateSlider.addChangeListener(e -> { - bitrateLabel.setText(bitrateSlider.getValue() + " kbit/s"); - pushEncoder.run(); - }); - - vbrCheck = new JCheckBox("Variable bitrate (VBR)", settings.vbr); - fecCheck = new JCheckBox("Forward error correction (FEC)", settings.fec); - vbrCheck.addActionListener(e -> pushEncoder.run()); - fecCheck.addActionListener(e -> pushEncoder.run()); - - complexitySlider = new JSlider(0, 10, settings.complexity); - JLabel complexityLabel = new JLabel(String.valueOf(settings.complexity)); - complexitySlider.addChangeListener(e -> { - complexityLabel.setText(String.valueOf(complexitySlider.getValue())); - pushEncoder.run(); - }); - - musicCheck = new JCheckBox("Music codec (stereo, higher fidelity)", settings.music); - musicCheck.setToolTipText("Transmits OPUS_MUSIC: stereo when the capture " - + "device has two channels, and without the voice pre-processing " - + "(noise removal, typing attenuation, AGC).
    " - + "Voice mode (OPUS_VOICE) is mono, as in the official client."); - musicCheck.addActionListener(e -> pushEncoder.run()); - - delaySlider = choiceSlider(Settings.REDUNDANCY_DELAYS, settings.redundancyDelay); - JLabel delayLabel = new JLabel(delayLabel(selectedDelay())); - int copies = Math.max(1, Math.min(Settings.MAX_REDUNDANCY_COPIES, settings.redundancyCopies)); - copiesSlider = new JSlider(1, Settings.MAX_REDUNDANCY_COPIES, copies); - copiesSlider.setMajorTickSpacing(1); - copiesSlider.setPaintTicks(true); - copiesSlider.setSnapToTicks(true); - JLabel copiesLabel = new JLabel(String.valueOf(copies)); - Runnable syncCopies = () -> { - copiesSlider.setEnabled(selectedDelay() > 0); - copiesLabel.setEnabled(selectedDelay() > 0); - }; - syncCopies.run(); - delaySlider.addChangeListener(e -> { - delayLabel.setText(delayLabel(selectedDelay())); - syncCopies.run(); - pushRedundancy(); - }); - copiesSlider.addChangeListener(e -> { - copiesLabel.setText(String.valueOf(copiesSlider.getValue())); - pushRedundancy(); - }); - - receiveBufferSlider = choiceSlider(Settings.RECEIVE_BUFFERS, settings.receiveBuffer); - JLabel receiveBufferLabel = new JLabel(delayLabel(selectedReceiveBuffer())); - receiveBufferSlider.addChangeListener(e -> receiveBufferLabel.setText(delayLabel(selectedReceiveBuffer()))); - - int row = 0; - addSection(this, c, row++, "Encoder"); - addRow(this, c, row++, new JLabel("Bitrate:"), sliderWithLabel(bitrateSlider, bitrateLabel, 70)); - addWide(this, c, row++, vbrCheck); - addWide(this, c, row++, fecCheck); - addRow(this, c, row++, new JLabel("Complexity:"), sliderWithLabel(complexitySlider, complexityLabel, 70)); - addWide(this, c, row++, musicCheck); - addSection(this, c, row++, "Redundancy"); - addRow(this, c, row++, new JLabel("Delay:"), sliderWithLabel(delaySlider, delayLabel, 70)); - addRow(this, c, row++, new JLabel("Copies:"), sliderWithLabel(copiesSlider, copiesLabel, 70)); - addSection(this, c, row++, "Receive"); - addRow(this, c, row++, new JLabel("Extra buffering:"), sliderWithLabel(receiveBufferSlider, receiveBufferLabel, 70)); - addFiller(this, c, row); - } - - /** A slider over the indices of {@code choices}, starting at the one nearest {@code ms}. */ - private static JSlider choiceSlider(int[] choices, int ms) { - JSlider slider = new JSlider(0, choices.length - 1, nearest(choices, ms)); - slider.setMajorTickSpacing(1); - slider.setPaintTicks(true); - slider.setSnapToTicks(true); - return slider; - } - - private void pushRedundancy() { - if (liveMic != null) liveMic.setRedundancy(selectedDelay(), copiesSlider.getValue()); - } - - private static String delayLabel(int ms) { - return ms == 0 ? "Off" : ms + " ms"; - } - - private static int nearest(int[] choices, int ms) { - int best = 0; - for (int i = 1; i < choices.length; i++) { - if (Math.abs(choices[i] - ms) < Math.abs(choices[best] - ms)) best = i; - } - return best; - } - - private int selectedDelay() { - return Settings.REDUNDANCY_DELAYS[delaySlider.getValue()]; - } - - private int selectedReceiveBuffer() { - return Settings.RECEIVE_BUFFERS[receiveBufferSlider.getValue()]; - } - - /** Copies the page into {@code target}, without touching anything else. */ - void writeInto(Settings target) { - target.bitrate = bitrateSlider.getValue() * 1000; - target.vbr = vbrCheck.isSelected(); - target.fec = fecCheck.isSelected(); - target.complexity = complexitySlider.getValue(); - target.music = musicCheck.isSelected(); - target.redundancyDelay = selectedDelay(); - target.redundancyCopies = copiesSlider.getValue(); - target.receiveBuffer = selectedReceiveBuffer(); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/NicknameCellEditor.java b/ts3-client/swing/src/main/java/com/ts3client/ui/NicknameCellEditor.java deleted file mode 100644 index 36cfe75..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/NicknameCellEditor.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.net.ClientEntry; - -import javax.swing.DefaultCellEditor; -import javax.swing.JLabel; -import javax.swing.JTextField; -import javax.swing.JTree; -import javax.swing.SwingUtilities; -import javax.swing.Timer; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeCellEditor; -import javax.swing.tree.DefaultTreeCellRenderer; -import javax.swing.tree.TreePath; -import java.awt.Component; -import java.awt.event.MouseEvent; -import java.util.EventObject; -import java.util.function.IntPredicate; - -/** - * Turns our own row in the server tree into a text field on a double click, the way - * TeamSpeak renames a client in place. Only that one row is editable; every other - * double click keeps its usual meaning (joining a channel, opening a chat). - * - *

    The field opens on the current nickname with it selected, so typing replaces it, - * Enter commits and Escape leaves the name alone. - */ -final class NicknameCellEditor extends DefaultTreeCellEditor { - - /** Pulls the field left by its own border, so the text sits where the label did. */ - private static final int FIELD_NUDGE = 2; - - /** Long enough for the click's own release to have been handled first. */ - private static final int SELECT_DELAY_MS = 80; - - private final JTextField field; - /** Whether a client id is our own — the tree learns ours only once connected. */ - private final IntPredicate isSelf; - - private NicknameCellEditor(JTree tree, DefaultTreeCellRenderer renderer, JTextField field, - IntPredicate isSelf) { - super(tree, renderer, new DefaultCellEditor(field)); - this.field = field; - this.isSelf = isSelf; - } - - static NicknameCellEditor create(JTree tree, DefaultTreeCellRenderer renderer, IntPredicate isSelf) { - JTextField field = new JTextField(); - // Only our own row is edited, and that name is bold in the tree. - field.setFont(Theme.uiBold()); - return new NicknameCellEditor(tree, renderer, field, isSelf); - } - - /** Whether a path is the row this editor works on. */ - boolean editsPath(TreePath path) { - ClientEntry client = clientOf(path); - return client != null && isSelf.test(client.id); - } - - /** - * Editing is started by the tree's own double-click handling, which works a row by - * its whole line; Swing's would only see clicks that land on the label, and its - * click-pause-click timer would rename on clicks meant as a selection. - */ - @Override - public boolean isCellEditable(EventObject event) { - return !(event instanceof MouseEvent); - } - - @Override - public Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected, - boolean expanded, boolean leaf, int row) { - // The node itself has to reach super, whose renderer measures the row from it; - // the text it derives is the node's toString, so the nickname is filled in after. - Component c = super.getTreeCellEditorComponent(tree, value, isSelected, expanded, leaf, row); - ClientEntry client = clientOf(value); - if (client != null) { - field.setText(client.nickname); - field.selectAll(); - } - SwingUtilities.invokeLater(field::requestFocusInWindow); - // The double click that opened the field ends in a release, which a text - // component turns into a caret placement — undoing any selection made before - // it. Selecting after that has been delivered is what leaves the whole name - // selected, ready to be typed over. - Timer select = new Timer(SELECT_DELAY_MS, e -> field.selectAll()); - select.setRepeats(false); - select.start(); - return c; - } - - /** - * Keeps the row's own icon while it is being edited. The inherited version knows - * only the renderer's default leaf/branch icons, which would swap a client's state - * icon for a blank page for as long as the field is open. - */ - @Override - protected void determineOffset(JTree tree, Object value, boolean isSelected, boolean expanded, - boolean leaf, int row) { - super.determineOffset(tree, value, isSelected, expanded, leaf, row); - Component c = renderer.getTreeCellRendererComponent(tree, value, isSelected, expanded, leaf, - row, false); - if (!(c instanceof JLabel)) return; - editingIcon = ((JLabel) c).getIcon(); - offset = editingIcon == null ? 0 - : editingIcon.getIconWidth() + renderer.getIconTextGap() - UIScale.scale(FIELD_NUDGE); - } - - /** The edited nickname, trimmed; empty when nothing usable was typed. */ - String editedNickname() { - String text = field.getText(); - return text == null ? "" : text.trim(); - } - - private static ClientEntry clientOf(TreePath path) { - return path == null ? null : clientOf(path.getLastPathComponent()); - } - - private static ClientEntry clientOf(Object node) { - if (!(node instanceof DefaultMutableTreeNode)) return null; - Object obj = ((DefaultMutableTreeNode) node).getUserObject(); - return obj instanceof ClientEntry ? (ClientEntry) obj : null; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/NotificationsPanel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/NotificationsPanel.java deleted file mode 100644 index 400fb90..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/NotificationsPanel.java +++ /dev/null @@ -1,412 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.config.Settings; -import com.ts3client.sound.NotificationSettings; -import com.ts3client.sound.SoundEvent; -import com.ts3client.sound.SoundNotifier; -import com.ts3client.sound.SoundPack; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JFileChooser; -import javax.swing.JLabel; -import javax.swing.JMenuItem; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.JScrollPane; -import javax.swing.JSlider; -import javax.swing.JTable; -import javax.swing.JTextField; -import javax.swing.ListSelectionModel; -import javax.swing.table.AbstractTableModel; -import javax.swing.table.DefaultTableCellRenderer; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Insets; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * Options page for sound packs: which pack is active, how loud it is, and what - * each action does. - * - *

    An action can be switched off entirely, or marked important (shown in - * bold) — important actions are the only ones still played while the speakers are - * muted, which is how the official client behaves. Actions the active pack has no - * sound for are greyed out. - */ -final class NotificationsPanel extends JPanel { - - private static final int TOGGLE_COLUMN_WIDTH = 34; - - /** A table row: either a category heading or one action. */ - private static final class Row { - final SoundEvent.Category heading; - final SoundEvent event; - - Row(SoundEvent.Category heading, SoundEvent event) { - this.heading = heading; - this.event = event; - } - - boolean isHeading() { - return event == null; - } - } - - private final Settings settings; - private final SoundNotifier sounds; - /** Edited copy, applied to the settings only when the dialog is confirmed. */ - private final NotificationSettings working; - private final List rows = new ArrayList<>(); - /** What {@link #revert()} goes back to: as the dialog opened, or as last applied. */ - private String originalPackId; - private String originalPackDir; - - private final JComboBox packCombo = new JComboBox<>(); - private final JLabel packInfo = new JLabel(); - private final JSlider volume; - private final JTextField packDirField; - private final JCheckBox desktopNotifications = - new JCheckBox("Show pokes and private messages as desktop notifications while in the background"); - private final JTable table; - private final EventTableModel tableModel = new EventTableModel(); - - NotificationsPanel(Settings settings, SoundNotifier sounds) { - super(new BorderLayout(0, UIScale.scale(8))); - this.settings = settings; - this.sounds = sounds; - this.working = settings.notifications.copy(); - this.originalPackId = settings.soundPack; - this.originalPackDir = settings.soundPackDir; - this.volume = new JSlider(0, 100, (int) Math.round(settings.soundVolume * 100)); - this.packDirField = new JTextField(settings.soundPackDir, 18); - - buildRows(); - this.table = buildTable(); - - setBorder(new ScaledEmptyBorder(12, 12, 12, 12)); - add(buildHeader(), BorderLayout.NORTH); - add(new JScrollPane(table), BorderLayout.CENTER); - add(buildFooter(), BorderLayout.SOUTH); - - reloadPacks(); - } - - /** Copies the edited state into the settings; the caller saves them. */ - void apply() { - settings.notifications.copyFrom(working); - settings.soundVolume = volume.getValue() / 100.0; - String directory = packDirField.getText().trim(); - boolean rescan = !directory.equals(settings.soundPackDir); - settings.soundPackDir = directory; - settings.desktopNotifications = desktopNotifications.isSelected(); - sounds.setPack((SoundPack) packCombo.getSelectedItem()); - if (rescan) sounds.reload(); - originalPackId = settings.soundPack; - originalPackDir = settings.soundPackDir; - } - - /** Puts back the pack (and folder) last applied, for a cancelled edit. */ - void revert() { - settings.soundPackDir = originalPackDir; - settings.soundPack = originalPackId; - sounds.reload(); - } - - // ---- layout ---- - - private JComponent buildHeader() { - JPanel p = new JPanel(new GridBagLayout()); - GridBagConstraints c = new GridBagConstraints(); - c.insets = UIScale.scale(new Insets(2, 2, 2, 2)); - c.anchor = GridBagConstraints.WEST; - c.fill = GridBagConstraints.HORIZONTAL; - - packCombo.setToolTipText("Sound packs installed here or in a TeamSpeak 3 client"); - packCombo.addActionListener(e -> onPackSelected()); - JButton test = new JButton("Test"); - test.setToolTipText("Play this pack's test sound"); - test.addActionListener(e -> sounds.preview(SoundEvent.SPECIAL_SOUND_TEST)); - - JPanel packRow = new JPanel(new BorderLayout(UIScale.scale(6), 0)); - packRow.add(packCombo, BorderLayout.CENTER); - packRow.add(test, BorderLayout.EAST); - - int row = 0; - addRow(p, c, row++, new JLabel("Sound pack:"), packRow); - c.gridx = 1; - c.gridy = row++; - packInfo.setEnabled(false); - p.add(packInfo, c); - - volume.setToolTipText("Volume of the notification sounds"); - addRow(p, c, row++, new JLabel("Sound volume:"), volume); - - JPanel dirRow = new JPanel(new BorderLayout(UIScale.scale(6), 0)); - JButton browse = new JButton("Browse…"); - browse.addActionListener(e -> browseForPackFolder()); - dirRow.add(packDirField, BorderLayout.CENTER); - dirRow.add(browse, BorderLayout.EAST); - packDirField.setToolTipText("Extra folder to look for sound packs in"); - addRow(p, c, row++, new JLabel("Extra pack folder:"), dirRow); - - desktopNotifications.setSelected(settings.desktopNotifications); - c.gridx = 0; - c.gridy = row; - c.gridwidth = 2; - p.add(desktopNotifications, c); - c.gridwidth = 1; - return p; - } - - private JComponent buildFooter() { - JPanel p = new JPanel(new BorderLayout(UIScale.scale(6), 0)); - JLabel hint = new JLabel("Bold actions are important: they are still played " - + "while your speakers are muted."); - hint.setBorder(new ScaledEmptyBorder(4, 0, 0, 0)); - - JPanel buttons = new JPanel(); - JButton important = new JButton("Toggle important"); - important.addActionListener(e -> toggleImportant()); - JButton play = new JButton("Play"); - play.addActionListener(e -> previewSelected()); - JButton defaults = new JButton("Reset"); - defaults.setToolTipText("Restore the default notification settings"); - defaults.addActionListener(e -> { - working.resetToDefaults(); - tableModel.fireTableDataChanged(); - }); - buttons.add(play); - buttons.add(important); - buttons.add(defaults); - - p.add(hint, BorderLayout.CENTER); - p.add(buttons, BorderLayout.EAST); - return p; - } - - private JTable buildTable() { - JTable t = new JTable(tableModel); - t.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - t.setShowGrid(false); - t.setTableHeader(null); - t.setRowHeight(Math.max(t.getRowHeight(), t.getFontMetrics(t.getFont()).getHeight() + UIScale.scale(6))); - t.getColumnModel().getColumn(0).setMaxWidth(UIScale.scale(TOGGLE_COLUMN_WIDTH)); - t.getColumnModel().getColumn(0).setMinWidth(UIScale.scale(TOGGLE_COLUMN_WIDTH)); - t.getColumnModel().getColumn(0).setCellRenderer(new ToggleRenderer(t.getDefaultRenderer(Boolean.class))); - t.getColumnModel().getColumn(1).setCellRenderer(new ActionRenderer()); - t.setPreferredScrollableViewportSize(UIScale.scale(new Dimension(360, 260))); - - t.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (e.getClickCount() == 2 && e.getButton() == MouseEvent.BUTTON1) previewSelected(); - } - - @Override - public void mousePressed(MouseEvent e) { - showMenu(e); - } - - @Override - public void mouseReleased(MouseEvent e) { - showMenu(e); - } - - private void showMenu(MouseEvent e) { - if (!e.isPopupTrigger()) return; - int row = t.rowAtPoint(e.getPoint()); - if (row < 0 || rows.get(row).isHeading()) return; - t.setRowSelectionInterval(row, row); - contextMenu(rows.get(row).event).show(t, e.getX(), e.getY()); - } - }); - return t; - } - - private JPopupMenu contextMenu(SoundEvent event) { - JPopupMenu menu = new JPopupMenu(); - JMenuItem important = new JMenuItem(working.isImportant(event) ? "Mark as Unimportant" : "Mark as Important"); - important.addActionListener(e -> toggleImportant()); - JMenuItem enabled = new JMenuItem(working.isEnabled(event) ? "Turn sound off" : "Turn sound on"); - enabled.addActionListener(e -> { - working.setEnabled(event, !working.isEnabled(event)); - tableModel.fireTableRowsUpdated(0, rows.size() - 1); - }); - JMenuItem play = new JMenuItem("Play sound"); - play.addActionListener(e -> sounds.preview(event)); - menu.add(play); - menu.addSeparator(); - menu.add(enabled); - menu.add(important); - return menu; - } - - // ---- actions ---- - - private void onPackSelected() { - SoundPack pack = (SoundPack) packCombo.getSelectedItem(); - sounds.setPack(pack); - packInfo.setText(pack == null ? "No sound packs found" - : "by " + (pack.author().isEmpty() ? "unknown" : pack.author()) - + (pack.version().isEmpty() ? "" : ", version " + pack.version())); - tableModel.fireTableDataChanged(); - } - - private void reloadPacks() { - sounds.reload(); - packCombo.removeAllItems(); - for (SoundPack pack : sounds.availablePacks()) { - packCombo.addItem(pack); - } - packCombo.setSelectedItem(sounds.pack()); - onPackSelected(); - } - - private void browseForPackFolder() { - JFileChooser chooser = new JFileChooser(); - chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - chooser.setDialogTitle("Folder containing sound packs"); - String current = packDirField.getText().trim(); - if (!current.isEmpty()) chooser.setCurrentDirectory(new File(current)); - if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return; - packDirField.setText(chooser.getSelectedFile().getAbsolutePath()); - settings.soundPackDir = packDirField.getText(); - reloadPacks(); - } - - private SoundEvent selectedEvent() { - int row = table.getSelectedRow(); - return row < 0 || rows.get(row).isHeading() ? null : rows.get(row).event; - } - - private void previewSelected() { - SoundEvent event = selectedEvent(); - if (event != null) sounds.preview(event); - } - - private void toggleImportant() { - SoundEvent event = selectedEvent(); - if (event == null) return; - working.setImportant(event, !working.isImportant(event)); - tableModel.fireTableRowsUpdated(table.getSelectedRow(), table.getSelectedRow()); - } - - private void buildRows() { - for (SoundEvent.Category category : SoundEvent.Category.values()) { - rows.add(new Row(category, null)); - for (SoundEvent event : SoundEvent.values()) { - if (event.category() == category) rows.add(new Row(category, event)); - } - } - } - - private static void addRow(JPanel p, GridBagConstraints c, int row, JLabel label, Component field) { - c.gridx = 0; - c.gridy = row; - c.weightx = 0; - p.add(label, c); - c.gridx = 1; - c.weightx = 1; - p.add(field, c); - } - - // ---- table plumbing ---- - - private final class EventTableModel extends AbstractTableModel { - - @Override - public int getRowCount() { - return rows.size(); - } - - @Override - public int getColumnCount() { - return 2; - } - - @Override - public Class getColumnClass(int column) { - return column == 0 ? Boolean.class : String.class; - } - - @Override - public Object getValueAt(int rowIndex, int column) { - Row row = rows.get(rowIndex); - if (column == 0) return row.isHeading() ? Boolean.FALSE : working.isEnabled(row.event); - return row.isHeading() ? row.heading.label() : row.event.label(); - } - - @Override - public boolean isCellEditable(int rowIndex, int column) { - return column == 0 && !rows.get(rowIndex).isHeading(); - } - - @Override - public void setValueAt(Object value, int rowIndex, int column) { - Row row = rows.get(rowIndex); - if (column == 0 && !row.isHeading()) { - working.setEnabled(row.event, Boolean.TRUE.equals(value)); - } - } - } - - /** Only actions get a checkbox; a category heading spans an empty cell. */ - private final class ToggleRenderer implements javax.swing.table.TableCellRenderer { - - private final javax.swing.table.TableCellRenderer checkBox; - private final DefaultTableCellRenderer blank = new DefaultTableCellRenderer(); - - ToggleRenderer(javax.swing.table.TableCellRenderer checkBox) { - this.checkBox = checkBox; - } - - @Override - public Component getTableCellRendererComponent(JTable table, Object value, boolean selected, - boolean focused, int rowIndex, int column) { - javax.swing.table.TableCellRenderer delegate = rows.get(rowIndex).isHeading() ? blank : checkBox; - return delegate.getTableCellRendererComponent(table, - delegate == blank ? "" : value, selected, focused, rowIndex, column); - } - } - - /** Headings stand out, important actions are bold, unmapped ones are greyed. */ - private final class ActionRenderer extends DefaultTableCellRenderer { - - @Override - public Component getTableCellRendererComponent(JTable table, Object value, boolean selected, - boolean focused, int rowIndex, int column) { - super.getTableCellRendererComponent(table, value, selected, focused, rowIndex, column); - Row row = rows.get(rowIndex); - Font base = table.getFont(); - // The foreground is set on every row: this renderer remembers the last - // unselected colour it was given, so a greyed row would tint the rest. - if (row.isHeading()) { - setFont(base.deriveFont(Font.BOLD)); - setForeground(selected ? table.getSelectionForeground() : table.getForeground()); - setBorder(new ScaledEmptyBorder(2, 2, 2, 2)); - setToolTipText(null); - return this; - } - setBorder(new ScaledEmptyBorder(2, 18, 2, 2)); - setFont(base.deriveFont(working.isImportant(row.event) ? Font.BOLD : Font.PLAIN)); - boolean silent = !sounds.hasSound(row.event); - setForeground(selected ? table.getSelectionForeground() - : silent ? java.awt.Color.GRAY : table.getForeground()); - setToolTipText(silent ? "This sound pack has no sound for this action" : null); - return this; - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/OfflineMessageComposeDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/OfflineMessageComposeDialog.java deleted file mode 100644 index 5571b79..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/OfflineMessageComposeDialog.java +++ /dev/null @@ -1,457 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.FlatClientProperties; -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.contacts.Contact; -import com.ts3client.contacts.ContactStore; -import com.ts3client.contacts.ContactType; -import com.ts3client.net.DatabaseClient; -import com.ts3client.net.OfflineMessage; -import com.ts3client.net.TeamspeakConnection; -import com.ts3client.text.BBCode; - -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.DefaultListCellRenderer; -import javax.swing.DefaultListModel; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSplitPane; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.ListSelectionModel; -import javax.swing.SwingUtilities; -import javax.swing.UIManager; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.text.AbstractDocument; -import javax.swing.text.AttributeSet; -import javax.swing.text.BadLocationException; -import javax.swing.text.DocumentFilter; -import javax.swing.text.JTextComponent; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Cursor; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.Window; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Pattern; - -/** - * Writing an offline message, as the official client's New / Reply Offline Message window: - * recipients, subject and text on the left, the clients one may pick from on the right. - * - *

    A recipient is typed as a unique id or a nickname. Unlike the official client, which - * only searches the server's database, a unique id is looked up directly, which needs no - * permission; a nickname needs {@code b_virtualserver_client_dbsearch}. - */ -final class OfflineMessageComposeDialog extends JDialog { - - private static final Pattern UNIQUE_ID = Pattern.compile("[A-Za-z0-9+/]{27}="); - /** The client property naming the recipient a chip stands for. */ - private static final String CHIP_UID = "ts3.recipientUid"; - - private final TeamspeakConnection conn; - - /** Recipients by unique id, in the order they were added. */ - private final Map recipients = new LinkedHashMap<>(); - private final JPanel recipientChips = new JPanel(new FlowLayout(FlowLayout.LEADING, UIScale.scale(4), UIScale.scale(2))); - private final JTextField recipientField = new JTextField(); - private final JLabel recipientError = new JLabel(); - private final JTextField subjectField = new JTextField(); - private final JTextArea bodyArea = new JTextArea(); - private final JLabel limitLabel = new JLabel(" "); - private final DefaultListModel available = new DefaultListModel<>(); - private final JList availableList = new JList<>(available); - private final JButton sendButton = new JButton("Send"); - private boolean sending; - - static OfflineMessageComposeDialog compose(Window owner, TeamspeakConnection conn, ContactStore contacts) { - return new OfflineMessageComposeDialog(owner, "New Offline Message", conn, contacts); - } - - /** A reply to {@code message}, quoting {@code body}. */ - static OfflineMessageComposeDialog reply(Window owner, TeamspeakConnection conn, ContactStore contacts, - OfflineMessage message, String body) { - OfflineMessageComposeDialog d = new OfflineMessageComposeDialog(owner, "Reply Offline Message", conn, contacts); - d.addRecipient(new DatabaseClient(message.senderUid(), 0, message.senderName())); - String subject = message.subject().regionMatches(true, 0, "Re:", 0, 3) - ? message.subject() : "Re: " + message.subject(); - d.subjectField.setText(subject.length() > TeamspeakConnection.OFFLINE_MESSAGE_SUBJECT_LIMIT - ? subject.substring(0, TeamspeakConnection.OFFLINE_MESSAGE_SUBJECT_LIMIT) : subject); - d.bodyArea.setText(quote(message.senderName(), body)); - d.bodyArea.setCaretPosition(d.bodyArea.getDocument().getLength()); - return d; - } - - /** The reply's opening, as the official client writes it: who wrote, then their text marked with "> ". */ - private static String quote(String sender, String body) { - StringBuilder out = new StringBuilder("\"").append(sender).append("\" wrote:\n"); - for (String line : body.split("\n", -1)) out.append("> ").append(line).append('\n'); - return out.toString(); - } - - private OfflineMessageComposeDialog(Window owner, String title, TeamspeakConnection conn, ContactStore contacts) { - super(owner, title, ModalityType.MODELESS); - this.conn = conn; - - limit(subjectField, TeamspeakConnection.OFFLINE_MESSAGE_SUBJECT_LIMIT); - limit(bodyArea, TeamspeakConnection.OFFLINE_MESSAGE_LIMIT); - for (Contact c : contacts.all()) { - if (c.type != ContactType.BLOCKED) { - available.addElement(new DatabaseClient(c.uniqueId, 0, c.nickname.isEmpty() ? c.uniqueId : c.nickname)); - } - } - sortAvailable(); - - JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, buildMessage(), buildAvailable()); - split.setResizeWeight(1); - split.setBorder(null); - split.setOpaque(false); - - JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(8))); - content.setBackground(Theme.windowBg()); - content.setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); - content.add(split, BorderLayout.CENTER); - content.add(buildButtons(), BorderLayout.SOUTH); - setContentPane(content); - - setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); - addWindowListener(new WindowAdapter() { - @Override - public void windowClosing(WindowEvent e) { - cancel(); - } - }); - Dialogs.closeOnEscape(this, this::cancel); - setPreferredSize(UIScale.scale(new Dimension(620, 460))); - pack(); - setLocationRelativeTo(owner); - updateSendButton(); - } - - // ---- construction ---- - - private JPanel buildMessage() { - recipientChips.setOpaque(false); - recipientField.putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, "Nickname or unique ID"); - recipientField.addActionListener(e -> resolveTyped()); - recipientField.addKeyListener(new KeyAdapter() { - @Override - public void keyPressed(KeyEvent e) { - if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE && recipientField.getText().isEmpty() - && !recipients.isEmpty()) { - removeRecipient(new ArrayList<>(recipients.keySet()).get(recipients.size() - 1)); - } - } - }); - recipientField.getDocument().addDocumentListener(onChange(() -> recipientError.setVisible(false))); - recipientError.setForeground(UIManager.getColor("Actions.Red")); - recipientError.setVisible(false); - - JPanel recipientBox = new JPanel(); - recipientBox.setLayout(new BoxLayout(recipientBox, BoxLayout.Y_AXIS)); - recipientBox.setOpaque(false); - recipientBox.add(left(recipientChips)); - recipientBox.add(left(recipientField)); - recipientBox.add(left(recipientError)); - - JPanel subjectRow = new JPanel(new BorderLayout(UIScale.scale(6), 0)); - subjectRow.setOpaque(false); - JLabel subjectLabel = new JLabel("Subject:"); - subjectLabel.setDisplayedMnemonic(KeyEvent.VK_S); - subjectLabel.setLabelFor(subjectField); - subjectRow.add(subjectLabel, BorderLayout.WEST); - subjectRow.add(subjectField, BorderLayout.CENTER); - - JPanel top = new JPanel(); - top.setLayout(new BoxLayout(top, BoxLayout.Y_AXIS)); - top.setOpaque(false); - top.add(left(new JLabel("Recipients:"))); - top.add(left(recipientBox)); - top.add(Box.createVerticalStrut(UIScale.scale(8))); - top.add(left(subjectRow)); - - bodyArea.setLineWrap(true); - bodyArea.setWrapStyleWord(true); - bodyArea.setFont(Theme.uiFont()); - bodyArea.getDocument().addDocumentListener(onChange(this::updateSendButton)); - limitLabel.setForeground(UIManager.getColor("Actions.Red")); - - JPanel panel = new JPanel(new BorderLayout(0, UIScale.scale(6))); - panel.setOpaque(false); - panel.setBorder(new ScaledEmptyBorder(0, 0, 0, 6)); - panel.add(top, BorderLayout.NORTH); - panel.add(new JScrollPane(bodyArea), BorderLayout.CENTER); - panel.add(limitLabel, BorderLayout.SOUTH); - return panel; - } - - private JPanel buildAvailable() { - availableList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - availableList.setCellRenderer(new DefaultListCellRenderer() { - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, - boolean selected, boolean focused) { - DatabaseClient c = (DatabaseClient) value; - String text = c.databaseId() > 0 ? c.nickname() + " (" + c.databaseId() + ")" : c.nickname(); - super.getListCellRendererComponent(list, text, index, selected, focused); - setToolTipText(c.uniqueId()); - return this; - } - }); - availableList.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e)) addChosen(); - } - }); - availableList.addKeyListener(new KeyAdapter() { - @Override - public void keyPressed(KeyEvent e) { - if (e.getKeyCode() == KeyEvent.VK_ENTER) addChosen(); - } - }); - - JPanel panel = new JPanel(new BorderLayout(0, UIScale.scale(4))); - panel.setOpaque(false); - panel.setBorder(new ScaledEmptyBorder(0, 6, 0, 0)); - panel.add(new JLabel("Available Contacts:"), BorderLayout.NORTH); - panel.add(new JScrollPane(availableList), BorderLayout.CENTER); - panel.setPreferredSize(UIScale.scale(new Dimension(170, 0))); - return panel; - } - - private JPanel buildButtons() { - sendButton.addActionListener(e -> send()); - JButton cancel = new JButton("Cancel"); - cancel.addActionListener(e -> cancel()); - JPanel row = new JPanel(new BorderLayout()); - row.setOpaque(false); - row.add(sendButton, BorderLayout.WEST); - row.add(cancel, BorderLayout.EAST); - return row; - } - - /** Lines a component up on the left of a vertical box; a text field keeps its height. */ - private static Component left(JComponent c) { - c.setAlignmentX(LEFT_ALIGNMENT); - if (c instanceof JTextField) c.setMaximumSize(new Dimension(Integer.MAX_VALUE, c.getPreferredSize().height)); - return c; - } - - private static DocumentListener onChange(Runnable action) { - return new DocumentListener() { - @Override - public void insertUpdate(DocumentEvent e) { - action.run(); - } - - @Override - public void removeUpdate(DocumentEvent e) { - action.run(); - } - - @Override - public void changedUpdate(DocumentEvent e) { - action.run(); - } - }; - } - - /** Caps a field at what the server accepts, saying so when typing runs into it. */ - private void limit(JTextComponent field, int max) { - ((AbstractDocument) field.getDocument()).setDocumentFilter(new DocumentFilter() { - @Override - public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr) - throws BadLocationException { - replace(fb, offset, 0, text, attr); - } - - @Override - public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) - throws BadLocationException { - String added = text == null ? "" : text; - int room = max - (fb.getDocument().getLength() - length); - if (added.length() > room) { - added = added.substring(0, Math.max(0, room)); - limitLabel.setText("Character limit reached (" + max + ")"); - } - super.replace(fb, offset, length, added, attrs); - } - - @Override - public void remove(FilterBypass fb, int offset, int length) throws BadLocationException { - super.remove(fb, offset, length); - limitLabel.setText(" "); - } - }); - } - - // ---- recipients ---- - - private void addRecipient(DatabaseClient client) { - if (client.uniqueId().isEmpty() || recipients.containsKey(client.uniqueId())) return; - recipients.put(client.uniqueId(), client); - recipientChips.add(chip(client)); - recipientChips.revalidate(); - recipientChips.repaint(); - updateSendButton(); - } - - private void removeRecipient(String uniqueId) { - if (recipients.remove(uniqueId) == null) return; - for (Component c : recipientChips.getComponents()) { - if (uniqueId.equals(((JPanel) c).getClientProperty(CHIP_UID))) recipientChips.remove(c); - } - recipientChips.revalidate(); - recipientChips.repaint(); - updateSendButton(); - } - - /** A recipient's name with a cross that takes them off again. */ - private JPanel chip(DatabaseClient client) { - JLabel name = new JLabel(client.nickname().isEmpty() ? client.uniqueId() : client.nickname()); - name.setToolTipText(client.uniqueId()); - JLabel remove = new JLabel("×"); - remove.setToolTipText("Remove"); - remove.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - remove.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - removeRecipient(client.uniqueId()); - } - }); - JPanel chip = new JPanel(new FlowLayout(FlowLayout.LEADING, UIScale.scale(4), 0)); - chip.putClientProperty(CHIP_UID, client.uniqueId()); - chip.setBackground(Theme.treeBg()); - chip.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Theme.border()), - new ScaledEmptyBorder(1, 2, 1, 2))); - chip.add(name); - chip.add(remove); - return chip; - } - - private void addChosen() { - DatabaseClient chosen = availableList.getSelectedValue(); - if (chosen != null) addRecipient(chosen); - } - - /** Turns what was typed into a recipient: a unique id directly, a nickname by contacts or a server search. */ - private void resolveTyped() { - String typed = recipientField.getText().trim(); - if (typed.isEmpty()) return; - if (UNIQUE_ID.matcher(typed).matches()) { - conn.lookupDatabaseClient(typed, (client, error) -> SwingUtilities.invokeLater(() -> { - if (error != null) showRecipientError(error); - else if (client == null) showRecipientError("The unique ID is unknown on this server."); - else accept(client); - })); - return; - } - for (int i = 0; i < available.size(); i++) { - if (available.get(i).nickname().equalsIgnoreCase(typed)) { - accept(available.get(i)); - return; - } - } - conn.searchDatabaseClients(typed, (found, error) -> SwingUtilities.invokeLater(() -> { - if (error != null) { - showRecipientError(error); - } else if (found.isEmpty()) { - showRecipientError("The nickname is unknown on this server."); - } else { - offer(found); - DatabaseClient exact = found.stream().filter(c -> c.nickname().equalsIgnoreCase(typed)) - .findFirst().orElse(found.size() == 1 ? found.get(0) : null); - if (exact != null) accept(exact); - } - })); - } - - private void accept(DatabaseClient client) { - addRecipient(client); - recipientField.setText(""); - } - - /** Lists search results among the contacts, so a match can be picked from them. */ - private void offer(List found) { - for (DatabaseClient c : found) { - boolean listed = false; - for (int i = 0; i < available.size() && !listed; i++) { - listed = available.get(i).uniqueId().equals(c.uniqueId()); - } - if (!listed) available.addElement(c); - } - sortAvailable(); - availableList.setSelectedValue(found.get(0), true); - } - - private void sortAvailable() { - List sorted = new ArrayList<>(); - for (int i = 0; i < available.size(); i++) sorted.add(available.get(i)); - sorted.sort(Comparator.comparing(DatabaseClient::nickname, String.CASE_INSENSITIVE_ORDER)); - available.clear(); - sorted.forEach(available::addElement); - } - - private void showRecipientError(String message) { - if (!isDisplayable()) return; - recipientError.setText("" + BBCode.escape(message) + ""); - recipientError.setVisible(true); - recipientError.getParent().revalidate(); - } - - // ---- sending ---- - - private void updateSendButton() { - sendButton.setEnabled(!sending && !recipients.isEmpty() && !bodyArea.getText().isBlank()); - } - - private void send() { - if (!sendButton.isEnabled()) return; - sending = true; - updateSendButton(); - conn.sendOfflineMessage(new ArrayList<>(recipients.keySet()), subjectField.getText(), bodyArea.getText(), - error -> SwingUtilities.invokeLater(() -> { - sending = false; - if (!isDisplayable()) return; - if (error == null) { - dispose(); - return; - } - updateSendButton(); - JOptionPane.showMessageDialog(this, "Failed to send offline message: " + error, getTitle(), - JOptionPane.ERROR_MESSAGE); - })); - } - - private void cancel() { - if (!recipients.isEmpty()) { - int answer = JOptionPane.showConfirmDialog(this, - "The list of recipients is not empty and the message has not yet been sent.\nDo you want to cancel?", - "Please Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); - if (answer != JOptionPane.YES_OPTION) return; - } - dispose(); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/OfflineMessagesDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/OfflineMessagesDialog.java deleted file mode 100644 index 3fd9fa9..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/OfflineMessagesDialog.java +++ /dev/null @@ -1,573 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.net.OfflineMessage; -import com.ts3client.net.TeamspeakConnection; -import com.ts3client.text.BBCode; - -import javax.swing.AbstractAction; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.Icon; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JEditorPane; -import javax.swing.JLabel; -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.JScrollPane; -import javax.swing.JSplitPane; -import javax.swing.JTable; -import javax.swing.JTextField; -import javax.swing.KeyStroke; -import javax.swing.ListSelectionModel; -import javax.swing.RowSorter; -import javax.swing.SortOrder; -import javax.swing.SwingUtilities; -import javax.swing.UIManager; -import javax.swing.event.HyperlinkEvent; -import javax.swing.event.PopupMenuEvent; -import javax.swing.event.PopupMenuListener; -import javax.swing.table.AbstractTableModel; -import javax.swing.table.DefaultTableCellRenderer; -import javax.swing.table.TableRowSorter; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Frame; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.KeyEvent; -import java.awt.event.MouseEvent; -import java.time.Instant; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Our offline message inbox on one server, as the official client's Tools > Offline Messages - * window: the messages above, the selected one's subject and text below. Viewing a message - * marks it read. - * - *

    One per server tab and modeless; the tab closes it when the connection goes away. - */ -final class OfflineMessagesDialog extends JDialog { - - private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - - /** Where Compose and Reply lead: the tab opens the compose window. */ - interface Composer { - void compose(); - - void reply(OfflineMessage message, String body); - } - - private enum Column { - STATE("", 24), - SUBJECT("Subject", 200), - SENDER("Sender", 110), - DATE("Date", 150); - - final String title; - final int width; - - Column(String title, int width) { - this.title = title; - this.width = width; - } - } - - private final TeamspeakConnection conn; - private final Composer composer; - - private final MessageTableModel tableModel = new MessageTableModel(); - private final JTable table = new JTable(tableModel) { - /** - * The popup acts on what was clicked; Swing asks here before showing it. As in the - * official client, that selects the row without opening it in the reader. - */ - @Override - public Point getPopupLocation(MouseEvent e) { - int row = e == null ? -1 : rowAtPoint(e.getPoint()); - if (row >= 0 && !isRowSelected(row)) { - selectingForPopup = true; - try { - setRowSelectionInterval(row, row); - } finally { - selectingForPopup = false; - } - } - return super.getPopupLocation(e); - } - }; - private final JButton composeButton = new JButton("Compose"); - private final JButton replyButton = new JButton("Reply"); - private final JButton deleteButton = new JButton("Delete"); - private final JTextField subjectField = new JTextField(); - private final JEditorPane bodyPane = HtmlStyles.pane("font-family:sans-serif; font-size:11px;"); - private final JLabel status = new JLabel(" "); - - /** Bodies already read, by message id; each costs a {@code messageget}. */ - private final Map bodies = new HashMap<>(); - /** The message the reader shows or is loading, or -1. */ - private int shownId = -1; - /** Set while a right-click selects its row, which leaves the reader alone. */ - private boolean selectingForPopup; - private boolean loading; - - OfflineMessagesDialog(Frame owner, TeamspeakConnection conn, Composer composer) { - super(owner, "Offline Messages", false); - this.conn = conn; - this.composer = composer; - - JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, buildTable(), buildReader()); - split.setResizeWeight(0.45); - split.setBorder(null); - split.setOpaque(false); - - JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(6))); - content.setBackground(Theme.windowBg()); - content.setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); - content.add(buildToolbar(), BorderLayout.NORTH); - content.add(split, BorderLayout.CENTER); - content.add(buildBottom(), BorderLayout.SOUTH); - setContentPane(content); - bindKeys(); - - serverNameChanged(); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - setPreferredSize(UIScale.scale(new Dimension(600, 560))); - pack(); - setLocationRelativeTo(owner); - updateButtons(); - reload(); - } - - // ---- construction ---- - - private JPanel buildToolbar() { - composeButton.setMnemonic(KeyEvent.VK_C); - composeButton.setToolTipText("Compose a new message
    (Ctrl+N)"); - composeButton.addActionListener(e -> compose()); - replyButton.setMnemonic(KeyEvent.VK_R); - replyButton.setToolTipText("Reply to message"); - replyButton.addActionListener(e -> replySelected()); - deleteButton.setMnemonic(KeyEvent.VK_D); - deleteButton.setToolTipText("Delete selected messages
    (Del)"); - deleteButton.addActionListener(e -> deleteSelected()); - - JPanel bar = new JPanel(); - bar.setLayout(new BoxLayout(bar, BoxLayout.X_AXIS)); - bar.setOpaque(false); - bar.add(composeButton); - bar.add(Box.createHorizontalStrut(UIScale.scale(6))); - bar.add(replyButton); - bar.add(Box.createHorizontalGlue()); - bar.add(deleteButton); - return bar; - } - - private JScrollPane buildTable() { - table.setFont(Theme.uiFont()); - table.setRowHeight(UIScale.scale(20)); - table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - table.setFillsViewportHeight(true); - table.setShowGrid(false); - table.getTableHeader().setReorderingAllowed(false); - table.setComponentPopupMenu(tablePopup()); - table.getSelectionModel().addListSelectionListener(e -> { - if (e.getValueIsAdjusting()) return; - updateButtons(); - if (!selectingForPopup) showSelected(); - }); - MessageCellRenderer renderer = new MessageCellRenderer(); - for (Column c : Column.values()) { - table.getColumnModel().getColumn(c.ordinal()).setPreferredWidth(UIScale.scale(c.width)); - table.getColumnModel().getColumn(c.ordinal()).setCellRenderer(renderer); - } - table.getColumnModel().getColumn(Column.STATE.ordinal()).setMaxWidth(UIScale.scale(Column.STATE.width)); - - TableRowSorter sorter = new TableRowSorter<>(tableModel); - sorter.setComparator(Column.SUBJECT.ordinal(), String.CASE_INSENSITIVE_ORDER); - sorter.setComparator(Column.SENDER.ordinal(), String.CASE_INSENSITIVE_ORDER); - sorter.setSortKeys(List.of(new RowSorter.SortKey(Column.DATE.ordinal(), SortOrder.ASCENDING))); - table.setRowSorter(sorter); - - JScrollPane scroll = new JScrollPane(table); - scroll.getViewport().setBackground(Theme.treeBg()); - scroll.setMinimumSize(UIScale.scale(new Dimension(0, 80))); - return scroll; - } - - private JPanel buildReader() { - subjectField.setEditable(false); - bodyPane.addHyperlinkListener(e -> { - if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) Links.open(e.getDescription(), this); - }); - - JPanel subjectRow = new JPanel(new BorderLayout(UIScale.scale(6), 0)); - subjectRow.setOpaque(false); - subjectRow.add(new JLabel("Subject:"), BorderLayout.WEST); - subjectRow.add(subjectField, BorderLayout.CENTER); - - JScrollPane bodyScroll = new JScrollPane(bodyPane); - HtmlStyles.fillViewport(bodyPane); - - JPanel reader = new JPanel(new BorderLayout(0, UIScale.scale(6))); - reader.setOpaque(false); - reader.setBorder(new ScaledEmptyBorder(6, 0, 0, 0)); - reader.add(subjectRow, BorderLayout.NORTH); - reader.add(bodyScroll, BorderLayout.CENTER); - reader.setMinimumSize(UIScale.scale(new Dimension(0, 100))); - return reader; - } - - private JPanel buildBottom() { - JButton reload = new JButton("Reload", Icons.of("REFRESH")); - reload.setToolTipText("Reload messages
    (F5)"); - reload.addActionListener(e -> reload()); - JButton close = new JButton("Close"); - close.addActionListener(e -> dispose()); - - JPanel row = new JPanel(new BorderLayout()); - row.setOpaque(false); - row.add(reload, BorderLayout.WEST); - row.add(close, BorderLayout.EAST); - - JPanel bottom = new JPanel(new BorderLayout(0, UIScale.scale(8))); - bottom.setOpaque(false); - bottom.add(status, BorderLayout.NORTH); - bottom.add(row, BorderLayout.SOUTH); - status.setForeground(Theme.chatEvent()); - return bottom; - } - - private JPopupMenu tablePopup() { - JMenuItem reply = item("Reply to message", this::replySelected); - JMenuItem delete = item("Delete message", this::deleteSelected); - JMenuItem markRead = item("Mark as Read", () -> markSelected(true)); - JMenuItem markUnread = item("Mark as Unread", () -> markSelected(false)); - JPopupMenu menu = new JPopupMenu(); - menu.add(reply); - menu.add(delete); - menu.addSeparator(); - menu.add(item("Reload messages", this::reload)); - menu.addSeparator(); - menu.add(markRead); - menu.add(markUnread); - menu.addPopupMenuListener(new PopupMenuListener() { - @Override - public void popupMenuWillBecomeVisible(PopupMenuEvent e) { - List selected = selectedMessages(); - reply.setEnabled(replyButton.isEnabled()); - delete.setEnabled(!selected.isEmpty()); - markRead.setEnabled(selected.stream().anyMatch(m -> !m.read())); - markUnread.setEnabled(selected.stream().anyMatch(OfflineMessage::read)); - } - - @Override - public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { - } - - @Override - public void popupMenuCanceled(PopupMenuEvent e) { - } - }); - return menu; - } - - private static JMenuItem item(String text, Runnable action) { - JMenuItem item = new JMenuItem(text); - item.addActionListener(e -> action.run()); - return item; - } - - private void bindKeys() { - bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("F5"), this::reload); - bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control N"), this::compose); - bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control W"), this::dispose); - bind(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), - this::deleteSelected); - Dialogs.closeOnEscape(this); - } - - private static void bind(JComponent target, int condition, KeyStroke key, Runnable action) { - String name = "ts3-offline-messages-" + key; - target.getInputMap(condition).put(key, name); - target.getActionMap().put(name, new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - action.run(); - } - }); - } - - // ---- data ---- - - void serverNameChanged() { - String name = conn.getModel().getServerName(); - setTitle(name == null || name.isBlank() ? "Offline Messages" : "Offline Messages on " + name); - } - - void connectionLost() { - dispose(); - } - - /** Reads the inbox again, keeping the selection where the messages are still there. */ - void reload() { - if (loading) return; - loading = true; - status.setText("Loading…"); - conn.requestOfflineMessages((messages, error) -> SwingUtilities.invokeLater(() -> { - loading = false; - if (!isDisplayable()) return; - if (error != null) { - status.setText("Failed to list offline messages: " + error); - return; - } - setMessages(messages); - status.setText(messages.isEmpty() ? "No messages" : " "); - })); - } - - private void setMessages(List messages) { - Set selected = new HashSet<>(); - for (OfflineMessage m : selectedMessages()) selected.add(m.id()); - tableModel.setMessages(messages); - for (int i = 0; i < messages.size(); i++) { - if (!selected.contains(messages.get(i).id())) continue; - int view = table.convertRowIndexToView(i); - if (view >= 0) table.addRowSelectionInterval(view, view); - } - updateButtons(); - showSelected(); - } - - private List selectedMessages() { - List out = new ArrayList<>(); - for (int view : table.getSelectedRows()) out.add(tableModel.get(table.convertRowIndexToModel(view))); - return out; - } - - private OfflineMessage singleSelected() { - List selected = selectedMessages(); - return selected.size() == 1 ? selected.get(0) : null; - } - - private void updateButtons() { - boolean canSend = conn.canSendOfflineMessages(); - composeButton.setEnabled(canSend); - replyButton.setEnabled(canSend && singleSelected() != null); - deleteButton.setEnabled(table.getSelectedRowCount() > 0); - } - - /** Shows the selected message in the reader, reading its body first if need be, and marks it read. */ - private void showSelected() { - OfflineMessage message = singleSelected(); - if (message == null) { - shownId = -1; - subjectField.setText(""); - bodyPane.setText(""); - return; - } - if (message.id() == shownId) return; - shownId = message.id(); - subjectField.setText(message.subject()); - subjectField.setCaretPosition(0); - String body = bodies.get(message.id()); - if (body != null) { - showBody(message, body); - return; - } - bodyPane.setText(""); - conn.requestOfflineMessageBody(message.id(), (text, error) -> SwingUtilities.invokeLater(() -> { - if (!isDisplayable()) return; - if (error != null) { - if (shownId == message.id()) status.setText("Failed to get offline message: " + error); - return; - } - bodies.put(message.id(), text); - if (shownId == message.id()) showBody(message, text); - })); - } - - private void showBody(OfflineMessage message, String body) { - bodyPane.setText("" + BBCode.toHtml(body) + ""); - bodyPane.setCaretPosition(0); - if (!message.read()) mark(List.of(message), true); - } - - // ---- actions ---- - - private void compose() { - if (composeButton.isEnabled()) composer.compose(); - } - - private void replySelected() { - OfflineMessage message = singleSelected(); - if (message == null || !replyButton.isEnabled()) return; - String body = bodies.get(message.id()); - if (body != null) { - composer.reply(message, body); - return; - } - conn.requestOfflineMessageBody(message.id(), (text, error) -> SwingUtilities.invokeLater(() -> { - if (!isDisplayable()) return; - if (error != null) { - status.setText("Failed to get offline message: " + error); - return; - } - bodies.put(message.id(), text); - composer.reply(message, text); - })); - } - - private void markSelected(boolean read) { - mark(selectedMessages().stream().filter(m -> m.read() != read).toList(), read); - } - - /** Flags messages read or unread, showing the change straight away. */ - private void mark(List messages, boolean read) { - if (messages.isEmpty()) return; - for (OfflineMessage m : messages) tableModel.replace(m.withRead(read)); - conn.markOfflineMessages(messages.stream().map(OfflineMessage::id).toList(), read, - error -> SwingUtilities.invokeLater(() -> { - if (error == null || !isDisplayable()) return; - status.setText("Failed to update offline message: " + error); - reload(); - })); - } - - private void deleteSelected() { - List selected = selectedMessages(); - if (selected.isEmpty()) return; - List unread = selected.stream().filter(m -> !m.read()).toList(); - if (!unread.isEmpty()) { - String question = unread.size() == 1 - ? "Do you really want to delete the unread message
    with subject: \"" - + BBCode.escape(subjectOrPlaceholder(unread.get(0))) + "\"?" - : "Do you really want to delete " + unread.size() + " unread messages?"; - int answer = JOptionPane.showConfirmDialog(this, question, "Delete Offline Message", - JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); - if (answer != JOptionPane.YES_OPTION) return; - } - conn.deleteOfflineMessages(selected.stream().map(OfflineMessage::id).toList(), - error -> SwingUtilities.invokeLater(() -> { - if (!isDisplayable()) return; - if (error != null) { - JOptionPane.showMessageDialog(this, "Failed to delete offline message: " + error, - getTitle(), JOptionPane.ERROR_MESSAGE); - } - for (OfflineMessage m : selected) bodies.remove(m.id()); - reload(); - })); - } - - private static String subjectOrPlaceholder(OfflineMessage m) { - return m.subject().isEmpty() ? "" : m.subject(); - } - - // ---- table ---- - - private static final class MessageTableModel extends AbstractTableModel { - - private List messages = List.of(); - - void setMessages(List messages) { - this.messages = new ArrayList<>(messages); - fireTableDataChanged(); - } - - OfflineMessage get(int row) { - return messages.get(row); - } - - void replace(OfflineMessage message) { - for (int i = 0; i < messages.size(); i++) { - if (messages.get(i).id() != message.id()) continue; - messages.set(i, message); - fireTableRowsUpdated(i, i); - return; - } - } - - @Override - public int getRowCount() { - return messages.size(); - } - - @Override - public int getColumnCount() { - return Column.values().length; - } - - @Override - public String getColumnName(int column) { - return Column.values()[column].title; - } - - @Override - public Class getColumnClass(int column) { - return switch (Column.values()[column]) { - case STATE -> Boolean.class; - case DATE -> Long.class; - default -> String.class; - }; - } - - @Override - public Object getValueAt(int row, int column) { - OfflineMessage m = messages.get(row); - return switch (Column.values()[column]) { - case STATE -> m.read(); - case SUBJECT -> m.subject(); - case SENDER -> m.senderName(); - case DATE -> m.timestampEpochSeconds(); - }; - } - } - - /** Unread messages in bold, as the official client shows them; a missing subject greyed out. */ - private final class MessageCellRenderer extends DefaultTableCellRenderer { - @Override - public Component getTableCellRendererComponent(JTable t, Object value, boolean selected, - boolean focused, int row, int column) { - // setForeground sticks as the renderer's unselected colour; clear it so the - // table's own colour applies again after a greyed cell. - setForeground(null); - OfflineMessage m = tableModel.get(t.convertRowIndexToModel(row)); - Column c = Column.values()[column]; - Object shown = switch (c) { - case STATE -> ""; - case SUBJECT -> subjectOrPlaceholder(m); - case DATE -> m.timestampEpochSeconds() <= 0 ? "" : DATE.format( - Instant.ofEpochSecond(m.timestampEpochSeconds()).atZone(ZoneId.systemDefault())); - default -> value; - }; - super.getTableCellRendererComponent(t, shown, selected, focused, row, column); - setFont(m.read() ? t.getFont() : t.getFont().deriveFont(Font.BOLD)); - setBorder(new ScaledEmptyBorder(0, 2, 0, 2)); - setHorizontalAlignment(c == Column.STATE ? CENTER : LEADING); - setIcon(c == Column.STATE ? stateIcon(m.read()) : null); - setToolTipText(c == Column.SENDER && !m.senderUid().equals(m.senderName()) ? m.senderUid() : null); - if (c == Column.SUBJECT && m.subject().isEmpty() && !selected) { - setForeground(UIManager.getColor("Label.disabledForeground")); - } - return this; - } - } - - private static Icon stateIcon(boolean read) { - return read ? Icons.of("MESSAGES") : Icons.of("OFFLINE_MESSAGES"); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/OptionsPage.java b/ts3-client/swing/src/main/java/com/ts3client/ui/OptionsPage.java deleted file mode 100644 index 2852c19..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/OptionsPage.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.ts3client.ui; - -import javax.swing.ImageIcon; -import javax.swing.JComponent; -import java.util.List; - -/** - * One page of the Options dialog, as the sidebar lists it. - * - * @param iconKeys TeamSpeak icon keys to try in turn, since packs differ in what they ship - */ -record OptionsPage(String title, List iconKeys, JComponent content) { - - OptionsPage(String title, JComponent content, String... iconKeys) { - this(title, List.of(iconKeys), content); - } - - /** @return the page's icon at {@code size} pixels, or {@code null} when the pack has none */ - ImageIcon icon(int size) { - for (String key : iconKeys) { - ImageIcon icon = IconTheme.icon(key, size); - if (icon != null) return icon; - } - return null; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/OptionsSidebar.java b/ts3-client/swing/src/main/java/com/ts3client/ui/OptionsSidebar.java deleted file mode 100644 index 2dea9ef..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/OptionsSidebar.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; - -import javax.swing.DefaultListModel; -import javax.swing.Icon; -import javax.swing.ImageIcon; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.ListCellRenderer; -import javax.swing.ListSelectionModel; -import javax.swing.UIManager; -import java.awt.Color; -import java.awt.Component; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.util.List; - -/** The Options dialog's page list: large icons with their titles, one page per row, as in TS3. */ -final class OptionsSidebar extends JList { - - static final int ICON_SIZE = 32; - - OptionsSidebar(List pages) { - super(model(pages)); - setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - setCellRenderer(new Renderer()); - setBorder(new ScaledEmptyBorder(4, 4, 4, 4)); - } - - private static DefaultListModel model(List pages) { - DefaultListModel model = new DefaultListModel<>(); - pages.forEach(model::addElement); - return model; - } - - /** - * Paints its own rounded selection in the accent colour: the list's selection would turn - * grey whenever focus moves into the page, and the sidebar should always show where you are. - */ - private static final class Renderer extends JLabel implements ListCellRenderer { - - private boolean selected; - - Renderer() { - setOpaque(false); - setBorder(new ScaledEmptyBorder(6, 8, 6, 16)); - } - - @Override - public Component getListCellRendererComponent(JList list, OptionsPage page, - int index, boolean isSelected, boolean focus) { - int size = UIScale.scale(ICON_SIZE); - ImageIcon icon = page.icon(size); - setIcon(icon != null ? icon : new BlankIcon(size)); - setIconTextGap(UIScale.scale(10)); - setText(page.title()); - setFont(list.getFont()); - selected = isSelected; - setForeground(isSelected ? selectionForeground() : list.getForeground()); - return this; - } - - @Override - protected void paintComponent(Graphics g) { - if (selected) { - Graphics2D g2 = (Graphics2D) g.create(); - try { - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g2.setColor(accent()); - int arc = UIScale.scale(8); - g2.fillRoundRect(0, 0, getWidth(), getHeight(), arc, arc); - } finally { - g2.dispose(); - } - } - super.paintComponent(g); - } - - private static Color accent() { - Color c = UIManager.getColor("Component.accentColor"); - return c != null ? c : UIManager.getColor("List.selectionBackground"); - } - - private static Color selectionForeground() { - Color c = UIManager.getColor("List.selectionForeground"); - return c != null ? c : Color.WHITE; - } - } - - /** Keeps the titles lined up for a page whose icon the pack lacks. */ - private record BlankIcon(int size) implements Icon { - @Override - public void paintIcon(Component c, Graphics g, int x, int y) { - } - - @Override - public int getIconWidth() { - return size; - } - - @Override - public int getIconHeight() { - return size; - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/PictureViewer.java b/ts3-client/swing/src/main/java/com/ts3client/ui/PictureViewer.java deleted file mode 100644 index 263f206..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/PictureViewer.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.KeyStroke; -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.GraphicsConfiguration; -import java.awt.Image; -import java.awt.Rectangle; -import java.awt.Window; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.image.BufferedImage; - -/** A picture at full size, or as large as the screen allows, with a way to save it. */ -final class PictureViewer extends JDialog { - - private static final int MIN_WIDTH = 360; - private static final int MIN_HEIGHT = 240; - - PictureViewer(Window owner, String title, BufferedImage picture, Runnable onSave) { - super(owner, title, ModalityType.MODELESS); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - - JLabel view = new JLabel(new ImageIcon(fitted(picture, owner))); - view.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - dispose(); - } - }); - JScrollPane scroll = new JScrollPane(view); - scroll.setBorder(null); - - JButton save = new JButton("Save…"); - save.addActionListener(e -> onSave.run()); - JButton close = new JButton("Close"); - close.addActionListener(e -> dispose()); - JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT, UIScale.scale(4), 0)); - buttons.setBorder(new ScaledEmptyBorder(6, 6, 6, 6)); - buttons.add(save); - buttons.add(close); - - add(scroll, BorderLayout.CENTER); - add(buttons, BorderLayout.SOUTH); - getRootPane().registerKeyboardAction(e -> dispose(), KeyStroke.getKeyStroke("ESCAPE"), - JComponent.WHEN_IN_FOCUSED_WINDOW); - getRootPane().setDefaultButton(close); - pack(); - // A small picture still gets a window its title and buttons fit in. - setSize(Math.max(getWidth(), UIScale.scale(MIN_WIDTH)), Math.max(getHeight(), UIScale.scale(MIN_HEIGHT))); - setLocationRelativeTo(owner); - } - - /** The picture narrowed to most of the owner's screen; small ones are left as they are. */ - private static Image fitted(BufferedImage picture, Window owner) { - GraphicsConfiguration gc = owner != null ? owner.getGraphicsConfiguration() : null; - Rectangle screen = gc != null ? gc.getBounds() : new Rectangle(new Dimension(1280, 800)); - int maxWidth = screen.width * 85 / 100; - int maxHeight = screen.height * 75 / 100; - int width = picture.getWidth(); - int height = picture.getHeight(); - double scale = Math.min(1, Math.min(maxWidth / (double) width, maxHeight / (double) height)); - if (scale >= 1) return picture; - return picture.getScaledInstance(Math.max(1, (int) (width * scale)), Math.max(1, (int) (height * scale)), - Image.SCALE_SMOOTH); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/PlaybackPanel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/PlaybackPanel.java deleted file mode 100644 index a27914b..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/PlaybackPanel.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.audio.AudioDevice; -import com.ts3client.audio.AudioIo; -import com.ts3client.audio.VoiceOutput; -import com.ts3client.config.Settings; -import com.ts3client.sound.SoundEvent; -import com.ts3client.sound.SoundNotifier; - -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSlider; -import java.awt.FlowLayout; -import java.awt.GridBagConstraints; -import java.util.function.Consumer; - -/** - * Options page for the playback device and voice volume. The volume previews live on the - * visible connection; a device change is handed to the microphone test's loopback. - */ -final class PlaybackPanel extends FormPanel { - - private final JComboBox outputCombo; - private final JSlider outputVol; - - PlaybackPanel(Settings settings, AudioIo io, VoiceOutput livePlayback, SoundNotifier sounds, - Consumer onOutputDeviceChanged) { - GridBagConstraints c = gbc(); - - outputCombo = AudioDevices.combo(io.outputDevices(), settings.outputDevice); - limitWidth(outputCombo, FIELD_WIDTH); - outputCombo.addActionListener(e -> onOutputDeviceChanged.accept(AudioDevices.selectedId(outputCombo))); - - outputVol = new JSlider(0, 200, (int) Math.round(settings.outputVolume * 100)); - JLabel volumeLabel = new JLabel(outputVol.getValue() + "%"); - outputVol.addChangeListener(e -> { - volumeLabel.setText(outputVol.getValue() + "%"); - if (livePlayback != null) livePlayback.setMasterVolume(outputVol.getValue() / 100.0); - }); - - JButton testSound = new JButton("Play Test Sound"); - testSound.addActionListener(e -> sounds.preview(SoundEvent.SPECIAL_SOUND_TEST)); - JPanel testRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); - testRow.add(testSound); - - int row = 0; - addSection(this, c, row++, "Device"); - addRow(this, c, row++, new JLabel("Playback device:"), outputCombo); - addSection(this, c, row++, "Volume"); - addRow(this, c, row++, new JLabel("Voice volume:"), sliderWithLabel(outputVol, volumeLabel)); - addWide(this, c, row++, testRow); - addFiller(this, c, row); - } - - /** Copies the form into {@code target}, without touching anything else. */ - void writeInto(Settings target) { - target.outputDevice = AudioDevices.selectedId(outputCombo); - target.outputVolume = outputVol.getValue() / 100.0; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/PrivilegeKeyCreateDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/PrivilegeKeyCreateDialog.java deleted file mode 100644 index 1d9c00e..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/PrivilegeKeyCreateDialog.java +++ /dev/null @@ -1,168 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.net.ChannelNode; -import com.ts3client.net.Group; -import com.ts3client.net.ServerModel; -import com.ts3client.net.TeamspeakConnection; - -import javax.swing.Box; -import javax.swing.ButtonGroup; -import javax.swing.DefaultListCellRenderer; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JTextField; -import javax.swing.SwingUtilities; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.FlowLayout; -import java.awt.GridBagConstraints; -import java.awt.Toolkit; -import java.awt.Window; -import java.awt.datatransfer.StringSelection; - -/** - * Creates privilege keys, as the official client's "Create Privilege Key" dialog: a server - * group, or a channel group in a chosen channel, and an optional description. Each key - * created is shown for copying, and the dialog stays open for the next one. - */ -final class PrivilegeKeyCreateDialog extends JDialog { - - private final TeamspeakConnection conn; - private final Runnable onCreated; - - private final JRadioButton serverGroup = new JRadioButton("Server Group", true); - private final JRadioButton channelGroup = new JRadioButton("Channel Group"); - private final JComboBox groupBox = new JComboBox<>(); - private final JComboBox channelBox = new JComboBox<>(); - private final JTextField descriptionField = new JTextField(28); - private final JTextField keyField = new JTextField(28); - private final JButton copy = new JButton("Copy", Icons.of("COPY")); - private final JButton create = new JButton("Create"); - - /** @param onCreated runs on the UI thread after each key is created */ - PrivilegeKeyCreateDialog(Window owner, TeamspeakConnection conn, GroupIcons groupIcons, Runnable onCreated) { - super(owner, "Create Privilege Key", ModalityType.APPLICATION_MODAL); - this.conn = conn; - this.onCreated = onCreated; - - ButtonGroup type = new ButtonGroup(); - type.add(serverGroup); - type.add(channelGroup); - serverGroup.addActionListener(e -> typeChanged()); - channelGroup.addActionListener(e -> typeChanged()); - JPanel typeRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); - typeRow.add(serverGroup); - typeRow.add(Box.createHorizontalStrut(UIScale.scale(12))); - typeRow.add(channelGroup); - - groupBox.setRenderer(new DefaultListCellRenderer() { - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, - boolean selected, boolean focused) { - super.getListCellRendererComponent(list, value, index, selected, focused); - if (value instanceof Group g) { - setText(g.name); - setIcon(groupIcons.iconOf(g)); - } - return this; - } - }); - groupBox.addActionListener(e -> updateCreate()); - ServerModel model = conn.getModel(); - channelBox.setRenderer(new DefaultListCellRenderer() { - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, - boolean selected, boolean focused) { - super.getListCellRendererComponent(list, value, index, selected, focused); - if (value instanceof ChannelNode c) setText(model.channelPath(c.id)); - return this; - } - }); - for (ChannelNode c : model.channelsInTreeOrder()) channelBox.addItem(c); - channelBox.setToolTipText("When creating a privilege key for a channel group, specify the channel here"); - descriptionField.setToolTipText("Optional description for this privilege key"); - descriptionField.addActionListener(e -> create()); - - keyField.setEditable(false); - copy.setEnabled(false); - copy.addActionListener(e -> Toolkit.getDefaultToolkit().getSystemClipboard() - .setContents(new StringSelection(keyField.getText()), null)); - JPanel keyRow = new JPanel(new BorderLayout(4, 0)); - keyRow.add(keyField, BorderLayout.CENTER); - keyRow.add(copy, BorderLayout.EAST); - - FormPanel form = new FormPanel(); - GridBagConstraints c = FormPanel.gbc(); - FormPanel.addRow(form, c, 0, new JLabel("Group Type:"), typeRow); - FormPanel.addRow(form, c, 1, new JLabel("Group:"), groupBox); - FormPanel.addRow(form, c, 2, new JLabel("Channel:"), channelBox); - FormPanel.addRow(form, c, 3, new JLabel("Description:"), descriptionField); - FormPanel.addRow(form, c, 4, new JLabel("Privilege Key:"), keyRow); - - create.addActionListener(e -> create()); - JButton close = new JButton("Close"); - close.addActionListener(e -> dispose()); - JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT)); - buttons.setBorder(new ScaledEmptyBorder(0, 8, 4, 8)); - buttons.add(create); - buttons.add(close); - getRootPane().setDefaultButton(create); - - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(form, BorderLayout.CENTER); - getContentPane().add(buttons, BorderLayout.SOUTH); - - typeChanged(); - Dialogs.closeOnEscape(this); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - pack(); - setResizable(false); - setLocationRelativeTo(owner); - } - - private boolean forChannelGroup() { - return channelGroup.isSelected(); - } - - private void typeChanged() { - groupBox.removeAllItems(); - for (Group g : conn.getModel().privilegeKeyGroups(forChannelGroup())) groupBox.addItem(g); - channelBox.setEnabled(forChannelGroup()); - updateCreate(); - } - - private void updateCreate() { - create.setEnabled(groupBox.getSelectedItem() != null - && (!forChannelGroup() || channelBox.getSelectedItem() != null)); - } - - private void create() { - if (!create.isEnabled()) return; - Group group = (Group) groupBox.getSelectedItem(); - ChannelNode channel = (ChannelNode) channelBox.getSelectedItem(); - create.setEnabled(false); - conn.addPrivilegeKey(forChannelGroup(), group.id, channel == null ? 0 : channel.id, - descriptionField.getText().trim(), (key, error) -> SwingUtilities.invokeLater(() -> { - if (!isDisplayable()) return; - updateCreate(); - if (error != null) { - JOptionPane.showMessageDialog(this, "Failed to add Privilege Key: " + error, - getTitle(), JOptionPane.ERROR_MESSAGE); - return; - } - keyField.setText(key); - keyField.selectAll(); - keyField.requestFocusInWindow(); - copy.setEnabled(true); - onCreated.run(); - })); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/PrivilegeKeysDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/PrivilegeKeysDialog.java deleted file mode 100644 index a217cf6..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/PrivilegeKeysDialog.java +++ /dev/null @@ -1,355 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.net.Group; -import com.ts3client.net.PrivilegeKey; -import com.ts3client.net.ServerModel; -import com.ts3client.net.TeamspeakConnection; - -import javax.swing.AbstractAction; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.KeyStroke; -import javax.swing.ListSelectionModel; -import javax.swing.SwingUtilities; -import javax.swing.table.AbstractTableModel; -import javax.swing.table.DefaultTableCellRenderer; -import javax.swing.table.TableRowSorter; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Frame; -import java.awt.Toolkit; -import java.awt.datatransfer.StringSelection; -import java.awt.event.ActionEvent; -import java.awt.event.KeyEvent; -import java.time.Instant; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -/** - * The server's privilege keys, as the official client's Permissions > Privilege Keys - * window: Create and Remove above the list, Reload below it. - * - *

    One per server tab and modeless, like the ban list; the tab closes it when the - * connection goes away. - */ -final class PrivilegeKeysDialog extends JDialog { - - private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - - private enum Column { - KEY("Privilege Key", 320), - TYPE("Type", 110), - GROUP("Group", 140), - CHANNEL("Channel", 140), - CREATED("Created", 150), - DESCRIPTION("Description", 180); - - final String title; - final int width; - - Column(String title, int width) { - this.title = title; - this.width = width; - } - } - - private final TeamspeakConnection conn; - private final GroupIcons groupIcons; - - private final KeyTableModel tableModel = new KeyTableModel(); - private final JTable table = new JTable(tableModel); - private final JButton createButton = new JButton("Create", Icons.of("ADD")); - private final JButton removeButton = new JButton("Remove", Icons.of("DELETE")); - private final JLabel status = new JLabel(" "); - - private boolean loading; - - PrivilegeKeysDialog(Frame owner, TeamspeakConnection conn, GroupIcons groupIcons) { - super(owner, "Privilege Keys", false); - this.conn = conn; - this.groupIcons = groupIcons; - - JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(6))); - content.setBackground(Theme.windowBg()); - content.setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); - content.add(buildToolbar(), BorderLayout.NORTH); - content.add(buildTable(), BorderLayout.CENTER); - content.add(buildBottom(), BorderLayout.SOUTH); - setContentPane(content); - bindKeys(); - - serverNameChanged(); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - setPreferredSize(UIScale.scale(new Dimension(1040, 400))); - pack(); - setLocationRelativeTo(owner); - reload(); - } - - // ---- construction ---- - - private JPanel buildToolbar() { - createButton.setToolTipText("Create new privilege key
    (Ctrl+N)"); - removeButton.setToolTipText("Remove selected privilege keys
    (Delete)"); - createButton.addActionListener(e -> createKey()); - removeButton.addActionListener(e -> removeKeys()); - - JPanel bar = new JPanel(); - bar.setLayout(new BoxLayout(bar, BoxLayout.X_AXIS)); - bar.setOpaque(false); - bar.add(createButton); - bar.add(Box.createHorizontalStrut(UIScale.scale(6))); - bar.add(removeButton); - bar.add(Box.createHorizontalGlue()); - return bar; - } - - private JScrollPane buildTable() { - table.setFont(Theme.uiFont()); - table.setRowHeight(UIScale.scale(20)); - table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - table.setFillsViewportHeight(true); - table.setRowSorter(new TableRowSorter<>(tableModel)); - table.getSelectionModel().addListSelectionListener(e -> updateButtons()); - table.setComponentPopupMenu(tablePopup()); - table.getTableHeader().setReorderingAllowed(true); - KeyCellRenderer renderer = new KeyCellRenderer(); - for (Column c : Column.values()) { - table.getColumnModel().getColumn(c.ordinal()).setPreferredWidth(UIScale.scale(c.width)); - table.getColumnModel().getColumn(c.ordinal()).setCellRenderer(renderer); - } - - JScrollPane scroll = new JScrollPane(table); - scroll.getViewport().setBackground(Theme.treeBg()); - return scroll; - } - - private JPanel buildBottom() { - JButton reload = new JButton("Reload", Icons.of("REFRESH")); - reload.setToolTipText("Reload privilege keys
    (F5)"); - reload.addActionListener(e -> reload()); - JButton close = new JButton("Close"); - close.addActionListener(e -> dispose()); - - JPanel row = new JPanel(new BorderLayout()); - row.setOpaque(false); - row.add(reload, BorderLayout.WEST); - row.add(close, BorderLayout.EAST); - - JPanel bottom = new JPanel(new BorderLayout(0, UIScale.scale(8))); - bottom.setOpaque(false); - bottom.add(status, BorderLayout.NORTH); - bottom.add(row, BorderLayout.SOUTH); - status.setForeground(Theme.chatEvent()); - return bottom; - } - - private JPopupMenu tablePopup() { - JPopupMenu menu = new JPopupMenu(); - menu.add(item("Create", "ADD", this::createKey)); - menu.add(item("Remove", "DELETE", this::removeKeys)); - menu.add(item("Copy", "COPY", this::copyKeys)); - menu.addSeparator(); - menu.add(item("Reload", "REFRESH", this::reload)); - return menu; - } - - private static JMenuItem item(String text, String icon, Runnable action) { - JMenuItem item = new JMenuItem(text, Icons.of(icon)); - item.addActionListener(e -> action.run()); - return item; - } - - private void bindKeys() { - bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control N"), this::createKey); - bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("F5"), this::reload); - bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control W"), this::dispose); - bind(table, JComponent.WHEN_FOCUSED, KeyStroke.getKeyStroke("control C"), this::copyKeys); - bind(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), - this::removeKeys); - Dialogs.closeOnEscape(this); - } - - private static void bind(JComponent target, int condition, KeyStroke key, Runnable action) { - String name = "ts3-privilegekeys-" + key; - target.getInputMap(condition).put(key, name); - target.getActionMap().put(name, new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - action.run(); - } - }); - } - - // ---- data ---- - - /** Follows the server's name, as the ban list's title does. */ - void serverNameChanged() { - String name = conn.getModel().getServerName(); - setTitle(name == null || name.isBlank() ? "Privilege Keys" : "Privilege Keys - " + name); - } - - void connectionLost() { - dispose(); - } - - private void reload() { - if (loading) return; - loading = true; - status.setText("Loading…"); - conn.requestPrivilegeKeys((keys, error) -> SwingUtilities.invokeLater(() -> { - loading = false; - if (!isDisplayable()) return; - if (error != null) { - tableModel.setKeys(List.of()); - status.setText("Failed to request Privilege Key list: " + error); - } else { - tableModel.setKeys(keys); - status.setText(keys.size() == 1 ? "1 privilege key" : keys.size() + " privilege keys"); - } - updateButtons(); - })); - } - - private List selectedKeys() { - List selected = new ArrayList<>(); - for (int row : table.getSelectedRows()) selected.add(tableModel.get(table.convertRowIndexToModel(row))); - return selected; - } - - private void updateButtons() { - ServerModel model = conn.getModel(); - createButton.setEnabled(model.permits("b_virtualserver_token_add")); - removeButton.setEnabled(!selectedKeys().isEmpty() && model.permits("b_virtualserver_token_delete")); - } - - // ---- actions ---- - - private void createKey() { - if (!createButton.isEnabled()) return; - new PrivilegeKeyCreateDialog(this, conn, groupIcons, this::reload).setVisible(true); - } - - private void removeKeys() { - if (!removeButton.isEnabled()) return; - int answer = JOptionPane.showConfirmDialog(this, "Do you really want to delete the selected privilege key(s)?", - "Delete Privilege Keys", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); - if (answer != JOptionPane.YES_OPTION) return; - List tokens = selectedKeys().stream().map(PrivilegeKey::token).collect(Collectors.toList()); - conn.deletePrivilegeKeys(tokens, error -> SwingUtilities.invokeLater(() -> { - if (!isDisplayable()) return; - if (error != null) { - JOptionPane.showMessageDialog(this, "Failed to delete Privilege Key: " + error, getTitle(), - JOptionPane.ERROR_MESSAGE); - } - reload(); - })); - } - - private void copyKeys() { - List keys = selectedKeys(); - if (keys.isEmpty()) return; - String text = keys.stream().map(PrivilegeKey::token).collect(Collectors.joining("\n")); - Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(text), null); - } - - // ---- table ---- - - private Group groupOf(PrivilegeKey key) { - ServerModel model = conn.getModel(); - return key.channelGroup() ? model.channelGroup(key.groupId()) : model.serverGroup(key.groupId()); - } - - private final class KeyTableModel extends AbstractTableModel { - - private List keys = List.of(); - - void setKeys(List keys) { - this.keys = new ArrayList<>(keys); - fireTableDataChanged(); - } - - PrivilegeKey get(int row) { - return keys.get(row); - } - - @Override - public int getRowCount() { - return keys.size(); - } - - @Override - public int getColumnCount() { - return Column.values().length; - } - - @Override - public String getColumnName(int column) { - return Column.values()[column].title; - } - - @Override - public Class getColumnClass(int column) { - return Column.values()[column] == Column.CREATED ? Long.class : String.class; - } - - @Override - public Object getValueAt(int row, int column) { - PrivilegeKey key = keys.get(row); - if (Column.values()[column] == Column.CREATED) return key.createdEpochSeconds(); - return text(key, Column.values()[column]); - } - - String text(PrivilegeKey key, Column column) { - switch (column) { - case KEY: - return key.token(); - case TYPE: - return key.channelGroup() ? "Channel Group" : "Server Group"; - case GROUP: - Group group = groupOf(key); - return group != null ? group.name : Integer.toString(key.groupId()); - case CHANNEL: - if (!key.channelGroup()) return ""; - String path = conn.getModel().channelPath(key.channelId()); - return path.isEmpty() ? Integer.toString(key.channelId()) : path; - case CREATED: - return key.createdEpochSeconds() <= 0 ? "" : DATE.format( - Instant.ofEpochSecond(key.createdEpochSeconds()).atZone(ZoneId.systemDefault())); - case DESCRIPTION: - return key.description(); - default: - return ""; - } - } - } - - /** Shows each column's text, with the group's icon beside its name. */ - private final class KeyCellRenderer extends DefaultTableCellRenderer { - @Override - public Component getTableCellRendererComponent(JTable t, Object value, boolean selected, - boolean focused, int row, int column) { - PrivilegeKey key = tableModel.get(t.convertRowIndexToModel(row)); - Column c = Column.values()[t.convertColumnIndexToModel(column)]; - super.getTableCellRendererComponent(t, tableModel.text(key, c), selected, focused, row, column); - setIcon(c == Column.GROUP ? groupIcons.iconOf(groupOf(key)) : null); - return this; - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ReasonDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ReasonDialog.java deleted file mode 100644 index 9ccfda5..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ReasonDialog.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; - -import javax.swing.BoxLayout; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.event.AncestorEvent; -import javax.swing.event.AncestorListener; -import javax.swing.text.AttributeSet; -import javax.swing.text.BadLocationException; -import javax.swing.text.PlainDocument; -import java.awt.Component; -import java.awt.Dimension; - -/** - * Asks for the reason text that goes with a moderation action. The server caps - * such messages, so the field refuses anything longer. - */ -final class ReasonDialog { - - private ReasonDialog() { - } - - /** @return the reason (possibly empty), or {@code null} when the dialog was cancelled */ - static String prompt(Component owner, String title, String message, int maxLength) { - JTextField field = reasonField(maxLength); - focusWhenShown(field); - - JPanel panel = new JPanel(); - panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); - panel.add(label(message)); - panel.add(field); - - int result = JOptionPane.showConfirmDialog(owner, panel, title, - JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); - return result == JOptionPane.OK_OPTION ? field.getText().trim() : null; - } - - static JTextField reasonField(int maxLength) { - JTextField field = new JTextField(24); - field.setDocument(new LimitedDocument(maxLength)); - field.setAlignmentX(Component.LEFT_ALIGNMENT); - fixHeight(field); - return field; - } - - /** A left-aligned label with a little air below it, for use in a box layout. */ - static JLabel label(String text) { - JLabel label = new JLabel(text); - label.setAlignmentX(Component.LEFT_ALIGNMENT); - label.setBorder(new ScaledEmptyBorder(0, 0, 4, 0)); - return label; - } - - /** Keeps a component from stretching taller than it needs in a box layout. */ - static void fixHeight(Component c) { - c.setMaximumSize(new Dimension(Integer.MAX_VALUE, c.getPreferredSize().height)); - } - - /** Puts the caret in a field as soon as its dialog appears. */ - static void focusWhenShown(JComponent field) { - field.addAncestorListener(new AncestorListener() { - @Override - public void ancestorAdded(AncestorEvent event) { - field.requestFocusInWindow(); - } - - @Override - public void ancestorRemoved(AncestorEvent event) { - } - - @Override - public void ancestorMoved(AncestorEvent event) { - } - }); - } - - /** A document that silently drops anything past its length limit. */ - private static final class LimitedDocument extends PlainDocument { - - private final int limit; - - LimitedDocument(int limit) { - this.limit = limit; - } - - @Override - public void insertString(int offset, String text, AttributeSet attrs) throws BadLocationException { - if (text == null) return; - int room = limit - getLength(); - if (room <= 0) return; - super.insertString(offset, text.length() > room ? text.substring(0, room) : text, attrs); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/RecordingActions.java b/ts3-client/swing/src/main/java/com/ts3client/ui/RecordingActions.java deleted file mode 100644 index 638b8e0..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/RecordingActions.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.config.Settings; -import com.ts3client.recording.VoiceRecorder; -import com.ts3client.session.ServerSession; - -import javax.swing.JFileChooser; -import javax.swing.filechooser.FileNameExtensionFilter; -import java.awt.Component; -import java.io.File; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - -/** Starts recordings, into a file the user picks or, from a hotkey, the folder last used. */ -final class RecordingActions { - - private final Component owner; - private final Settings settings; - - RecordingActions(Component owner, Settings settings) { - this.owner = owner; - this.settings = settings; - } - - /** Asks where to save, then starts recording. */ - void choose(ServerSession session, boolean multitrack) { - if (!session.isConnected() || session.isRecording()) return; - Path dir = settings.recordingFolder(); - if (!Files.isDirectory(dir)) dir = Paths.get(System.getProperty("user.home", ".")); - JFileChooser chooser = new JFileChooser(dir.toFile()); - chooser.setDialogTitle(multitrack ? "Start Multitrack Recording" : "Start Recording"); - chooser.setFileFilter(new FileNameExtensionFilter("Ogg Opus (*.ogg)", "ogg")); - chooser.setSelectedFile(session.recordingFile(dir).toFile()); - if (chooser.showSaveDialog(owner) != JFileChooser.APPROVE_OPTION) return; - File file = chooser.getSelectedFile(); - if (!file.getName().toLowerCase().endsWith(".ogg")) file = new File(file.getParentFile(), file.getName() + ".ogg"); - settings.recordingDir = file.getParentFile().getAbsolutePath(); - settings.save(); - session.startRecording(mode(multitrack), file.toPath()); - } - - void startNow(ServerSession session, boolean multitrack) { - if (!session.isConnected() || session.isRecording()) return; - session.startRecording(mode(multitrack), session.recordingFile(settings.recordingFolder())); - } - - private static VoiceRecorder.Mode mode(boolean multitrack) { - return multitrack ? VoiceRecorder.Mode.MULTITRACK : VoiceRecorder.Mode.MIXED; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/RowColorCombo.java b/ts3-client/swing/src/main/java/com/ts3client/ui/RowColorCombo.java deleted file mode 100644 index 8c99807..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/RowColorCombo.java +++ /dev/null @@ -1,123 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.config.ClientRowColors; - -import javax.swing.DefaultListCellRenderer; -import javax.swing.Icon; -import javax.swing.JColorChooser; -import javax.swing.JComboBox; -import javax.swing.JList; -import javax.swing.UIManager; -import java.awt.Color; -import java.awt.Component; -import java.awt.Graphics; - -/** - * Picks a row background: none, one of {@link ClientRowColors#PRESETS}, or a custom - * colour from a colour chooser. The value is ARGB, 0 for none. - */ -final class RowColorCombo extends JComboBox { - - record Option(String name, int argb, boolean custom) { - } - - private static final Option NONE = new Option("None", 0, false); - - /** The last item, holding whichever custom colour was chosen. */ - private Option custom; - private Option previous; - private boolean choosing; - - RowColorCombo(int argb) { - addItem(NONE); - for (ClientRowColors.Preset p : ClientRowColors.PRESETS) addItem(new Option(p.name(), p.argb(), false)); - boolean isCustom = argb != 0 && ClientRowColors.presetOf(argb) == null; - custom = new Option("Custom…", isCustom ? argb : 0, true); - addItem(custom); - setValue(argb); - previous = (Option) getSelectedItem(); - - setMaximumRowCount(getItemCount()); - setRenderer(new DefaultListCellRenderer() { - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, - boolean selected, boolean focus) { - super.getListCellRendererComponent(list, value, index, selected, focus); - Option o = (Option) value; - setText(o == null ? "" : o.name()); - setIcon(o == null ? null : new Swatch(o.argb())); - return this; - } - }); - addActionListener(e -> onSelected()); - } - - int value() { - Option o = (Option) getSelectedItem(); - return o == null ? 0 : o.argb(); - } - - private void setValue(int argb) { - for (int i = 0; i < getItemCount(); i++) { - Option o = getItemAt(i); - if (o.argb() == argb && (argb != 0 || o == NONE)) { - setSelectedIndex(i); - return; - } - } - setSelectedItem(NONE); - } - - private void onSelected() { - Option o = (Option) getSelectedItem(); - if (o == null || choosing) return; - if (!o.custom()) { - previous = o; - return; - } - choosing = true; - try { - int start = custom.argb() != 0 ? custom.argb() : previous.argb() != 0 ? previous.argb() : 0x59808080; - Color picked = JColorChooser.showDialog(this, "Row Colour", new Color(start, true), true); - if (picked == null || picked.getRGB() == 0) { - setSelectedItem(previous); - return; - } - Option chosen = new Option("Custom…", picked.getRGB(), true); - removeItem(custom); - custom = chosen; - addItem(custom); - setSelectedItem(custom); - previous = custom; - } finally { - choosing = false; - } - } - - /** A small square of the colour over the tree's background, as a row shows it. */ - private record Swatch(int argb) implements Icon { - @Override - public void paintIcon(Component c, Graphics g, int x, int y) { - int size = getIconWidth(); - g.setColor(UIManager.getColor("Tree.background")); - g.fillRect(x, y, size, size); - if (argb != 0) { - g.setColor(new Color(argb, true)); - g.fillRect(x, y, size, size); - } - g.setColor(UIManager.getColor("Component.borderColor")); - g.drawRect(x, y, size - 1, size - 1); - } - - @Override - public int getIconWidth() { - return UIScale.scale(14); - } - - @Override - public int getIconHeight() { - return getIconWidth(); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerGroupsDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerGroupsDialog.java deleted file mode 100644 index 1d68c05..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerGroupsDialog.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.net.ClientEntry; -import com.ts3client.net.Group; -import com.ts3client.net.GroupChoice; -import com.ts3client.net.TeamspeakConnection; - -import javax.swing.BoxLayout; -import javax.swing.GrayFilter; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.SwingConstants; -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.util.HashMap; -import java.util.Map; - -/** - * Every regular server group on the server, as a scrollable checkbox list. Groups - * the local client has no power to (un)assign are shown too, so the client's full - * membership is visible, but greyed out and disabled. - */ -final class ServerGroupsDialog extends JDialog { - - private final TeamspeakConnection conn; - private final GroupIcons groupIcons; - private final int clientId; - private final ServerTreePanel.Actions actions; - - private final JPanel list = new JPanel(); - private final JLabel header = new JLabel(); - /** Cached grayscale icons, keyed by the source icon's identity. */ - private final Map grayscale = new HashMap<>(); - - ServerGroupsDialog(MainFrame owner, TeamspeakConnection conn, GroupIcons groupIcons, - ClientEntry client, ServerTreePanel.Actions actions) { - super(owner, "Server Groups", true); - this.conn = conn; - this.groupIcons = groupIcons; - this.clientId = client.id; - this.actions = actions; - - list.setLayout(new BoxLayout(list, BoxLayout.Y_AXIS)); - JScrollPane scroll = new JScrollPane(list); - scroll.setPreferredSize(UIScale.scale(new Dimension(280, 360))); - scroll.getVerticalScrollBar().setUnitIncrement(16); - - header.setBorder(new ScaledEmptyBorder(8, 10, 4, 10)); - header.setHorizontalAlignment(SwingConstants.LEFT); - - JButton close = new JButton("Close"); - close.addActionListener(a -> dispose()); - JPanel buttons = new JPanel(); - buttons.add(close); - getRootPane().setDefaultButton(close); - - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(header, BorderLayout.NORTH); - getContentPane().add(scroll, BorderLayout.CENTER); - getContentPane().add(buttons, BorderLayout.SOUTH); - - Dialogs.closeOnEscape(this); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - refresh(); - pack(); - setLocationRelativeTo(owner); - } - - /** Rebuilds the list from the current model state; closes the dialog if the client left. */ - void refresh() { - ClientEntry client = conn.getModel().getClient(clientId); - if (client == null) { - dispose(); - return; - } - header.setText(client.nickname); - - list.removeAll(); - for (GroupChoice choice : conn.getModel().serverGroupChoices(client)) { - Group g = choice.group(); - ImageIcon icon = groupIcons.iconOf(g); - JCheckBox box = new JCheckBox(g.name, choice.allowed() ? icon : grayscale(icon)); - box.setSelected(choice.assigned()); - box.setEnabled(choice.allowed()); - box.setAlignmentX(0f); - if (choice.allowed()) { - box.addActionListener(a -> actions.setClientServerGroup(client, g, box.isSelected())); - } - list.add(box); - } - list.revalidate(); - list.repaint(); - } - - private ImageIcon grayscale(ImageIcon icon) { - if (icon == null) return null; - return grayscale.computeIfAbsent(icon, - i -> new ImageIcon(GrayFilter.createDisabledImage(i.getImage()))); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogDialog.java deleted file mode 100644 index c887f15..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogDialog.java +++ /dev/null @@ -1,364 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.config.ServerLogSettings; -import com.ts3client.config.ServerLogSettings.Highlight; -import com.ts3client.config.Settings; -import com.ts3client.net.ServerLogEntry; -import com.ts3client.net.ServerLogEntry.Level; -import com.ts3client.net.ServerLogPage; -import com.ts3client.net.TeamspeakConnection; -import com.ts3client.text.TextQuery; - -import javax.swing.AbstractAction; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JEditorPane; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextPane; -import javax.swing.KeyStroke; -import javax.swing.SwingUtilities; -import javax.swing.text.BadLocationException; -import javax.swing.text.DefaultStyledDocument; -import javax.swing.text.SimpleAttributeSet; -import javax.swing.text.StyleConstants; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Frame; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.KeyEvent; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -/** - * The virtual server's log, as the official client's Tools > Server Log window: the newest - * hundred lines, more on Show Older, narrowed down by level and exclude terms and coloured - * by keyword. Find (with "show only matches") stands in for TS3's separate search and - * include-filter fields. - * - *

    One per server tab and modeless, like the ban list; the tab closes it when the - * connection goes away. - */ -final class ServerLogDialog extends JDialog { - - private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - private static final String TITLE = "Server Log"; - private static final int LEVEL_WIDTH = "Critical".length(); - - private final TeamspeakConnection conn; - private final Settings settings; - private final ServerLogSettings view; - - private final JTextPane log = new JTextPane() { - /** Long lines scroll sideways rather than wrap, keeping the columns lined up. */ - @Override - public boolean getScrollableTracksViewportWidth() { - return getParent() == null || getUI().getPreferredSize(this).width <= getParent().getWidth(); - } - }; - private final DefaultStyledDocument doc = new DefaultStyledDocument(); - private final ChatSearch search = new ChatSearch(new ChatSearch.Host() { - @Override - public JEditorPane selectedLog() { - return log; - } - - @Override - public void showMatching(TextQuery filter) { - onlyMatching = filter; - render(false); - } - }, "Show only matching lines"); - private final Map levelBoxes = new EnumMap<>(Level.class); - private final JComboBox timeZone = new JComboBox<>(new String[]{"UTC time", "Local time"}); - private final JButton olderButton = new JButton("Show Older"); - /** Loading, failures and an empty log; hidden otherwise. */ - private final JLabel status = new JLabel(); - - /** Everything read so far, oldest first. */ - private final List entries = new ArrayList<>(); - private long olderFrom; - private TextQuery onlyMatching; - private boolean loading; - - ServerLogDialog(Frame owner, TeamspeakConnection conn, Settings settings) { - super(owner, TITLE, false); - this.conn = conn; - this.settings = settings; - this.view = settings.serverLog; - - JPanel center = new JPanel(new BorderLayout()); - center.setOpaque(false); - center.add(buildLog(), BorderLayout.CENTER); - center.add(search.bar(), BorderLayout.SOUTH); - - JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(6))); - content.setBackground(Theme.windowBg()); - content.setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); - content.add(buildToolbar(), BorderLayout.NORTH); - content.add(center, BorderLayout.CENTER); - content.add(buildBottom(), BorderLayout.SOUTH); - setContentPane(content); - bindKeys(); - - serverNameChanged(); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - setPreferredSize(UIScale.scale(new Dimension(900, 520))); - pack(); - setLocationRelativeTo(owner); - search.open(); - reload(); - } - - // ---- construction ---- - - private JPanel buildToolbar() { - JPanel bar = new JPanel(); - bar.setLayout(new BoxLayout(bar, BoxLayout.X_AXIS)); - bar.setOpaque(false); - String[] labels = {"Critical", "Errors", "Warnings", "Info"}; - int[] mnemonics = {KeyEvent.VK_C, KeyEvent.VK_E, KeyEvent.VK_W, KeyEvent.VK_I}; - for (int i = 0; i < ServerLogSettings.SHOWN_LEVELS.size(); i++) { - Level level = ServerLogSettings.SHOWN_LEVELS.get(i); - JCheckBox box = new JCheckBox(labels[i], view.levels.contains(level)); - box.setMnemonic(mnemonics[i]); - box.setOpaque(false); - box.addActionListener(e -> { - if (box.isSelected()) view.levels.add(level); - else view.levels.remove(level); - settingsChanged(); - }); - levelBoxes.put(level, box); - bar.add(box); - bar.add(Box.createHorizontalStrut(UIScale.scale(6))); - } - bar.add(Box.createHorizontalStrut(UIScale.scale(12))); - - JButton highlighting = new JButton("Highlighting…"); - highlighting.setMnemonic(KeyEvent.VK_H); - highlighting.addActionListener(e -> { - if (ServerLogHighlightDialog.edit(this, view.highlights)) settingsChanged(); - }); - JButton exclude = new JButton("Exclude Filter…"); - exclude.setMnemonic(KeyEvent.VK_X); - exclude.addActionListener(e -> { - if (ServerLogExcludeDialog.edit(this, view.excludes)) settingsChanged(); - }); - bar.add(highlighting); - bar.add(Box.createHorizontalStrut(UIScale.scale(6))); - bar.add(exclude); - bar.add(Box.createHorizontalGlue()); - - timeZone.setSelectedIndex(view.localTime ? 1 : 0); - timeZone.setMaximumSize(timeZone.getPreferredSize()); - timeZone.addActionListener(e -> { - view.localTime = timeZone.getSelectedIndex() == 1; - settingsChanged(); - }); - bar.add(timeZone); - return bar; - } - - private JScrollPane buildLog() { - log.setEditable(false); - log.setDocument(doc); - log.setFont(new Font(Font.MONOSPACED, Font.PLAIN, UIScale.scale(12))); - log.setBackground(Theme.chatBg()); - log.setForeground(Theme.chatText()); - log.setBorder(new ScaledEmptyBorder(4, 6, 4, 6)); - JScrollPane scroll = new JScrollPane(log); - scroll.getViewport().setBackground(Theme.chatBg()); - return scroll; - } - - private JPanel buildBottom() { - JButton reload = new JButton("Reload", Icons.of("REFRESH")); - reload.setMnemonic(KeyEvent.VK_R); - reload.setToolTipText("Reload the newest lines
    (F5)"); - reload.addActionListener(e -> reload()); - olderButton.setMnemonic(KeyEvent.VK_O); - olderButton.setEnabled(false); - olderButton.addActionListener(e -> loadOlder()); - JButton close = new JButton("Close"); - close.addActionListener(e -> dispose()); - - JPanel left = new JPanel(); - left.setLayout(new BoxLayout(left, BoxLayout.X_AXIS)); - left.setOpaque(false); - left.add(reload); - left.add(Box.createHorizontalStrut(UIScale.scale(6))); - left.add(olderButton); - - JPanel row = new JPanel(new BorderLayout()); - row.setOpaque(false); - row.add(left, BorderLayout.WEST); - row.add(close, BorderLayout.EAST); - - JPanel bottom = new JPanel(new BorderLayout(0, UIScale.scale(8))); - bottom.setOpaque(false); - bottom.add(status, BorderLayout.NORTH); - bottom.add(row, BorderLayout.SOUTH); - status.setVisible(false); - return bottom; - } - - private void bindKeys() { - bind(KeyStroke.getKeyStroke("F5"), this::reload); - bind(KeyStroke.getKeyStroke("control W"), this::dispose); - bind(KeyStroke.getKeyStroke("control F"), search::open); - Dialogs.closeOnEscape(this); - } - - private void bind(KeyStroke key, Runnable action) { - String name = "ts3-serverlog-" + key; - getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(key, name); - getRootPane().getActionMap().put(name, new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - action.run(); - } - }); - } - - // ---- data ---- - - void serverNameChanged() { - String name = conn.getModel().getServerName(); - setTitle(name == null || name.isBlank() ? TITLE : TITLE + " - " + name); - } - - void connectionLost() { - dispose(); - } - - private void reload() { - request(0); - } - - private void loadOlder() { - if (olderFrom > 0) request(olderFrom); - } - - /** Reads the newest page ({@code from} 0, replacing what is shown) or the one ending at {@code from}. */ - private void request(long from) { - if (loading) return; - loading = true; - olderButton.setEnabled(false); - showStatus("Loading…", Theme.chatEvent()); - conn.requestServerLog(from, (page, error) -> SwingUtilities.invokeLater(() -> { - loading = false; - if (!isDisplayable()) return; - if (error != null) { - failed(error); - olderButton.setEnabled(olderFrom > 0); - return; - } - received(page, from > 0); - })); - } - - private void received(ServerLogPage page, boolean older) { - if (!older) entries.clear(); - entries.addAll(0, page.entries()); - olderFrom = page.olderFrom(); - olderButton.setEnabled(page.hasOlder()); - render(!older); - if (older) log.setCaretPosition(0); - } - - private void failed(String error) { - showStatus(error.toLowerCase(Locale.ROOT).contains("insufficient") - ? "Insufficient permissions to view Server Log" - : "Error requesting server log: " + error, - Theme.isDark() ? new Color(0xFF6B6B) : new Color(0xC00000)); - } - - private void settingsChanged() { - settings.save(); - render(false); - } - - // ---- rendering ---- - - /** Lays the log out again; {@code toEnd} scrolls to the newest line, otherwise the view stays put. */ - private void render(boolean toEnd) { - int channelWidth = 0; - for (ServerLogEntry e : entries) channelWidth = Math.max(channelWidth, e.channel().length()); - - int scrollY = log.getVisibleRect().y; - try { - doc.remove(0, doc.getLength()); - for (ServerLogEntry e : entries) { - String line = format(e, channelWidth); - if (!view.shows(e.level(), line)) continue; - if (onlyMatching != null && !onlyMatching.matches(line)) continue; - doc.insertString(doc.getLength(), line + "\n", style(view.highlightFor(line))); - } - } catch (BadLocationException ignored) { - // appending at the end never fails - } - - showStatus(entries.isEmpty() ? "No log entries available" : null, Theme.chatEvent()); - - if (toEnd) { - log.setCaretPosition(doc.getLength()); - } else { - SwingUtilities.invokeLater(() -> log.scrollRectToVisible( - new Rectangle(0, scrollY, 1, log.getVisibleRect().height))); - } - } - - /** Shows {@code text} under the log, or hides the label for {@code null}. */ - private void showStatus(String text, Color color) { - status.setText(text); - status.setForeground(color); - status.setVisible(text != null); - } - - private String format(ServerLogEntry e, int channelWidth) { - String time = ""; - if (e.timestamp() != null) { - LocalDateTime t = view.localTime - ? e.timestamp().atOffset(ZoneOffset.UTC).atZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime() - : e.timestamp(); - time = TIME.format(t); - } - return pad(time, 19) + " " + pad(e.channel(), channelWidth) + " " - + pad(levelName(e.level()), LEVEL_WIDTH) + " " + e.message(); - } - - private static String levelName(Level level) { - String name = level.name(); - return name.charAt(0) + name.substring(1).toLowerCase(Locale.ROOT); - } - - private static String pad(String s, int width) { - return s.length() >= width ? s : s + " ".repeat(width - s.length()); - } - - private static SimpleAttributeSet style(Highlight h) { - SimpleAttributeSet a = new SimpleAttributeSet(); - if (h == null) return a; - if (h.foreground() != null) StyleConstants.setForeground(a, new Color(h.foreground())); - if (h.background() != null) StyleConstants.setBackground(a, new Color(h.background())); - return a; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogExcludeDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogExcludeDialog.java deleted file mode 100644 index 0341be1..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogExcludeDialog.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.ts3client.ui; - -import java.awt.Window; -import java.util.List; - -/** The Server Log's exclude filter: terms whose lines are left out. */ -final class ServerLogExcludeDialog extends ListEditorDialog { - - private ServerLogExcludeDialog(Window owner, List terms) { - super(owner, "Exclude Filter", "Exclude lines containing:", "Term:", terms, false); - } - - /** @return whether the terms were changed */ - static boolean edit(Window owner, List terms) { - return new ServerLogExcludeDialog(owner, terms).showAndApply(terms); - } - - @Override - protected String item(String text, String old) { - return text; - } - - @Override - protected String text(String item) { - return item; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogHighlightDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogHighlightDialog.java deleted file mode 100644 index 6cca868..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogHighlightDialog.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.config.ServerLogSettings.Highlight; - -import javax.swing.DefaultListCellRenderer; -import javax.swing.Icon; -import javax.swing.JButton; -import javax.swing.JColorChooser; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Component; -import java.awt.FlowLayout; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.Window; -import java.util.List; -import java.util.function.Function; - -/** The Server Log's highlighting: keywords and the colours their lines are drawn in, first match first. */ -final class ServerLogHighlightDialog extends ListEditorDialog { - - private JButton foreground; - private JButton background; - private JButton clearForeground; - private JButton clearBackground; - - private ServerLogHighlightDialog(Window owner, List highlights) { - super(owner, "Highlighting", null, "Keyword:", highlights, true); - list.setCellRenderer(new DefaultListCellRenderer() { - @Override - public Component getListCellRendererComponent(JList l, Object value, int index, - boolean selected, boolean focused) { - Highlight h = (Highlight) value; - super.getListCellRendererComponent(l, h.keyword(), index, selected, focused); - if (!selected) { - if (h.foreground() != null) setForeground(new Color(h.foreground())); - if (h.background() != null) setBackground(new Color(h.background())); - } - return this; - } - }); - } - - /** @return whether the highlights were changed */ - static boolean edit(Window owner, List highlights) { - return new ServerLogHighlightDialog(owner, highlights).showAndApply(highlights); - } - - @Override - protected Highlight item(String text, Highlight old) { - return old == null ? new Highlight(text, null, null) : new Highlight(text, old.foreground(), old.background()); - } - - @Override - protected String text(Highlight item) { - return item.keyword(); - } - - @Override - protected JComponent extraControls() { - foreground = new JButton("Text Color…"); - foreground.addActionListener(e -> choose("Text Color", Highlight::foreground, true)); - clearForeground = new JButton("None"); - clearForeground.addActionListener(e -> update(null, true)); - background = new JButton("Background…"); - background.addActionListener(e -> choose("Background", Highlight::background, false)); - clearBackground = new JButton("None"); - clearBackground.addActionListener(e -> update(null, false)); - - JPanel row = new JPanel(new FlowLayout(FlowLayout.LEFT, UIScale.scale(4), 0)); - row.setOpaque(false); - row.add(foreground); - row.add(clearForeground); - row.add(new JLabel(" ")); - row.add(background); - row.add(clearBackground); - return row; - } - - @Override - protected void selectionChanged() { - Highlight h = list.getSelectedValue(); - foreground.setEnabled(h != null); - background.setEnabled(h != null); - clearForeground.setEnabled(h != null && h.foreground() != null); - clearBackground.setEnabled(h != null && h.background() != null); - foreground.setIcon(new Swatch(h == null ? null : h.foreground())); - background.setIcon(new Swatch(h == null ? null : h.background())); - } - - private void choose(String title, Function current, boolean isForeground) { - Highlight h = list.getSelectedValue(); - if (h == null) return; - Integer rgb = current.apply(h); - Color chosen = JColorChooser.showDialog(this, title, rgb == null ? Theme.chatText() : new Color(rgb)); - if (chosen != null) update(chosen.getRGB() & 0xFFFFFF, isForeground); - } - - private void update(Integer rgb, boolean isForeground) { - int i = list.getSelectedIndex(); - if (i < 0) return; - Highlight h = model.get(i); - model.set(i, isForeground ? new Highlight(h.keyword(), rgb, h.background()) - : new Highlight(h.keyword(), h.foreground(), rgb)); - selectionChanged(); - } - - /** A colour sample; struck through when there is none. */ - private record Swatch(Integer rgb) implements Icon { - @Override - public void paintIcon(Component c, Graphics g, int x, int y) { - Graphics2D g2 = (Graphics2D) g.create(); - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - int w = getIconWidth() - 1; - int h = getIconHeight() - 1; - if (rgb != null) { - g2.setColor(new Color(rgb)); - g2.fillRect(x, y, w, h); - } - g2.setColor(Theme.border()); - g2.drawRect(x, y, w, h); - if (rgb == null) { - g2.setStroke(new BasicStroke(UIScale.scale(1f))); - g2.drawLine(x, y + h, x + w, y); - } - g2.dispose(); - } - - @Override - public int getIconWidth() { - return UIScale.scale(14); - } - - @Override - public int getIconHeight() { - return UIScale.scale(14); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerMenu.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerMenu.java deleted file mode 100644 index 7b0a39a..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerMenu.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.net.ChannelSettings; - -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; - -/** - * The context menu for the server itself — the tree's root row. - */ -final class ServerMenu { - - private ServerMenu() { - } - - static JPopupMenu build(ServerTreePanel.Actions actions) { - JPopupMenu menu = new JPopupMenu(); - JMenuItem create = new JMenuItem("Create Channel", Icons.of("CHANNEL_CREATE")); - create.addActionListener(a -> actions.createChannel(null, ChannelSettings.Type.PERMANENT)); - menu.add(create); - JMenuItem spacer = new JMenuItem("Create Spacer", - Icons.ofAny("CHANNEL_CREATE_SPACER", "CHANNEL_CREATE")); - spacer.setToolTipText("Create a new spacer"); - spacer.addActionListener(a -> actions.createSpacer()); - menu.add(spacer); - return menu; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTab.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTab.java deleted file mode 100644 index 4276ccb..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTab.java +++ /dev/null @@ -1,371 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.audio.AudioBackend; -import com.ts3client.config.BanReasonPresets; -import com.ts3client.config.IdentityStore; -import com.ts3client.config.Settings; -import com.ts3client.contacts.ContactStore; -import com.ts3client.net.ChannelNode; -import com.ts3client.net.ClientEntry; -import com.ts3client.net.ConnectionListener.ChatScope; -import com.ts3client.net.OfflineMessage; -import com.ts3client.net.PictureDownloads; -import com.ts3client.net.TeamspeakConnection; -import com.ts3client.net.avatar.Avatar; -import com.ts3client.session.ServerSession; -import com.ts3client.sound.SoundNotifier; -import com.ts3client.text.TsLink; - -import javax.swing.JComponent; -import javax.swing.JOptionPane; -import javax.swing.JSplitPane; -import javax.swing.SwingUtilities; -import java.awt.Component; -import java.awt.Window; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; - -/** - * One server connection and the views bound to it (tree, info and chat). The - * client keeps several of these side by side; {@link MainFrame} shows one at a - * time and owns the toolbar, menus and status bar that act on it. - * - *

    The connection and the client's own state on it live in the {@link ServerSession}; - * ServerTab owns the panels, tree context-menu actions and selection live in - * {@link ServerTabTreeActions}, and session callbacks in {@link ServerTabConnectionEvents}. - */ -final class ServerTab { - - private final MainFrame host; - private final Settings settings; - - private final ServerSession session; - private final ContactStore contacts; - private final TeamspeakConnection conn; - private final GroupIcons groupIcons; - private final ServerTabTreeActions treeActions; - private final ServerTreePanel treePanel; - private final ChatPanel chatPanel; - private final InfoPanel infoPanel; - private final AvatarActions avatar; - private final JComponent component; - private JSplitPane leftColumn; - private int normalDividerSize; - private int savedDividerLocation = -1; - /** Whether the saved divider share has been applied; before that, layout is not the user's doing. */ - private boolean splitRestored; - - /** The one open ban list window for this server, if any. */ - private BanListDialog banList; - private PrivilegeKeysDialog privilegeKeys; - private ComplaintsDialog complaints; - private ServerLogDialog serverLog; - private OfflineMessagesDialog offlineMessages; - /** The unread count last reported, to tell new mail from messages being read. */ - private int unreadMessages; - - ServerTab(MainFrame host, Settings settings, IdentityStore identities, AudioBackend audio, - SoundNotifier sounds, ContactStore contacts, PictureDownloads pictures) { - this.host = host; - this.settings = settings; - this.contacts = contacts; - this.infoPanel = new InfoPanel(settings, pictures, host.infoZoom()); - - // ServerTabConnectionEvents must exist before the session (which needs a listener - // up front), and the session must exist before the tree/chat panels and the other - // tab helpers that read from it — so wiring finishes with an explicit attach() once - // everything is built. Nothing fires callbacks before then. - ServerTabConnectionEvents events = new ServerTabConnectionEvents(host, this, settings); - this.session = new ServerSession(settings, identities, audio, sounds, contacts, events); - this.conn = session.connection(); - this.groupIcons = new GroupIcons(conn.getIcons()); - this.chatPanel = new ChatPanel(host.chatZoom(), settings, pictures, conn::serverUniqueId); - this.treeActions = new ServerTabTreeActions(host, this, conn, chatPanel, infoPanel, groupIcons); - this.treePanel = new ServerTreePanel(conn.getModel(), groupIcons, contacts, settings, treeActions); - treeActions.attach(treePanel); - events.attach(session, treePanel, chatPanel, treeActions); - - chatPanel.setSendHandler(this::onSendChat); - chatPanel.setLinkHandler(new ChatPanel.LinkHandler() { - @Override - public void onClientLink(TsLink.Ref ref, Component source, int x, int y) { - treeActions.handleClientLink(ref, source, x, y); - } - - @Override - public void onChannelLink(TsLink.Ref ref, Component source, int x, int y) { - treeActions.handleChannelLink(ref, source, x, y); - } - - @Override - public void onOfflineMessagesLink() { - showOfflineMessages(); - } - }); - chatPanel.setAttachmentHandler(new ChatAttachmentActions(host, session, chatPanel, pictures, ServerTab::scope)); - chatPanel.setSharingAvailable(host.canShareFiles()); - chatPanel.setInputEnabled(false); - - infoPanel.setDescriptionHandler(new InfoPanel.DescriptionHandler() { - @Override - public void showInfoTab(String html, Runnable onClose) { - chatPanel.openDescriptionTab("info", Icons.channelClientPair(), "", html, onClose); - } - - @Override - public void closeInfoTab() { - chatPanel.closeNoteTab("info"); - } - - @Override - public void setPanelHidden(boolean hidden) { - ServerTab.this.setInfoPanelHidden(hidden); - } - }); - - this.avatar = new AvatarActions(host, conn); - infoPanel.setAvatarHandler(new InfoPanel.AvatarHandler() { - @Override - public void steal(Avatar other) { - avatar.steal(other); - } - - @Override - public boolean canSet() { - return session.canSetAvatar(); - } - - @Override - public boolean canDeleteOthers() { - return session.canDeleteOtherAvatars(); - } - - @Override - public void deleteOf(ClientEntry client) { - avatar.deleteOf(client); - } - - @Override - public void set() { - avatar.choose(); - } - - @Override - public void delete() { - avatar.delete(); - } - }); - - leftColumn = new JSplitPane(JSplitPane.VERTICAL_SPLIT, treePanel, infoPanel); - leftColumn.setResizeWeight(0.68); - leftColumn.setContinuousLayout(true); - normalDividerSize = leftColumn.getDividerSize(); - // The info panel keeps the height the user gave it, in this tab and the next session. - leftColumn.addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent e) { - if (splitRestored) return; - splitRestored = true; - leftColumn.setDividerLocation(settings.infoSplitRatio); - } - }); - leftColumn.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, e -> rememberSplit()); - - JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftColumn, chatPanel); - split.setResizeWeight(0.55); - split.setDividerLocation(400); - split.setContinuousLayout(true); - this.component = split; - } - - // ---- accessors ---- - - JComponent component() { - return component; - } - - ServerSession session() { - return session; - } - - TeamspeakConnection connection() { - return conn; - } - - ChatPanel chat() { - return chatPanel; - } - - /** Opens the server's ban list, or brings the already open one forward. */ - void showBanList(BanReasonPresets presets) { - if (!session.isConnected()) return; - if (banList == null || !banList.isDisplayable()) { - banList = new BanListDialog(host, conn, settings, presets); - } - banList.setVisible(true); - banList.toFront(); - } - - /** Opens the server's complaints, or brings the already open window forward. */ - void showComplaints() { - if (!session.isConnected()) return; - if (complaints == null || !complaints.isDisplayable()) { - complaints = new ComplaintsDialog(host, conn, treeActions::banClient); - } - complaints.setVisible(true); - complaints.toFront(); - } - - /** Opens the server's log, or brings the already open window forward. */ - void showServerLog() { - if (!session.isConnected()) return; - if (serverLog == null || !serverLog.isDisplayable()) { - serverLog = new ServerLogDialog(host, conn, settings); - } - serverLog.setVisible(true); - serverLog.toFront(); - } - - /** Opens our offline message inbox, or brings the already open window forward. */ - void showOfflineMessages() { - if (!session.isConnected()) return; - if (offlineMessages == null || !offlineMessages.isDisplayable()) { - offlineMessages = new OfflineMessagesDialog(host, conn, new OfflineMessagesDialog.Composer() { - @Override - public void compose() { - composeOfflineMessage(); - } - - @Override - public void reply(OfflineMessage message, String body) { - if (!session.isConnected()) return; - OfflineMessageComposeDialog.reply(offlineMessages, conn, contacts, message, body).setVisible(true); - } - }); - } - offlineMessages.setVisible(true); - offlineMessages.toFront(); - } - - void composeOfflineMessage() { - if (!session.isConnected() || !conn.canSendOfflineMessages()) return; - Window owner = offlineMessages != null && offlineMessages.isShowing() ? offlineMessages : host; - OfflineMessageComposeDialog.compose(owner, conn, contacts).setVisible(true); - } - - /** New mail refreshes an open inbox; a message being read does not need to. */ - void unreadMessagesChanged(int unread) { - boolean newMail = unread > unreadMessages; - unreadMessages = unread; - if (newMail && offlineMessages != null && offlineMessages.isDisplayable()) offlineMessages.reload(); - } - - /** Asks for a privilege key and redeems it on this server. */ - void usePrivilegeKey() { - if (!session.isConnected()) return; - String key = (String) JOptionPane.showInputDialog(host, "Privilege Key:", "Use Privilege Key", - JOptionPane.PLAIN_MESSAGE, Icons.of("TOKEN_USE"), null, null); - if (key == null || key.isBlank()) return; - conn.usePrivilegeKey(key.trim(), error -> { - if (error == null) return; - SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(host, error, - "Error using Privilege Key", JOptionPane.ERROR_MESSAGE)); - }); - } - - /** Opens the server's privilege keys, or brings the already open window forward. */ - void showPrivilegeKeys() { - if (!session.isConnected()) return; - if (privilegeKeys == null || !privilegeKeys.isDisplayable()) { - privilegeKeys = new PrivilegeKeysDialog(host, conn, groupIcons); - } - privilegeKeys.setVisible(true); - privilegeKeys.toFront(); - } - - /** The server's name changed or the connection went; the server admin windows follow. */ - void serverWindowsChanged(boolean connected) { - if (banList != null) { - if (connected) banList.serverNameChanged(); - else banList.connectionLost(); - } - if (complaints != null) { - if (connected) complaints.serverNameChanged(); - else complaints.connectionLost(); - } - if (serverLog != null) { - if (connected) serverLog.serverNameChanged(); - else serverLog.connectionLost(); - } - if (privilegeKeys != null) { - if (connected) privilegeKeys.serverNameChanged(); - else privilegeKeys.connectionLost(); - } - if (offlineMessages != null) { - if (connected) offlineMessages.serverNameChanged(); - else offlineMessages.connectionLost(); - } - if (!connected) unreadMessages = 0; - } - - /** The contact list changed: names, colours and per-client playback follow. */ - void contactsChanged() { - conn.applyContacts(); - treePanel.refreshRowSizes(); - treeActions.renderInfo(); - } - - // ---- dialogs ---- - - AvatarActions avatar() { - return avatar; - } - - // ---- chat ---- - - private void onSendChat(ChatPanel.Target target, int clientId, String text) { - session.sendChat(scope(target), clientId, text); - } - - private static ChatScope scope(ChatPanel.Target target) { - return switch (target) { - case SERVER -> ChatScope.SERVER; - case PRIVATE -> ChatScope.PRIVATE; - default -> ChatScope.CHANNEL; - }; - } - - /** Opens the file repository browser for a channel, as the "Browse Files" hotkey/menu action does. */ - void browseFiles(ChannelNode channel) { - treeActions.browseFiles(channel); - } - - /** - * Records where the user put the divider, as a share of the column. Collapsed and - * pre-layout positions are not the user's choice, so they are left out. - */ - private void rememberSplit() { - if (!splitRestored || !infoPanel.isVisible()) return; - int span = leftColumn.getHeight() - leftColumn.getDividerSize(); - if (span <= 0) return; - double ratio = leftColumn.getDividerLocation() / (double) span; - if (ratio <= 0.05 || ratio >= 0.98) return; - settings.infoSplitRatio = ratio; - } - - /** Collapses the info panel to nothing while its content lives in the chat tab, or restores it. */ - private void setInfoPanelHidden(boolean hidden) { - if (hidden == !infoPanel.isVisible()) return; - if (hidden) { - savedDividerLocation = leftColumn.getDividerLocation(); - infoPanel.setVisible(false); - leftColumn.setDividerSize(0); - leftColumn.setDividerLocation(1.0); - } else { - infoPanel.setVisible(true); - leftColumn.setDividerSize(normalDividerSize); - if (savedDividerLocation >= 0) leftColumn.setDividerLocation(savedDividerLocation); - } - leftColumn.revalidate(); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTabConnectionEvents.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTabConnectionEvents.java deleted file mode 100644 index 9129330..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTabConnectionEvents.java +++ /dev/null @@ -1,209 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.config.Settings; -import com.ts3client.net.ChannelNode; -import com.ts3client.net.TeamspeakConnection; -import com.ts3client.session.ServerSession; - -import javax.swing.JOptionPane; -import javax.swing.SwingUtilities; -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Marshals {@link ServerSession} callbacks onto the EDT and fans them out to this tab's - * views (tree, chat, info panel) and to {@link MainFrame}. - * - *

    Constructed before the session it listens to exists — the session's constructor - * needs a listener up front — so {@link #attach} wires the rest of the tab in once - * everything else has been built. - */ -final class ServerTabConnectionEvents implements ServerSession.Listener { - - private final MainFrame host; - private final ServerTab tab; - private final Settings settings; - - private final AtomicBoolean modelChangePending = new AtomicBoolean(); - - private ServerSession session; - private TeamspeakConnection conn; - private ServerTreePanel treePanel; - private ChatPanel chatPanel; - private ServerTabTreeActions treeActions; - - ServerTabConnectionEvents(MainFrame host, ServerTab tab, Settings settings) { - this.host = host; - this.tab = tab; - this.settings = settings; - } - - void attach(ServerSession session, ServerTreePanel treePanel, ChatPanel chatPanel, - ServerTabTreeActions treeActions) { - this.session = session; - this.conn = session.connection(); - this.treePanel = treePanel; - this.chatPanel = chatPanel; - this.treeActions = treeActions; - } - - @Override - public void onSessionChanged() { - SwingUtilities.invokeLater(() -> { - if (session.isConnected()) tab.serverWindowsChanged(true); - host.tabUpdated(tab); - }); - } - - @Override - public void onSystemMessage(String text) { - SwingUtilities.invokeLater(() -> chatPanel.appendSystem(text)); - } - - @Override - public void onOwnChat(ChatScope scope, int peerClientId, String peerName, String text) { - String me = settings.nickname + " (you)"; - int myId = conn.getSelfClientId(); - SwingUtilities.invokeLater(() -> { - switch (scope) { - case SERVER -> chatPanel.appendServerMessage(myId, me, text); - case PRIVATE -> chatPanel.appendPrivateMessage(peerClientId, peerName, myId, me, text); - default -> chatPanel.appendChannelMessage(myId, me, text); - } - }); - } - - @Override - public void onUnreadMessagesChanged(int unread) { - SwingUtilities.invokeLater(() -> { - tab.unreadMessagesChanged(unread); - host.tabUpdated(tab); - }); - } - - @Override - public void onStatus(String text) { - // Reaches the tab through onSessionChanged. - } - - @Override - public void onConnected() { - SwingUtilities.invokeLater(() -> { - treePanel.setSelfClientId(conn.getSelfClientId()); - chatPanel.setInputEnabled(true); - host.tabConnected(tab); - }); - } - - @Override - public void onDisconnected(String reason) { - SwingUtilities.invokeLater(() -> { - treePanel.showDisconnected(); - treeActions.clearSelection(); - chatPanel.setInputEnabled(false); - chatPanel.closePrivateChats(); - chatPanel.closeNoteTabs(); - chatPanel.setServerName(null); - chatPanel.setChannelName(null); - tab.serverWindowsChanged(false); - host.tabDisconnected(tab); - }); - } - - @Override - public void onModelChanged() { - // Events arrive in bursts (hundreds while connecting); one rebuild covers all of them. - if (!modelChangePending.compareAndSet(false, true)) return; - SwingUtilities.invokeLater(() -> { - modelChangePending.set(false); - treePanel.rebuild(); - treeActions.renderInfo(); - treeActions.refreshGroupsDialog(); - host.refreshHostButton(tab); - if (session.isConnected()) { - ChannelNode channel = session.currentChannel(); - chatPanel.setServerName(conn.getModel().getServerName()); - chatPanel.setChannelName(channel == null ? null : channel.name); - } - }); - } - - @Override - public void onServerIconChanged(long iconId) { - SwingUtilities.invokeLater(() -> host.serverIconChanged(tab, iconId)); - } - - @Override - public void onInfoUpdated() { - SwingUtilities.invokeLater(treeActions::renderInfo); - } - - @Override - public void onIconsUpdated() { - SwingUtilities.invokeLater(() -> { - treePanel.refreshRowSizes(); - treeActions.renderInfo(); - }); - } - - @Override - public void onChat(ChatScope scope, int fromClientId, String fromUniqueId, String fromName, String message) { - SwingUtilities.invokeLater(() -> { - switch (scope) { - case PRIVATE -> { - chatPanel.appendPrivateMessage(fromClientId, fromUniqueId, fromName, - fromClientId, fromUniqueId, fromName, message); - host.notifier().privateMessage(tab, fromClientId, fromName, message); - } - case SERVER -> chatPanel.appendServerMessage(fromClientId, fromUniqueId, fromName, message); - default -> chatPanel.appendChannelMessage(fromClientId, fromUniqueId, fromName, message); - } - }); - } - - @Override - public void onChatHistory(ChatScope scope, List htmlEntries) { - SwingUtilities.invokeLater(() -> { - if (scope == ChatScope.SERVER) chatPanel.setServerHistory(htmlEntries); - else if (scope == ChatScope.CHANNEL) chatPanel.setChannelHistory(htmlEntries); - }); - } - - @Override - public void onPrivateChatHistory(int clientId, String nickname, List htmlEntries) { - SwingUtilities.invokeLater(() -> chatPanel.setPrivateHistory(clientId, nickname, htmlEntries)); - } - - @Override - public void onTalkStateChanged(int clientId, boolean talking) { - SwingUtilities.invokeLater(() -> { - treePanel.refreshVisual(); - if (clientId == conn.getSelfClientId()) host.selfStateChanged(tab); - }); - } - - @Override - public void onError(String message) { - // Reaches the chat through onSystemMessage and the tab through onSessionChanged. - } - - @Override - public void onServerLog(String message) { - SwingUtilities.invokeLater(() -> chatPanel.appendServerLog(message)); - } - - @Override - public void onServerLogHtml(String html) { - SwingUtilities.invokeLater(() -> chatPanel.appendServerLogHtml(html)); - } - - @Override - public void onPoke(String fromName, String message) { - SwingUtilities.invokeLater(() -> { - host.notifier().poke(tab, fromName, message); - host.selectTab(tab); - JOptionPane.showMessageDialog(host, fromName + " poked you:\n\n" + message, - "Poke", JOptionPane.INFORMATION_MESSAGE); - }); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTabPane.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTabPane.java deleted file mode 100644 index 22f4fd3..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTabPane.java +++ /dev/null @@ -1,198 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTabbedPane; -import javax.swing.SwingUtilities; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.Insets; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseWheelEvent; -import java.util.ArrayList; -import java.util.List; - -/** - * Container for the open server connections. With a single connection the - * server view fills the window as it always did; from the second connection on - * the views move into a {@link JTabbedPane} whose tab strip sits directly under - * the toolbar. - */ -final class ServerTabPane extends JPanel { - - interface Listener { - void selectTab(ServerTab tab); - - void closeTab(ServerTab tab); - } - - private final Listener listener; - private final JTabbedPane tabbed = new JTabbedPane(); - private final List tabs = new ArrayList<>(); - private final TabDragReorder dragReorder = new TabDragReorder(tabbed, this::moveTab); - - /** True while the tab strip is in use, i.e. more than one connection is open. */ - private boolean tabbedMode; - /** Suppresses selection callbacks while we rearrange the pane ourselves. */ - private boolean updating; - /** Remembered so a drag-reorder can rebuild the tab labels without the caller's help. */ - private ServerTab lastMicTab; - - ServerTabPane(Listener listener) { - super(new BorderLayout()); - this.listener = listener; - tabbed.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); - tabbed.setFocusable(false); - tabbed.addChangeListener(e -> { - if (updating) return; - int i = tabbed.getSelectedIndex(); - if (i >= 0 && i < tabs.size()) listener.selectTab(tabs.get(i)); - }); - tabbed.addMouseWheelListener(this::onWheel); - dragReorder.attach(tabbed); - } - - /** - * The tab strip is out of the component tree while a single server is open, so a - * look-and-feel switch would miss it and leave it in the old theme's colours. - */ - @Override - public void updateUI() { - super.updateUI(); - if (tabbed != null && tabbed.getParent() == null) SwingUtilities.updateComponentTreeUI(tabbed); - } - - /** Drags a tab from one position to another, keeping the current selection on screen. */ - private void moveTab(int from, int to) { - if (from < 0 || to < 0 || from >= tabs.size() || to >= tabs.size() || from == to) return; - ServerTab selected = tabbed.getSelectedIndex() >= 0 && tabbed.getSelectedIndex() < tabs.size() - ? tabs.get(tabbed.getSelectedIndex()) : null; - tabs.add(to, tabs.remove(from)); - updating = true; - try { - tabbed.removeAll(); - for (ServerTab tab : tabs) tabbed.addTab(tab.session().title(), tab.component()); - if (selected != null) tabbed.setSelectedIndex(tabs.indexOf(selected)); - } finally { - updating = false; - } - refresh(lastMicTab); - } - - /** - * Scrolling over the tab strip steps through the connections. The content - * area keeps its own scrolling, so only wheel events on the strip itself - * (and on the tab labels, which forward theirs) change tabs. - */ - private void onWheel(MouseWheelEvent e) { - if (!tabbedMode) return; - Component content = tabbed.getSelectedComponent(); - if (content != null && content.getBounds().contains(e.getPoint())) return; - - int steps = e.getWheelRotation(); - if (steps == 0) return; - int target = Math.max(0, Math.min(tabs.size() - 1, tabbed.getSelectedIndex() + steps)); - if (target != tabbed.getSelectedIndex()) listener.selectTab(tabs.get(target)); - e.consume(); - } - - void addTab(ServerTab tab) { - tabs.add(tab); - relayout(); - } - - void removeTab(ServerTab tab) { - tabs.remove(tab); - relayout(); - } - - void setSelected(ServerTab tab) { - int i = tabs.indexOf(tab); - if (!tabbedMode || i < 0 || tabbed.getSelectedIndex() == i) return; - updating = true; - try { - tabbed.setSelectedIndex(i); - } finally { - updating = false; - } - } - - /** Refreshes the tab labels; {@code micTab} is marked as owning the microphone. */ - void refresh(ServerTab micTab) { - lastMicTab = micTab; - if (!tabbedMode) return; - for (int i = 0; i < tabs.size(); i++) { - ServerTab tab = tabs.get(i); - tabbed.setTitleAt(i, tab.session().title()); - tabbed.setToolTipTextAt(i, tab.session().status()); - tabbed.setTabComponentAt(i, buildTabComponent(tab, tab == micTab)); - } - } - - /** - * Moves the views between the plain single-server layout and the tabbed one, - * keeping whatever is currently selected on screen. - */ - private void relayout() { - boolean wantTabs = tabs.size() > 1; - updating = true; - try { - removeAll(); - tabbed.removeAll(); - if (wantTabs) { - for (ServerTab tab : tabs) tabbed.addTab(tab.session().title(), tab.component()); - add(tabbed, BorderLayout.CENTER); - } else if (!tabs.isEmpty()) { - add(tabs.get(0).component(), BorderLayout.CENTER); - } - tabbedMode = wantTabs; - } finally { - updating = false; - } - revalidate(); - repaint(); - } - - /** A tab's label: title, microphone marker and a close button. */ - private JComponent buildTabComponent(ServerTab tab, boolean hasMic) { - JPanel cell = new JPanel(new FlowLayout(FlowLayout.LEFT, UIScale.scale(4), 0)); - cell.setOpaque(false); - cell.setBorder(new ScaledEmptyBorder(1, 0, 1, 0)); - - JLabel label = new JLabel(tab.session().title(), hasMic ? Icons.micActiveSmall() : null, JLabel.LEADING); - label.setFont(Theme.uiFont()); - label.setToolTipText(hasMic ? "Speaking on this server" : tab.session().status()); - // A label with a tooltip swallows mouse events, so select the tab explicitly. - label.addMouseListener(new MouseAdapter() { - @Override - public void mousePressed(MouseEvent e) { - listener.selectTab(tab); - } - }); - cell.add(label); - dragReorder.attach(cell); - dragReorder.attach(label); - - JButton close = new JButton("✕"); - close.setFont(Theme.uiFont()); - close.setFocusable(false); - close.setBorder(BorderFactory.createEmptyBorder()); - close.setContentAreaFilled(false); - close.setMargin(new Insets(0, 0, 0, 0)); - close.setForeground(Theme.chatSystem()); - close.setPreferredSize(UIScale.scale(new Dimension(14, 14))); - close.setToolTipText("Close this connection"); - close.addActionListener(e -> listener.closeTab(tab)); - cell.add(close); - return cell; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTabTreeActions.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTabTreeActions.java deleted file mode 100644 index 028e070..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTabTreeActions.java +++ /dev/null @@ -1,366 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.contacts.ContactType; -import com.ts3client.net.ChannelNode; -import com.ts3client.net.Spacers; -import com.ts3client.net.ChannelSettings; -import com.ts3client.net.ClientEntry; -import com.ts3client.net.Group; -import com.ts3client.net.TeamspeakConnection; -import com.ts3client.text.TsLink; - -import javax.swing.JOptionPane; -import javax.swing.SwingUtilities; -import java.awt.Component; - -/** - * Context-menu and drag/drop actions for one server's tree, plus tracking which - * node is selected so the info panel stays in sync. Also handles client/channel - * links clicked in the chat log, which open the same menus as the tree does. - * - *

    Constructed before the {@link ServerTreePanel} it drives exists — the tree's - * constructor needs an {@link ServerTreePanel.Actions} up front — so {@link #attach} - * wires the tree back in once it has been built. - */ -final class ServerTabTreeActions implements ServerTreePanel.Actions { - - private final MainFrame host; - private final ServerTab tab; - private final TeamspeakConnection conn; - private final ChatPanel chatPanel; - private final InfoPanel infoPanel; - private final GroupIcons groupIcons; - private ServerTreePanel treePanel; - - private Object currentSelection; - /** The one open {@link ServerGroupsDialog}, if any, refreshed whenever the model changes. */ - private ServerGroupsDialog groupsDialog; - - ServerTabTreeActions(MainFrame host, ServerTab tab, TeamspeakConnection conn, - ChatPanel chatPanel, InfoPanel infoPanel, GroupIcons groupIcons) { - this.host = host; - this.tab = tab; - this.conn = conn; - this.chatPanel = chatPanel; - this.infoPanel = infoPanel; - this.groupIcons = groupIcons; - } - - void attach(ServerTreePanel treePanel) { - this.treePanel = treePanel; - } - - /** Called by {@link ServerTabConnectionEvents} whenever the model changes, to live-refresh an open dialog. */ - void refreshGroupsDialog() { - if (groupsDialog != null) groupsDialog.refresh(); - } - - /** Refreshes the info panel for whatever is currently selected (or clears it). */ - void renderInfo() { - Object sel = currentSelection; - if (sel instanceof ChannelNode) { - infoPanel.showChannel((ChannelNode) sel); - } else if (sel instanceof ClientEntry) { - ClientEntry client = (ClientEntry) sel; - infoPanel.showClient(client, conn.getModel(), conn.getIcons(), - conn.getContacts().find(client.uniqueId), conn.avatarOf(client)); - } else if (sel instanceof String && conn.isConnected()) { - // The root row is the server itself, whose user object is just its name. - infoPanel.showServer(conn.getModel(), conn.getServerHost() + ":" + conn.getServerPort()); - } else { - infoPanel.clear(); - } - } - - /** Drops the selection on disconnect, since the model it points into is gone. */ - void clearSelection() { - currentSelection = null; - infoPanel.clear(); - } - - /** A client link in the chat log was clicked: show the same menu as the tree does. */ - void handleClientLink(TsLink.Ref ref, Component source, int x, int y) { - ClientEntry client = conn.getModel().getClient(ref.id); - // The id is only valid for the session the link was made in; fall back to - // the unique id (and finally the nickname) so older links still resolve. - if (client == null || (!ref.uniqueId.isEmpty() && !ref.uniqueId.equals(client.uniqueId))) { - ClientEntry byUid = ref.uniqueId.isEmpty() ? null - : conn.getModel().findClientByUniqueId(ref.uniqueId); - if (byUid == null && !ref.name.isEmpty()) byUid = conn.getModel().findClientByName(ref.name); - if (byUid != null) client = byUid; - } - if (client == null) { - chatPanel.appendSystem("That client is no longer on the server."); - return; - } - ClientMenu.build(client, client.id == conn.getSelfClientId(), false, conn.getModel(), groupIcons, this) - .show(source, x, y); - } - - void handleChannelLink(TsLink.Ref ref, Component source, int x, int y) { - ChannelNode channel = conn.getModel().getChannel(ref.id); - if (channel == null) { - chatPanel.appendSystem("That channel no longer exists."); - return; - } - ChannelMenu.build(channel, this).show(source, x, y); - } - - // ---- ServerTreePanel.Actions ---- - - @Override - public void joinChannel(int channelId) { - if (conn.isConnected()) conn.joinChannel(channelId, null); - } - - @Override - public void moveClientToChannel(ClientEntry client, ChannelNode target) { - if (!conn.isConnected()) return; - if (client.id == conn.getSelfClientId()) { - conn.joinChannel(target.id, null); - } else { - conn.moveClient(client.id, target.id, null); - } - } - - @Override - public void moveChannel(ChannelNode channel, int newParentId, int orderPredecessorId) { - if (conn.isConnected()) conn.moveChannel(channel.id, newParentId, orderPredecessorId); - } - - @Override - public void openPrivateChat(ClientEntry client) { - chatPanel.openPrivateChat(client.id, client.uniqueId, conn.displayName(client)); - conn.loadPrivateChatHistory(client.id, client.uniqueId); - } - - @Override - public void pokeClient(ClientEntry client) { - String msg = JOptionPane.showInputDialog(host, "Poke message for " + client.nickname + ":", "Poke!"); - if (msg != null) conn.poke(client.id, msg); - } - - @Override - public void complainAboutClient(ClientEntry client) { - if (!conn.isConnected()) return; - String reason = ReasonDialog.prompt(host, "Make a Complaint", "Enter the reason for your complaint:", - TeamspeakConnection.COMPLAINT_REASON_LIMIT); - if (reason != null) conn.complain(client, reason); - } - - @Override - public void kickClientFromChannel(ClientEntry client) { - String reason = kickReason("Kick Client from Channel", client); - if (reason != null) conn.kickFromChannel(client.id, reason); - } - - @Override - public void kickClientFromServer(ClientEntry client) { - String reason = kickReason("Kick Client from Server", client); - if (reason != null) conn.kickFromServer(client.id, reason); - } - - private String kickReason(String title, ClientEntry client) { - if (!conn.isConnected()) return null; - return ReasonDialog.prompt(host, title, "Reason for kicking " + client.nickname + ":", - TeamspeakConnection.KICK_REASON_LIMIT); - } - - @Override - public void banClient(ClientEntry client) { - if (!conn.isConnected()) return; - BanDialog dialog = new BanDialog(host, client.nickname, - conn.getModel().maxBanSeconds()); - dialog.setVisible(true); - if (dialog.isConfirmed()) conn.banClient(client.id, dialog.getSeconds(), dialog.getReason()); - } - - @Override - public void toggleClientMute(ClientEntry client) { - if (conn.getPlayback() == null) return; - boolean now = !conn.getPlayback().isClientMuted(client.id); - conn.getPlayback().setClientMuted(client.id, now); - } - - @Override - public void findClientInTree(ClientEntry client) { - host.selectTab(tab); - treePanel.selectClient(client.id); - } - - @Override - public void showConnectionInfo(ClientEntry client) { - if (!conn.isConnected()) return; - new ConnectionInfoDialog(host, conn, client.id, client.nickname).setVisible(true); - } - - @Override - public void moveClientToOwnChannel(ClientEntry client) { - if (!conn.isConnected() || client.id == conn.getSelfClientId()) return; - ClientEntry self = conn.getModel().getClient(conn.getSelfClientId()); - if (self != null) conn.moveClient(client.id, self.channelId, null); - } - - @Override - public void setClientServerGroup(ClientEntry client, Group group, boolean assign) { - if (conn.isConnected()) conn.setClientServerGroup(client.databaseId, group.id, assign); - } - - @Override - public void setClientChannelGroup(ClientEntry client, Group group) { - if (conn.isConnected()) conn.setClientChannelGroup(client.databaseId, client.channelId, group.id); - } - - @Override - public void showServerGroupsDialog(ClientEntry client) { - if (!conn.isConnected()) return; - groupsDialog = new ServerGroupsDialog(host, conn, groupIcons, client, this); - groupsDialog.setVisible(true); - groupsDialog = null; - } - - /** - * Reads the description from the server before prompting, since the model only - * carries one for clients whose info has been looked at. - */ - @Override - public boolean canDeleteOtherAvatars() { - return tab.session().canDeleteOtherAvatars(); - } - - @Override - public void deleteClientAvatar(ClientEntry client) { - tab.avatar().deleteOf(client); - } - - @Override - public void changeClientDescription(ClientEntry client) { - if (!conn.isConnected()) return; - conn.requestClientDescription(client.id, (description, error) -> SwingUtilities.invokeLater(() -> { - if (error != null) { - JOptionPane.showMessageDialog(host, "Could not read the description: " + error, - "Error", JOptionPane.ERROR_MESSAGE); - return; - } - String edited = (String) JOptionPane.showInputDialog(host, - "Description for " + client.nickname + ":", "Change Description", - JOptionPane.PLAIN_MESSAGE, Icons.of("EDIT"), null, description); - if (edited == null || edited.equals(description)) return; - conn.setClientDescription(client.id, edited, failure -> SwingUtilities.invokeLater(() -> { - if (failure != null) { - JOptionPane.showMessageDialog(host, "Could not change the description: " + failure, - "Error", JOptionPane.ERROR_MESSAGE); - } - })); - })); - } - - @Override - public void addContact(ClientEntry client, ContactType type) { - conn.getContacts().add(client.uniqueId, client.nickname, type, host.settings().contactDefaults); - } - - @Override - public void editContact(ClientEntry client) { - host.showContacts(client.uniqueId); - } - - @Override - public void removeContact(ClientEntry client) { - conn.getContacts().remove(client.uniqueId); - } - - @Override - public ContactType contactTypeOf(ClientEntry client) { - return conn.getContacts().typeOf(client.uniqueId); - } - - @Override - public void changeClientVolume(ClientEntry client) { - if (!conn.isConnected()) return; - new ClientVolumeDialog(host, conn, client).setVisible(true); - } - - @Override - public void renameSelf(String nickname) { - host.changeNickname(nickname); - } - - @Override - public void setChannelSubscribed(ChannelNode channel, boolean family, boolean subscribed) { - if (conn.isConnected()) conn.setChannelsSubscribed(channel.familyIds(family), subscribed); - } - - @Override - public void editChannel(ChannelNode channel) { - if (!conn.isConnected()) return; - ChannelDialog.toEdit(host, conn, groupIcons, channel).setVisible(true); - } - - @Override - public void deleteChannel(ChannelNode channel) { - if (!conn.isConnected()) return; - // Like TeamSpeak, a channel that is not empty takes its sub-channels along and sends its clients away. - boolean occupied = !channel.children.isEmpty() || !channel.clients.isEmpty(); - String question = "Delete channel \"" + channel.name + "\"" - + (occupied ? " with its sub-channels and the clients in it?" : "?"); - if (JOptionPane.showConfirmDialog(host, question, "Delete Channel", JOptionPane.OK_CANCEL_OPTION, - JOptionPane.WARNING_MESSAGE) != JOptionPane.OK_OPTION) { - return; - } - conn.deleteChannel(channel.id, true, error -> { - if (error != null) SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(host, - "Could not delete the channel: " + error, "Error", JOptionPane.ERROR_MESSAGE)); - }); - } - - @Override - public void createChannel(ChannelNode parent, ChannelSettings.Type type) { - if (!conn.isConnected()) return; - ChannelSettings defaults = new ChannelSettings(); - defaults.type = type; - ChannelDialog.toCreate(host, conn, groupIcons, - parent == null ? "Create Channel" : "Create Sub-Channel of " + parent.name, - parent == null ? 0 : parent.id, defaults).setVisible(true); - } - - @Override - public void createSpacer() { - if (!conn.isConnected()) return; - ChannelSettings defaults = new ChannelSettings(); - // Spacers are cosmetic root channels, so they outlive everyone and, being channels, - // need a name no other channel has — which is what the tag's number is for. - defaults.name = Spacers.freeName(conn.getModel().childrenOf(0)); - ChannelDialog.toCreate(host, conn, groupIcons, "Create Spacer", 0, defaults) - .setVisible(true); - } - - @Override - public boolean isConnected() { - return conn.isConnected(); - } - - @Override - public void browseFiles(ChannelNode channel) { - if (!conn.canTransferFiles()) return; - new FileBrowserDialog(host, conn, channel).setVisible(true); - } - - @Override - public boolean isClientLocallyMuted(int clientId) { - return conn.getPlayback() != null && conn.getPlayback().isClientMuted(clientId); - } - - @Override - public void onSelectionChanged(Object userObject) { - currentSelection = userObject; - renderInfo(); - if (!conn.isConnected()) return; - if (userObject instanceof ChannelNode) { - ChannelNode ch = (ChannelNode) userObject; - if (!ch.descriptionLoaded) conn.requestChannelInfo(ch.id); - } else if (userObject instanceof ClientEntry) { - conn.requestClientInfo(((ClientEntry) userObject).id); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTreeCellRenderer.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTreeCellRenderer.java deleted file mode 100644 index 8d1f4a1..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTreeCellRenderer.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.config.Settings; -import com.ts3client.contacts.Contact; -import com.ts3client.contacts.ContactStore; -import com.ts3client.net.ChannelNode; -import com.ts3client.net.Spacers; -import com.ts3client.net.ClientEntry; -import com.ts3client.net.ClientStatus; - -import javax.swing.ImageIcon; -import javax.swing.JTree; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeCellRenderer; -import java.awt.Color; -import java.awt.Component; -import java.util.function.IntPredicate; - -/** - * Draws a {@link ServerTreePanel} row: the status icon and the label. The group - * icon strip is painted separately, right-aligned, by {@link DropIndicatorTree}. - */ -final class ServerTreeCellRenderer extends DefaultTreeCellRenderer { - - /** Whether a client id is our own, which the panel learns on connecting. */ - private final IntPredicate isSelf; - private final ContactStore contacts; - private final Settings settings; - - ServerTreeCellRenderer(IntPredicate isSelf, ContactStore contacts, Settings settings) { - this.isSelf = isSelf; - this.contacts = contacts; - this.settings = settings; - } - - @Override - public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, - boolean expanded, boolean leaf, int row, - boolean hasFocus) { - super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); - setBackgroundNonSelectionColor(Theme.treeBg()); - setBackgroundSelectionColor(Theme.treeSelection()); - setBorderSelectionColor(Theme.treeSelection()); - - Object obj = ((DefaultMutableTreeNode) value).getUserObject(); - if (obj instanceof ChannelNode) { - ChannelNode c = (ChannelNode) obj; - Spacers.Spacer spacer = Spacers.parse(c.name); - if (spacer != null) { - setText(Spacers.render(spacer, 40)); - setIcon(null); - setForeground(Theme.idleClient()); - setFont(Theme.uiFont()); - } else { - setText(c.name); - setIcon(iconFor(c)); - setForeground(Theme.channelText()); - setFont(Theme.uiBold()); - } - } else if (obj instanceof ClientEntry) { - ClientEntry cl = (ClientEntry) obj; - Contact contact = contacts.find(cl.uniqueId); - String label = contact == null ? cl.nickname : contact.displayName(cl.nickname); - if (cl.away && !cl.awayMessage.isEmpty() && (contact == null || !contact.ignoreAwayMessage)) { - label += " [" + cl.awayMessage + "]"; - } - setText(label); - setIcon(iconFor(cl)); - // Talking shows in the client's icon, as it does in TeamSpeak. Marking the - // name as well would also re-measure the row mid-speech, which leaves the - // nickname clipped to an ellipsis for as long as it lasts. Our own name is - // bold throughout, so its width never changes either. - setForeground(contactColor(contact)); - setFont(isSelf.test(cl.id) ? Theme.uiBold() : Theme.uiFont()); - } else { - // root / server - setText(String.valueOf(obj)); - setIcon(Icons.server()); - setForeground(Theme.serverText()); - setFont(Theme.uiBold()); - } - return this; - } - - /** Friends and blocked clients stand out by colour, as in TeamSpeak, unless turned off. */ - private Color contactColor(Contact contact) { - if (contact == null || !settings.colorContacts) return Theme.treeText(); - switch (contact.type) { - case FRIEND: - return Theme.friend(); - case BLOCKED: - return Theme.blocked(); - default: - return Theme.treeText(); - } - } - - private ImageIcon iconFor(ChannelNode c) { - if (c.hasPassword) return Icons.channelLocked(c.subscribed); - if (c.maxClients >= 0 && c.clients.size() >= c.maxClients) return Icons.channelFull(c.subscribed); - return Icons.channel(c.subscribed); - } - - private ImageIcon iconFor(ClientEntry cl) { - return switch (ClientStatus.of(cl)) { - case QUERY -> Icons.clientQuery(); - case SPEAKERS_DISABLED -> Icons.speakerDisabled(); - case SPEAKERS_MUTED -> Icons.speakerMuted(); - case MIC_DISABLED -> Icons.micDisabled(); - case MIC_MUTED -> Icons.micMuted(); - case AWAY -> Icons.clientAway(); - case COMMANDER_TALKING -> Icons.clientCommanderTalking(); - case COMMANDER -> Icons.clientCommander(); - case TALKING -> Icons.clientTalking(); - case IDLE -> Icons.clientIdle(); - }; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTreeDragAndDrop.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTreeDragAndDrop.java deleted file mode 100644 index 9489b0b..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTreeDragAndDrop.java +++ /dev/null @@ -1,236 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.net.ChannelNode; -import com.ts3client.net.Spacers; -import com.ts3client.net.ClientEntry; -import com.ts3client.net.ServerModel; -import com.ts3client.text.TsLink; - -import javax.swing.JComponent; -import javax.swing.JTree; -import javax.swing.TransferHandler; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreePath; -import java.awt.datatransfer.DataFlavor; -import java.awt.datatransfer.Transferable; -import java.awt.datatransfer.UnsupportedFlavorException; -import java.util.function.Function; - -/** - * Drag-and-drop for the {@link ServerTreePanel} tree: dragging a client onto a - * channel moves it there, dragging a channel reorders/reparents it, and dropping - * either outside the tree yields its TS3 link BBCode, which the chat input accepts - * as plain text. - */ -final class ServerTreeDragAndDrop { - - /** Carries the dragged node inside this JVM; drops elsewhere get the BBCode text. */ - private static final DataFlavor NODE_FLAVOR = new DataFlavor( - DataFlavor.javaJVMLocalObjectMimeType + ";class=java.lang.Object", - "TeamSpeak tree node"); - - private final ServerModel model; - private final ServerTreePanel.Actions actions; - private final DropIndicatorTree tree; - /** Looks up the tree path currently showing a given channel/client, or {@code null}. */ - private final Function pathOf; - - ServerTreeDragAndDrop(ServerModel model, ServerTreePanel.Actions actions, DropIndicatorTree tree, - Function pathOf) { - this.model = model; - this.actions = actions; - this.tree = tree; - this.pathOf = pathOf; - } - - TransferHandler transferHandler() { - return new TreeTransferHandler(); - } - - private static DefaultMutableTreeNode nodeOf(TreePath path) { - return path == null ? null : (DefaultMutableTreeNode) path.getLastPathComponent(); - } - - /** - * The channel a dragged client would land in, or {@code null} if the drop makes - * no sense (outside a channel, or the channel the client is already in). - */ - private ChannelNode resolveClientDrop(JTree.DropLocation loc, ClientEntry dragged) { - DefaultMutableTreeNode target = nodeOf(loc.getPath()); - if (target == null) return null; - Object obj = target.getUserObject(); - ChannelNode channel = null; - if (obj instanceof ChannelNode) { - channel = (ChannelNode) obj; - } else if (obj instanceof ClientEntry) { - channel = model.getChannel(((ClientEntry) obj).channelId); - } - if (channel == null || Spacers.isSpacer(channel.name)) return null; - if (channel.id == dragged.channelId) return null; - return channel; - } - - /** - * The new parent and predecessor for a dragged channel as {@code {cpid, order}}, - * or {@code null} if this drop is not a legal (or meaningful) move. - */ - private int[] resolveChannelDrop(JTree.DropLocation loc, ChannelNode dragged) { - DefaultMutableTreeNode target = nodeOf(loc.getPath()); - if (target == null) return null; - - DefaultMutableTreeNode parentNode; - int insertIndex; - if (loc.getChildIndex() >= 0) { - parentNode = target; - insertIndex = loc.getChildIndex(); - } else { - // Dropped onto a node: become its last subchannel. - parentNode = target.getUserObject() instanceof ClientEntry - ? (DefaultMutableTreeNode) target.getParent() : target; - if (parentNode == null) return null; - insertIndex = parentNode.getChildCount(); - } - - int parentId = 0; - Object parentObj = parentNode.getUserObject(); - if (parentObj instanceof ChannelNode) { - ChannelNode parent = (ChannelNode) parentObj; - if (Spacers.isSpacer(parent.name)) return null; - if (isSelfOrDescendant(parent, dragged)) return null; // would detach the subtree - parentId = parent.id; - } else if (parentNode.getParent() != null) { - return null; - } - - int predecessorId = 0; - for (int i = 0; i < insertIndex && i < parentNode.getChildCount(); i++) { - Object o = ((DefaultMutableTreeNode) parentNode.getChildAt(i)).getUserObject(); - if (o instanceof ChannelNode && ((ChannelNode) o).id != dragged.id) { - predecessorId = ((ChannelNode) o).id; - } - } - if (parentId == dragged.parentId && predecessorId == dragged.order) return null; // no-op - return new int[]{parentId, predecessorId}; - } - - /** Whether {@code candidate} is {@code ancestor} itself or sits below it. */ - private boolean isSelfOrDescendant(ChannelNode candidate, ChannelNode ancestor) { - ChannelNode c = candidate; - for (int guard = 0; c != null && guard < 64; guard++) { - if (c.id == ancestor.id) return true; - c = model.getChannel(c.parentId); - } - return false; - } - - private final class TreeTransferHandler extends TransferHandler { - @Override - public int getSourceActions(JComponent c) { - return COPY | MOVE; - } - - @Override - protected Transferable createTransferable(JComponent c) { - TreePath path = tree.getSelectionPath(); - if (path == null) return null; - Object obj = nodeOf(path).getUserObject(); - if (obj instanceof ClientEntry) { - ClientEntry cl = (ClientEntry) obj; - return new NodeTransferable(cl, TsLink.clientBBCode(cl.id, cl.uniqueId, cl.nickname)); - } - if (obj instanceof ChannelNode) { - ChannelNode ch = (ChannelNode) obj; - // Spacers have no meaningful link text, but can still be re-ordered. - return new NodeTransferable(ch, Spacers.isSpacer(ch.name) - ? null : TsLink.channelBBCode(ch.id, ch.name)); - } - return null; - } - - @Override - public boolean canImport(TransferSupport support) { - if (!support.isDrop() || !support.isDataFlavorSupported(NODE_FLAVOR)) { - tree.highlightChannel(null); - return false; - } - if ((support.getSourceDropActions() & MOVE) == MOVE) support.setDropAction(MOVE); - Object resolved = resolve(support); - // A client always lands *inside* a channel, so mark that channel instead of - // drawing a line that would suggest a position among its clients. - tree.highlightChannel(resolved instanceof ChannelNode - ? pathOf.apply(resolved) : null); - // The indicator spans the full width, past the row rectangles Swing - // repaints on its own when the drop location moves. - tree.repaint(); - return resolved != null; - } - - @Override - protected void exportDone(JComponent source, Transferable data, int action) { - tree.highlightChannel(null); - tree.repaint(); - } - - @Override - public boolean importData(TransferSupport support) { - if (!canImport(support)) return false; - Object dragged = draggedNode(support); - Object resolved = resolve(support); - tree.highlightChannel(null); - if (dragged instanceof ClientEntry) { - actions.moveClientToChannel((ClientEntry) dragged, (ChannelNode) resolved); - } else if (dragged instanceof ChannelNode) { - int[] place = (int[]) resolved; - actions.moveChannel((ChannelNode) dragged, place[0], place[1]); - } - return true; - } - - /** The destination for this drop: a ChannelNode, an {@code {cpid, order}} pair, or null. */ - private Object resolve(TransferSupport support) { - Object dragged = draggedNode(support); - if (!(support.getDropLocation() instanceof JTree.DropLocation)) return null; - JTree.DropLocation loc = (JTree.DropLocation) support.getDropLocation(); - if (dragged instanceof ClientEntry) return resolveClientDrop(loc, (ClientEntry) dragged); - if (dragged instanceof ChannelNode) return resolveChannelDrop(loc, (ChannelNode) dragged); - return null; - } - - private Object draggedNode(TransferSupport support) { - try { - return support.getTransferable().getTransferData(NODE_FLAVOR); - } catch (Exception e) { - return null; - } - } - } - - /** Offers the dragged node locally and its TS3 link BBCode to other applications. */ - private static final class NodeTransferable implements Transferable { - private final Object node; - private final String text; - - NodeTransferable(Object node, String text) { - this.node = node; - this.text = text; - } - - @Override - public DataFlavor[] getTransferDataFlavors() { - return text == null ? new DataFlavor[]{NODE_FLAVOR} - : new DataFlavor[]{NODE_FLAVOR, DataFlavor.stringFlavor}; - } - - @Override - public boolean isDataFlavorSupported(DataFlavor flavor) { - return NODE_FLAVOR.equals(flavor) || (text != null && DataFlavor.stringFlavor.equals(flavor)); - } - - @Override - public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException { - if (NODE_FLAVOR.equals(flavor)) return node; - if (text != null && DataFlavor.stringFlavor.equals(flavor)) return text; - throw new UnsupportedFlavorException(flavor); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTreePanel.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTreePanel.java deleted file mode 100644 index 0fdfb33..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTreePanel.java +++ /dev/null @@ -1,493 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.config.Settings; -import com.ts3client.contacts.ContactStore; -import com.ts3client.contacts.ContactType; -import com.ts3client.net.ChannelNode; -import com.ts3client.net.Spacers; -import com.ts3client.net.ChannelSettings; -import com.ts3client.net.ClientEntry; -import com.ts3client.net.Group; -import com.ts3client.net.ServerModel; - -import javax.swing.AbstractAction; -import javax.swing.DropMode; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JViewport; -import javax.swing.KeyStroke; -import javax.swing.SwingUtilities; -import javax.swing.plaf.basic.BasicTreeUI; -import javax.swing.event.TreeExpansionEvent; -import javax.swing.event.TreeExpansionListener; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.TreePath; -import java.awt.BorderLayout; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * The server view: a tree of channels each containing its clients, styled to - * resemble the TeamSpeak 3 client. Talk state colours clients green live. - */ -public final class ServerTreePanel extends JPanel { - - /** Actions the tree can request of the controller. */ - public interface Actions { - void joinChannel(int channelId); - - void openPrivateChat(ClientEntry client); - - void pokeClient(ClientEntry client); - - void complainAboutClient(ClientEntry client); - - void kickClientFromChannel(ClientEntry client); - - void kickClientFromServer(ClientEntry client); - - void banClient(ClientEntry client); - - void toggleClientMute(ClientEntry client); - - void showConnectionInfo(ClientEntry client); - - /** Moves a client into the channel we are currently in. */ - void moveClientToOwnChannel(ClientEntry client); - - /** Opens the channel editor for a channel. */ - void editChannel(ChannelNode channel); - - void deleteChannel(ChannelNode channel); - - /** - * Opens the channel creator. - * - * @param parent the channel the new one goes below, or {@code null} for a top-level one - * @param type the channel type to start with - */ - void createChannel(ChannelNode parent, ChannelSettings.Type type); - - /** Opens the channel creator pre-filled as a spacer, which is always top-level. */ - void createSpacer(); - - /** Whether the server is there to act on at all. */ - boolean isConnected(); - - /** Open the file repository browser for a channel. */ - void browseFiles(ChannelNode channel); - - /** - * Changes a channel's subscription. - * - * @param family whether the channels below it are included - */ - void setChannelSubscribed(ChannelNode channel, boolean family, boolean subscribed); - - boolean isClientLocallyMuted(int clientId); - - /** Selects and scrolls to a client in the tree, e.g. from a chat/log link. */ - void findClientInTree(ClientEntry client); - - /** A channel or client node was selected (or {@code null} when cleared). */ - void onSelectionChanged(Object userObject); - - /** Drag-and-drop of a client onto a channel. */ - void moveClientToChannel(ClientEntry client, ChannelNode target); - - /** - * Drag-and-drop of a channel to a new place in the tree. - * - * @param orderPredecessorId the channel it should sit below among its new - * siblings, or 0 to place it first - */ - void moveChannel(ChannelNode channel, int newParentId, int orderPredecessorId); - - /** Assigns or removes a server group for a client. */ - void setClientServerGroup(ClientEntry client, Group group, boolean assign); - - /** Assigns a channel group for a client in its current channel. */ - void setClientChannelGroup(ClientEntry client, Group group); - - /** Opens the full server-groups list dialog for a client. */ - void showServerGroupsDialog(ClientEntry client); - - /** Edits a client's description — our own included. */ - void changeClientDescription(ClientEntry client); - - /** Whether we may delete other clients' avatars. */ - boolean canDeleteOtherAvatars(); - - void deleteClientAvatar(ClientEntry client); - - /** A new nickname for ourselves, typed into the tree row. */ - void renameSelf(String nickname); - - /** Files a client in the contact list as a friend, blocked or neutral. */ - void addContact(ClientEntry client, ContactType type); - - /** Opens the contact list at this client's entry. */ - void editContact(ClientEntry client); - - void removeContact(ClientEntry client); - - /** The type a client is filed under, or {@code null} for a client that is no contact. */ - ContactType contactTypeOf(ClientEntry client); - - /** Opens the per-client volume dialog. */ - void changeClientVolume(ClientEntry client); - } - - private final DropIndicatorTree tree; - private final JScrollPane scroll = new JScrollPane() { - @Override - public void updateUI() { - super.updateUI(); - // The rows stop at the last channel, so the space below them belongs to the tree - // rather than to the window behind it. - if (getViewport() != null) getViewport().setBackground(Theme.treeBg()); - } - }; - private final ServerTreeSearch search; - private final DefaultMutableTreeNode root = new DefaultMutableTreeNode(); - /** - * The nodes only mirror the connection's model, so an edited row is not written - * back into the tree: the new nickname goes to the server, and the row follows - * once it reports the rename. - */ - private final DefaultTreeModel treeModel = new DefaultTreeModel(root) { - @Override - public void valueForPathChanged(TreePath path, Object newValue) { - String nickname = String.valueOf(newValue).trim(); - Object edited = ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); - // The server answers a rename to the name already held with "nickname is - // already in use", so a field closed unchanged is simply left alone. - if (edited instanceof ClientEntry && nickname.equals(((ClientEntry) edited).nickname)) return; - if (!nickname.isEmpty()) actions.renameSelf(nickname); - } - }; - /** - * True while the tree is changed programmatically: a {@link #rebuild()} clearing and restoring - * the selection, or channels being reopened. The listeners ignore what happens meanwhile. - */ - private boolean rebuilding; - /** Channels the user collapsed; every other channel is shown open. */ - private final Set collapsedChannels = new HashSet<>(); - private final ServerModel model; - private final GroupIcons groupIcons; - private final Actions actions; - private final NicknameCellEditor nicknameEditor; - private int selfClientId = -1; - - public ServerTreePanel(ServerModel model, GroupIcons groupIcons, ContactStore contacts, Settings settings, - Actions actions) { - super(new BorderLayout()); - this.model = model; - this.groupIcons = groupIcons; - this.actions = actions; - root.setUserObject("Not connected"); - this.tree = new DropIndicatorTree(treeModel, model, groupIcons, settings); - tree.setRootVisible(true); - // The server node is the only top-level row and always stays open, so it gets - // no expand control. Nesting is tightened too: horizontal space in this view - // is scarce and channel names are long. - tree.setShowsRootHandles(false); - // Double-click joins a channel; expanding is left to the handles and the keyboard. - tree.setToggleClickCount(0); - if (tree.getUI() instanceof BasicTreeUI) { - BasicTreeUI ui = (BasicTreeUI) tree.getUI(); - ui.setLeftChildIndent(4); - ui.setRightChildIndent(10); - } - tree.setRowHeight(UIScale.scale(20)); - // Lays out only the rows on screen. The default cache measures every row as it is - // expanded, which freezes the window for seconds on servers with hundreds of channels. - tree.setLargeModel(true); - tree.setBackground(Theme.treeBg()); - tree.setFont(Theme.uiFont()); - ServerTreeCellRenderer renderer = new ServerTreeCellRenderer(id -> id == selfClientId, contacts, settings); - tree.setCellRenderer(renderer); - nicknameEditor = NicknameCellEditor.create(tree, renderer, id -> id == selfClientId); - tree.setCellEditor(nicknameEditor); - tree.setEditable(true); - tree.setPathEditable(nicknameEditor::editsPath); - tree.setInvokesStopCellEditing(true); - scroll.setViewportView(tree); - // The icon strip is drawn against the viewport's right edge, so the blitted - // pixels a scroll would reuse are stale; repaint the whole viewport instead. - scroll.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE); - // Scrolling slides the rows past a pointer that has not moved, so the outlined - // row has to be worked out again. - scroll.getViewport().addChangeListener(e -> tree.refreshHoverRow()); - scroll.getViewport().setBackground(Theme.treeBg()); - add(scroll, BorderLayout.CENTER); - - search = new ServerTreeSearch(tree, root, contacts, this::rebuild); - add(search.bar(), BorderLayout.SOUTH); - String find = "ts3-tree-find"; - getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("control F"), find); - getActionMap().put(find, new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - openFind(); - } - }); - - // Within the tree a drag moves the client or channel; dropped elsewhere it - // yields the TS3 link BBCode, which the chat input accepts as plain text. - tree.setDragEnabled(true); - tree.setDropMode(DropMode.ON_OR_INSERT); - tree.setTransferHandler(new ServerTreeDragAndDrop(model, actions, tree, this::pathOf).transferHandler()); - - tree.addTreeExpansionListener(new TreeExpansionListener() { - @Override - public void treeCollapsed(TreeExpansionEvent e) { - if (rebuilding) return; - Object obj = ((DefaultMutableTreeNode) e.getPath().getLastPathComponent()).getUserObject(); - if (obj instanceof ChannelNode) collapsedChannels.add(((ChannelNode) obj).id); - } - - @Override - public void treeExpanded(TreeExpansionEvent e) { - if (rebuilding) return; - DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent(); - if (!(node.getUserObject() instanceof ChannelNode)) return; - collapsedChannels.remove(((ChannelNode) node.getUserObject()).id); - // A rebuild while it was shut left everything below it shut too. - rebuilding = true; - try { - expandOpenChannels(node, e.getPath()); - } finally { - rebuilding = false; - } - } - }); - - tree.addTreeSelectionListener(e -> { - if (rebuilding) return; - TreePath path = tree.getSelectionPath(); - Object obj = null; - if (path != null) { - obj = ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); - } - actions.onSelectionChanged(obj); - }); - - tree.addMouseListener(new MouseAdapter() { - @Override - public void mousePressed(MouseEvent e) { - selectRowUnder(e); - maybePopup(e); - } - - @Override - public void mouseReleased(MouseEvent e) { - maybePopup(e); - } - - @Override - public void mouseClicked(MouseEvent e) { - Object obj = nodeAt(e); - if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) { - if (obj instanceof ChannelNode && !Spacers.isSpacer(((ChannelNode) obj).name)) { - actions.joinChannel(((ChannelNode) obj).id); - } else if (obj instanceof ClientEntry) { - if (((ClientEntry) obj).id == selfClientId) { - tree.startEditingAtPath(tree.pathAt(e.getY())); - } else { - actions.openPrivateChat((ClientEntry) obj); - } - } - } else if (SwingUtilities.isMiddleMouseButton(e) && obj instanceof ClientEntry) { - actions.showConnectionInfo((ClientEntry) obj); - } - } - }); - } - - /** - * Selects the row a press landed on. A row acts on its whole line, but Swing's own - * hit testing stops at the end of the label, so a press further right would leave - * the selection where it was. - */ - private void selectRowUnder(MouseEvent e) { - if (!SwingUtilities.isLeftMouseButton(e) && !e.isPopupTrigger()) return; - TreePath path = tree.pathAt(e.getY()); - if (path == null || path.equals(tree.getSelectionPath())) return; - Rectangle bounds = tree.getPathBounds(path); - // Left of the label is the expand handle, which Swing works the row without selecting it. - if (bounds != null && e.getX() < bounds.x) return; - tree.setSelectionPath(path); - } - - /** Opens the find bar above the tree. */ - public void openFind() { - search.open(); - } - - public void setSelfClientId(int id) { - this.selfClientId = id; - } - - /** Selects and scrolls to the row showing {@code client}, if it is currently visible. */ - public void selectClient(int clientId) { - ClientEntry client = model.getClient(clientId); - if (client == null) return; - TreePath path = pathOf(client); - if (path == null) return; - tree.setSelectionPath(path); - tree.scrollPathToVisible(path); - } - - private Object nodeAt(MouseEvent e) { - TreePath path = tree.pathAt(e.getY()); - if (path == null) return null; - DefaultMutableTreeNode n = (DefaultMutableTreeNode) path.getLastPathComponent(); - return n.getUserObject(); - } - - private void maybePopup(MouseEvent e) { - if (!e.isPopupTrigger()) return; - TreePath path = tree.pathAt(e.getY()); - if (path == null) return; - tree.setSelectionPath(path); - Object obj = ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); - if (obj instanceof ClientEntry) { - showClientMenu((ClientEntry) obj, e); - } else if (obj instanceof ChannelNode) { - showChannelMenu((ChannelNode) obj, e); - } else if (path.getPathCount() == 1 && actions.isConnected()) { - // The root row is the server itself, whose user object is just its name. - ServerMenu.build(actions).show(tree, e.getX(), e.getY()); - } - } - - private void showClientMenu(ClientEntry client, MouseEvent e) { - ClientMenu.build(client, client.id == selfClientId, true, model, groupIcons, actions) - .show(tree, e.getX(), e.getY()); - } - - private void showChannelMenu(ChannelNode channel, MouseEvent e) { - if (Spacers.isSpacer(channel.name)) return; // spacers aren't interactive - ChannelMenu.build(channel, actions).show(tree, e.getX(), e.getY()); - } - - /** The path of the tree node showing {@code target}, or {@code null}. */ - private TreePath pathOf(Object target) { - java.util.Enumeration nodes = root.breadthFirstEnumeration(); - while (nodes.hasMoreElements()) { - DefaultMutableTreeNode n = (DefaultMutableTreeNode) nodes.nextElement(); - if (n.getUserObject() == target) return new TreePath(n.getPath()); - } - return null; - } - - /** - * Rebuilds the tree from the model, preserving full expansion. Rebuilding - * replaces every tree node, which would otherwise drop the current - * selection on every update (a client talking, a group change, …); the - * previously selected channel/client is restored by identity once the new - * nodes are in place, so a selection sticks until the user changes it. - */ - public void rebuild() { - Object selected = selectedUserObject(); - rebuilding = true; - try { - root.setUserObject(model.getServerName()); - root.removeAllChildren(); - List roots = model.buildTree(); - boolean filtering = search.isFiltering(); - for (ChannelNode c : roots) { - DefaultMutableTreeNode node = buildChannel(c, filtering); - if (node != null) root.add(node); - } - treeModel.reload(); - expandOpenChannels(root, new TreePath(root)); - if (selected != null) { - TreePath path = pathOf(selected); - if (path != null) tree.setSelectionPath(path); - } - } finally { - rebuilding = false; - } - // The selection listener was swallowed above; tell the caller only if it actually changed - // (e.g. the previously selected channel/client is gone), since it already knows the rest. - Object nowSelected = selectedUserObject(); - if (nowSelected != selected) actions.onSelectionChanged(nowSelected); - search.treeRebuilt(); - } - - /** - * Opens {@code node} and every channel below it, except the ones the user collapsed and - * whatever is below those. While the find bar filters, everything opens, so every match shows. - */ - private void expandOpenChannels(DefaultMutableTreeNode node, TreePath path) { - tree.expandPath(path); - boolean filtering = search.isFiltering(); - for (int i = 0; i < node.getChildCount(); i++) { - DefaultMutableTreeNode child = (DefaultMutableTreeNode) node.getChildAt(i); - if (child.isLeaf() || !(child.getUserObject() instanceof ChannelNode)) continue; - if (!filtering && collapsedChannels.contains(((ChannelNode) child.getUserObject()).id)) continue; - expandOpenChannels(child, path.pathByAddingChild(child)); - } - } - - private Object selectedUserObject() { - TreePath path = tree.getSelectionPath(); - return path == null ? null : ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); - } - - /** - * @param filtering keep only what the find bar matched: a matching channel with its - * clients, a matching client, and the channels leading to either - * @return the channel's node, or {@code null} when filtering left nothing of it - */ - private DefaultMutableTreeNode buildChannel(ChannelNode c, boolean filtering) { - DefaultMutableTreeNode node = new DefaultMutableTreeNode(c); - boolean channelMatches = filtering && search.matches(c); - for (ClientEntry client : c.clients) { - if (!filtering || channelMatches || search.matches(client)) node.add(new DefaultMutableTreeNode(client)); - } - for (ChannelNode child : c.children) { - DefaultMutableTreeNode childNode = buildChannel(child, filtering); - if (childNode != null) node.add(childNode); - } - return !filtering || channelMatches || node.getChildCount() > 0 ? node : null; - } - - /** Clears the tree back to the disconnected placeholder state. */ - public void showDisconnected() { - root.setUserObject("Not connected"); - root.removeAllChildren(); - collapsedChannels.clear(); - treeModel.reload(); - search.treeRebuilt(); - } - - /** Repaint only (e.g. talk-state changes) without rebuilding structure. */ - public void refreshVisual() { - tree.repaint(); - } - - /** - * Re-measures every visible row, for changes that alter a row's width (a group - * icon that finished downloading). A plain repaint would keep the cached widths - * and clip the new icons. - */ - public void refreshRowSizes() { - for (int i = tree.getRowCount() - 1; i >= 0; i--) { - TreePath path = tree.getPathForRow(i); - if (path != null) { - treeModel.nodeChanged((DefaultMutableTreeNode) path.getLastPathComponent()); - } - } - } - -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTreeSearch.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTreeSearch.java deleted file mode 100644 index 9ff0032..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTreeSearch.java +++ /dev/null @@ -1,233 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.contacts.Contact; -import com.ts3client.contacts.ContactStore; -import com.ts3client.net.ChannelNode; -import com.ts3client.net.ClientEntry; -import com.ts3client.net.TreeMatch; -import com.ts3client.text.TextQuery; - -import javax.swing.Icon; -import javax.swing.JButton; -import javax.swing.JToggleButton; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreePath; -import java.awt.Dimension; -import java.awt.Insets; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Set; - -/** - * Find in the server tree: looks for clients or for channels by name, washes every - * matching row and selects them one at a time. Optionally prunes the tree down to - * the matches (and the channels leading to them). - */ -final class ServerTreeSearch implements FindBar.Listener { - - private final DropIndicatorTree tree; - private final DefaultMutableTreeNode root; - private final ContactStore contacts; - /** Rebuilds the tree, which asks {@link #isFiltering()} and {@link #matches} what to keep. */ - private final Runnable rebuild; - - private final FindBar bar = new FindBar(this); - private boolean searchChannels; - /** Switches between finding clients and finding channels, showing the kind it finds. */ - private final JButton scope = new JButton() { - @Override - public Icon getIcon() { - return searchChannels ? Icons.channel(true) : Icons.clientIdle(); - } - - /** Sized for the wider of both icons, so the field beside it stays put on a switch. */ - @Override - public Dimension getPreferredSize() { - Icon client = Icons.clientIdle(); - Icon channel = Icons.channel(true); - Insets in = getInsets(); - return new Dimension(Math.max(client.getIconWidth(), channel.getIconWidth()) + in.left + in.right, - Math.max(client.getIconHeight(), channel.getIconHeight()) + in.top + in.bottom); - } - - @Override - public Dimension getMaximumSize() { - return getPreferredSize(); - } - }; - private final JToggleButton onlyMatching; - - private TextQuery query = TextQuery.EMPTY; - private boolean filtering; - /** Matching rows in tree order. */ - private final List hits = new ArrayList<>(); - - ServerTreeSearch(DropIndicatorTree tree, DefaultMutableTreeNode root, ContactStore contacts, Runnable rebuild) { - this.tree = tree; - this.root = root; - this.contacts = contacts; - this.rebuild = rebuild; - scope.addActionListener(e -> { - searchChannels = !searchChannels; - scopeChanged(); - }); - bar.addLeading(scope); - onlyMatching = bar.addFilterToggle("Show only matches"); - bar.addResettable(() -> !searchChannels, () -> { - searchChannels = false; - showScope(); - }); - showScope(); - } - - FindBar bar() { - return bar; - } - - void open() { - bar.open(); - } - - /** Whether the tree should hold only matches and the channels leading to them. */ - boolean isFiltering() { - return filtering; - } - - /** Whether a channel or client row matches the current query in the current scope. */ - boolean matches(Object node) { - if (query.isEmpty()) return false; - if (node instanceof ClientEntry c) { - if (searchChannels) return false; - Contact contact = contacts.find(c.uniqueId); - return TreeMatch.client(query, c.nickname, contact != null ? contact.displayName(c.nickname) : null); - } - if (node instanceof ChannelNode ch) return searchChannels && TreeMatch.channel(query, ch.name); - return false; - } - - /** The tree was rebuilt from the model: its rows (and so the matches) may have changed. */ - void treeRebuilt() { - if (!bar.isOpen()) return; - collectHits(); - updateStatus(); - } - - private void scopeChanged() { - showScope(); - if (bar.isOpen()) bar.fireQueryChanged(); - } - - private void showScope() { - scope.setToolTipText(searchChannels ? "Finding channels — click to find clients" - : "Finding clients — click to find channels"); - scope.repaint(); - bar.setPlaceholder(searchChannels ? "Find channels" : "Find clients"); - } - - @Override - public void queryChanged(TextQuery q) { - query = q.isInvalid() ? TextQuery.EMPTY : q; - boolean filter = onlyMatching.isSelected() && !query.isEmpty(); - if (filter || filtering) { - filtering = filter; - rebuild.run(); - } - collectHits(); - if (!hits.isEmpty()) select(hits.get(0)); - updateStatus(); - } - - @Override - public void next() { - step(true); - } - - @Override - public void previous() { - step(false); - } - - @Override - public void closed() { - query = TextQuery.EMPTY; - hits.clear(); - tree.setSearchHits(Collections.emptySet()); - if (filtering) { - filtering = false; - rebuild.run(); - } - TreePath selected = tree.getSelectionPath(); - if (selected != null) tree.scrollPathToVisible(selected); - tree.requestFocusInWindow(); - } - - /** Moves to the match after (or before) the selected row, wrapping around. */ - private void step(boolean forward) { - if (hits.isEmpty()) return; - List order = preorder(); - int at = order.indexOf(selectedNode()); - DefaultMutableTreeNode target = null; - if (forward) { - for (DefaultMutableTreeNode hit : hits) { - if (order.indexOf(hit) > at) { - target = hit; - break; - } - } - if (target == null) target = hits.get(0); - } else { - for (int i = hits.size() - 1; i >= 0; i--) { - if (at < 0 || order.indexOf(hits.get(i)) < at) { - target = hits.get(i); - break; - } - } - if (target == null) target = hits.get(hits.size() - 1); - } - select(target); - updateStatus(); - } - - private void select(DefaultMutableTreeNode node) { - TreePath path = new TreePath(node.getPath()); - tree.setSelectionPath(path); - tree.scrollPathToVisible(path); - } - - private void collectHits() { - hits.clear(); - Set washed = Collections.newSetFromMap(new IdentityHashMap<>()); - for (DefaultMutableTreeNode n : preorder()) { - if (matches(n.getUserObject())) { - hits.add(n); - washed.add(n.getUserObject()); - } - } - tree.setSearchHits(washed); - } - - private void updateStatus() { - if (query.isEmpty()) { - if (!bar.query().isInvalid()) bar.clearCount(); - bar.setNavigable(false); - return; - } - bar.setNavigable(hits.size() > 1 || (hits.size() == 1 && hits.get(0) != selectedNode())); - bar.setCount(hits.indexOf(selectedNode()) + 1, hits.size(), false); - } - - private DefaultMutableTreeNode selectedNode() { - TreePath path = tree.getSelectionPath(); - return path == null ? null : (DefaultMutableTreeNode) path.getLastPathComponent(); - } - - private List preorder() { - List out = new ArrayList<>(); - Enumeration e = root.preorderEnumeration(); - while (e.hasMoreElements()) out.add((DefaultMutableTreeNode) e.nextElement()); - return out; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/SettingsDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/SettingsDialog.java deleted file mode 100644 index 2cf3b47..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/SettingsDialog.java +++ /dev/null @@ -1,224 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.audio.AudioBackend; -import com.ts3client.audio.OpusParameters; -import com.ts3client.audio.VoiceInput; -import com.ts3client.audio.VoiceOutput; -import com.ts3client.config.Settings; -import com.ts3client.sound.SoundNotifier; - -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.ScrollPaneConstants; -import javax.swing.SwingUtilities; -import java.awt.BorderLayout; -import java.awt.CardLayout; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.Frame; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.List; - -/** - * Options dialog, laid out like TS3's: a sidebar of pages on the left, the chosen page - * on the right, OK/Cancel/Apply below. Each page owns its controls and - * writes {@link Settings} when applied; this class wires the audio pages, which preview - * themselves live against the running audio subsystem, and owns the apply plumbing. - */ -public final class SettingsDialog extends JDialog { - - /** The page the dialog was last left on, to reopen there. */ - private static int lastPage; - - private final Settings settings; - private final VoiceOutput livePlayback; - private final Runnable onApply; - - private final ApplicationPanel applicationPanel; - private final PlaybackPanel playbackPanel; - private final CapturePanel capturePanel; - private final NetworkPanel networkPanel; - private final NotificationsPanel notificationsPanel; - private final DesignPanel designPanel; - private final HotkeysPanel hotkeysPanel; - private final ContactsPanel contactsPanel; - private final ChatLogsPanel chatLogsPanel; - - public SettingsDialog(Frame owner, Settings settings, AudioBackend audio, - VoiceInput liveMic, VoiceOutput livePlayback, - SoundNotifier sounds, HotkeyService hotkeys, MyTeamSpeakPanel myTeamSpeak, - Runnable onApply) { - super(owner, "Options", true); - this.settings = settings; - this.livePlayback = livePlayback; - this.onApply = onApply; - - applicationPanel = new ApplicationPanel(settings); - hotkeysPanel = new HotkeysPanel(hotkeys); - Runnable pushEncoder = () -> { - if (liveMic != null) liveMic.setOpusParameters(OpusParameters.from(audioSnapshot())); - }; - capturePanel = new CapturePanel(settings, audio, liveMic, hotkeys, hotkeysPanel, this::audioSnapshot); - networkPanel = new NetworkPanel(settings, liveMic, pushEncoder); - playbackPanel = new PlaybackPanel(settings, audio.io(), livePlayback, sounds, - capturePanel::setTestOutputDevice); - notificationsPanel = new NotificationsPanel(settings, sounds); - designPanel = new DesignPanel(settings); - contactsPanel = new ContactsPanel(settings); - chatLogsPanel = new ChatLogsPanel(settings); - - List pages = List.of( - new OptionsPage("Application", scrollable(applicationPanel), "SETTINGS"), - new OptionsPage("myTeamSpeak", myTeamSpeak, "MYTS_ACCOUNT"), - new OptionsPage("Playback", scrollable(playbackPanel), "PLAYBACK"), - new OptionsPage("Capture", scrollable(capturePanel), "CAPTURE"), - new OptionsPage("Network", scrollable(networkPanel), "PING_4"), - new OptionsPage("Design", designPanel, "GUISETUP", "CHANNEL_EDIT"), - new OptionsPage("Hotkeys", hotkeysPanel, "HOTKEYS"), - new OptionsPage("Contacts", scrollable(contactsPanel), "CONTACT", "EDIT_FRIEND_FOE_STATUS"), - new OptionsPage("Chat", scrollable(chatLogsPanel), "CHANNEL_CHAT", "PLAYER_CHAT"), - new OptionsPage("Notifications", notificationsPanel, "NOTIFICATIONS")); - - CardLayout cards = new CardLayout(); - JPanel content = new JPanel(cards); - for (OptionsPage page : pages) content.add(page.content(), page.title()); - - OptionsSidebar sidebar = new OptionsSidebar(pages); - sidebar.addListSelectionListener(e -> { - OptionsPage page = sidebar.getSelectedValue(); - if (page == null) return; - cards.show(content, page.title()); - lastPage = sidebar.getSelectedIndex(); - }); - sidebar.setSelectedIndex(Math.min(lastPage, pages.size() - 1)); - JScrollPane sidebarScroll = new JScrollPane(sidebar, - ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); - - JPanel body = new JPanel(new BorderLayout(UIScale.scale(8), 0)); - body.setBorder(new ScaledEmptyBorder(10, 10, 0, 10)); - body.add(sidebarScroll, BorderLayout.WEST); - body.add(content, BorderLayout.CENTER); - - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(body, BorderLayout.CENTER); - getContentPane().add(buildButtons(), BorderLayout.SOUTH); - - Runnable iconsChanged = () -> SwingUtilities.invokeLater(sidebar::repaint); - IconTheme.get().addListener(iconsChanged); - - // The microphone test hears typing too, so typing attenuation can be tried out here. - Runnable testKeyPress = () -> SwingUtilities.invokeLater( - () -> capturePanel.applyLive(VoiceInput::keyPressed)); - hotkeys.addKeyPressListener(testKeyPress); - - Dialogs.closeOnEscape(this, this::cancel); - setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); - addWindowListener(new WindowAdapter() { - @Override - public void windowClosing(WindowEvent e) { - cancel(); - } - - @Override - public void windowClosed(WindowEvent e) { - hotkeys.removeKeyPressListener(testKeyPress); - IconTheme.get().removeListener(iconsChanged); - capturePanel.stopTest(); - } - }); - - pack(); - setSize(UIScale.scale(new Dimension(900, 620))); - setMinimumSize(UIScale.scale(new Dimension(640, 440))); - setLocationRelativeTo(owner); - } - - private JComponent buildButtons() { - JButton ok = new JButton("OK"); - JButton cancel = new JButton("Cancel"); - JButton apply = new JButton("Apply"); - ok.addActionListener(e -> { - apply(); - close(); - }); - cancel.addActionListener(e -> cancel()); - apply.addActionListener(e -> apply()); - - JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT, UIScale.scale(6), 0)); - buttons.setBorder(new ScaledEmptyBorder(10, 10, 10, 10)); - buttons.add(ok); - buttons.add(cancel); - buttons.add(apply); - getRootPane().setDefaultButton(ok); - return buttons; - } - - private static JScrollPane scrollable(JPanel content) { - JScrollPane sp = new JScrollPane(content, - ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, - ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); - sp.setBorder(null); - sp.getVerticalScrollBar().setUnitIncrement(16); - return sp; - } - - /** Copies the audio pages into {@code target}, without touching anything else. */ - private void writeAudioSettings(Settings target) { - playbackPanel.writeInto(target); - capturePanel.writeInto(target); - networkPanel.writeInto(target); - } - - /** - * The audio pages as a standalone {@link Settings}, so the microphone test chain runs - * with the values currently on screen rather than the ones last saved. - * - *

    The test always runs voice activation: it exists to tune the gate, and push-to-talk - * would need the global hotkey, which belongs to the connected microphone. - */ - private Settings audioSnapshot() { - Settings snapshot = new Settings(); - snapshot.packetLoss = settings.packetLoss; - writeAudioSettings(snapshot); - if (snapshot.inputMode == Settings.InputMode.PUSH_TO_TALK) { - snapshot.inputMode = Settings.InputMode.VOICE_ACTIVATION; - } - return snapshot; - } - - private void apply() { - writeAudioSettings(settings); - applicationPanel.apply(); - notificationsPanel.apply(); - designPanel.apply(); - contactsPanel.apply(); - chatLogsPanel.apply(); - hotkeysPanel.apply(); - settings.save(); - - capturePanel.applyLive(m -> m.apply(settings)); - if (livePlayback != null) { - livePlayback.setMasterVolume(settings.outputVolume); - livePlayback.setOutputDevice(settings.outputDevice); - } - if (onApply != null) onApply.run(); - } - - /** Leaves without applying, putting back the settings that preview themselves live. */ - private void cancel() { - notificationsPanel.revert(); - designPanel.revert(); - close(); - } - - private void close() { - capturePanel.stopTest(); - dispose(); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/Spinners.java b/ts3-client/swing/src/main/java/com/ts3client/ui/Spinners.java deleted file mode 100644 index 18adbb3..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/Spinners.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.UIScale; - -import javax.swing.JSpinner; -import java.awt.Dimension; - -/** Shared shaping for the numeric spinners the channel editor is full of. */ -final class Spinners { - - /** Width that fits a five-digit power without swallowing the rest of a form row. */ - private static final int WIDTH = 80; - - private Spinners() { - } - - /** - * Keeps a spinner to a sensible width and drops the grouping separator: these hold - * permission powers and client counts, which TeamSpeak shows as plain numbers. - */ - static JSpinner compact(JSpinner spinner) { - JSpinner.NumberEditor editor = new JSpinner.NumberEditor(spinner, "#"); - spinner.setEditor(editor); - Dimension size = new Dimension(UIScale.scale(WIDTH), spinner.getPreferredSize().height); - spinner.setPreferredSize(size); - spinner.setMaximumSize(size); - return spinner; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/StatusBar.java b/ts3-client/swing/src/main/java/com/ts3client/ui/StatusBar.java deleted file mode 100644 index b5d4122..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/StatusBar.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; - -import javax.swing.JLabel; -import javax.swing.JPanel; -import java.awt.BorderLayout; -import java.awt.Cursor; -import java.awt.FlowLayout; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; - -/** - * The strip at the bottom of the window: connection status on the left, codec info on the - * right, and while the server on screen is being recorded, a label that stops it. An envelope - * shows while that server holds unread offline messages for us, and opens them. - */ -final class StatusBar extends JPanel { - - private final JLabel statusLabel = new JLabel("Not connected"); - private final JLabel codecLabel = new JLabel(); - private final JLabel recordingLabel = new JLabel("Recording", Icons.of("RECORDING_STOP"), JLabel.LEADING); - private final JLabel unreadLabel = new JLabel(Icons.of("OFFLINE_MESSAGES")); - - StatusBar(Runnable onStopRecording, Runnable onOpenOfflineMessages) { - super(new BorderLayout()); - setBackground(Theme.statusBg()); - setBorder(new ScaledEmptyBorder(3, 8, 3, 8)); - statusLabel.setFont(Theme.uiFont()); - codecLabel.setFont(Theme.uiFont()); - codecLabel.setForeground(Theme.chatSystem()); - recordingLabel.setFont(Theme.uiFont()); - recordingLabel.setToolTipText("Stop Recording"); - recordingLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - recordingLabel.setVisible(false); - recordingLabel.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - onStopRecording.run(); - } - }); - unreadLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - unreadLabel.setVisible(false); - unreadLabel.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - onOpenOfflineMessages.run(); - } - }); - JPanel east = new JPanel(new FlowLayout(FlowLayout.TRAILING, UIScale.scale(12), 0)); - east.setOpaque(false); - east.add(unreadLabel); - east.add(recordingLabel); - east.add(codecLabel); - // In the centre, a long status is cut short rather than drawn over the labels beside it. - add(statusLabel, BorderLayout.CENTER); - add(east, BorderLayout.EAST); - } - - void showRecording(boolean recording) { - recordingLabel.setVisible(recording); - } - - void showUnreadMessages(int unread) { - unreadLabel.setVisible(unread > 0); - unreadLabel.setToolTipText("

    You have " + unread + " unread " - + (unread == 1 ? "offline message" : "offline messages") + "

    "); - } - - void setStatus(String text) { - statusLabel.setText(text); - } - - void setCodec(String text) { - codecLabel.setText(text); - } - - String codecText() { - return codecLabel.getText(); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/TabDragReorder.java b/ts3-client/swing/src/main/java/com/ts3client/ui/TabDragReorder.java deleted file mode 100644 index 55f475a..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/TabDragReorder.java +++ /dev/null @@ -1,285 +0,0 @@ -package com.ts3client.ui; - -import javax.swing.JComponent; -import javax.swing.JRootPane; -import javax.swing.JTabbedPane; -import javax.swing.SwingUtilities; -import javax.swing.Timer; -import java.awt.AlphaComposite; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.image.BufferedImage; -import java.util.ArrayList; -import java.util.List; - -/** - * Lets the user reorder a {@link JTabbedPane}'s tabs by dragging one sideways over - * another, browser-tab style. Snapshots of every tab are drawn on the window's - * glass pane: the dragged one follows the cursor's X only (its Y stays put, and it - * can't leave the strip) and stays drawn on top; it swaps with whichever neighbour - * it reaches the midpoint of. The real tab model is only updated once, when the - * mouse is released, and the overlay eases into its final position on top of it. - * - *

    Swing delivers drag events only to whichever component originally got the - * press, so every component that should start a drag — the tab strip itself - * and each custom tab label — must be {@link #attach}ed individually. - */ -final class TabDragReorder { - - /** Moves the tab at {@code from} to sit where {@code to} currently is. */ - interface Reorder { - void moveTab(int from, int to); - } - - /** Below this many pixels of movement, a press is treated as a click, not a drag. */ - private static final int THRESHOLD = 5; - private static final double EASE = 0.35; - private static final double SETTLE_EPSILON = 0.5; - private static final int FRAME_MS = 15; - - private final JTabbedPane tabbed; - private final Reorder reorder; - - private int pressSlot = -1; - private Point pressPoint; - private boolean dragging; - private boolean releasing; - - private Overlay overlay; - private List order; - private Tile draggedTile; - private int dragSlot; - private int startSlot; - private int stripStartX; - private int stripWidth; - private int grabDx; - private Timer timer; - - TabDragReorder(JTabbedPane tabbed, Reorder reorder) { - this.tabbed = tabbed; - this.reorder = reorder; - } - - void attach(JComponent source) { - MouseAdapter listener = new MouseAdapter() { - @Override - public void mousePressed(MouseEvent e) { - Point inTabbed = SwingUtilities.convertPoint(e.getComponent(), e.getPoint(), tabbed); - pressSlot = tabbed.indexAtLocation(inTabbed.x, inTabbed.y); - pressPoint = inTabbed; - dragging = false; - } - - @Override - public void mouseDragged(MouseEvent e) { - if (pressSlot < 0) return; - Point inTabbed = SwingUtilities.convertPoint(e.getComponent(), e.getPoint(), tabbed); - if (!dragging) { - if (pressPoint.distance(inTabbed) < THRESHOLD) return; - dragging = beginDrag(inTabbed); - if (!dragging) return; - } - dragTo(inTabbed.x); - } - - @Override - public void mouseReleased(MouseEvent e) { - if (dragging) endDrag(); - // A custom tab component swallows the press, so the tabbed pane never gets - // to select the tab itself — a plain click has to do it here. - else if (pressSlot >= 0 && pressSlot < tabbed.getTabCount() - && SwingUtilities.isLeftMouseButton(e)) { - tabbed.setSelectedIndex(pressSlot); - } - pressSlot = -1; - dragging = false; - } - }; - source.addMouseListener(listener); - source.addMouseMotionListener(listener); - } - - /** Snapshots every tab and shows them on the glass pane in place of the real strip. */ - private boolean beginDrag(Point inTabbed) { - JRootPane root = tabbed.getRootPane(); - int n = tabbed.getTabCount(); - if (root == null || pressSlot < 0 || pressSlot >= n) return false; - - order = new ArrayList<>(n); - for (int i = 0; i < n; i++) { - Rectangle b = tabbed.getBoundsAt(i); - if (b == null || b.isEmpty()) return false; - order.add(new Tile(snapshot(b), b.x, b.y, b.width, b.height)); - } - stripStartX = order.get(0).x; - stripWidth = 0; - for (Tile t : order) stripWidth += t.width; - draggedTile = order.get(pressSlot); - dragSlot = pressSlot; - startSlot = pressSlot; - grabDx = inTabbed.x - draggedTile.x; - releasing = false; - - if (!(root.getGlassPane() instanceof Overlay)) { - root.setGlassPane(new Overlay()); - } - overlay = (Overlay) root.getGlassPane(); - overlay.origin = SwingUtilities.convertPoint(tabbed, new Point(0, 0), overlay); - overlay.tiles = order; - overlay.onTop = draggedTile; - overlay.setVisible(true); - overlay.repaint(); - - timer = new Timer(FRAME_MS, e -> tick()); - timer.start(); - return true; - } - - private BufferedImage snapshot(Rectangle bounds) { - BufferedImage img = new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = img.createGraphics(); - g.setClip(0, 0, bounds.width, bounds.height); - g.translate(-bounds.x, -bounds.y); - tabbed.paint(g); - g.dispose(); - return img; - } - - /** - * Swaps the dragged tile with whichever neighbour it has reached the midpoint - * of: its trailing edge past the next tile's midpoint when moving right, or its - * leading edge past the previous tile's midpoint when moving left. Checked - * against the neighbour's target slot rather than its live position, since that - * may itself still be mid-animation. - */ - private void dragTo(int cursorX) { - int min = stripStartX; - int max = stripStartX + stripWidth - draggedTile.width; - draggedTile.currentX = Math.max(min, Math.min(max, cursorX - grabDx)); - - if (dragSlot + 1 < order.size()) { - Tile next = order.get(dragSlot + 1); - double rightEdge = draggedTile.currentX + draggedTile.width; - if (rightEdge > next.targetX + next.width / 2.0) { - swap(dragSlot, dragSlot + 1); - return; - } - } - if (dragSlot - 1 >= 0) { - Tile prev = order.get(dragSlot - 1); - double leftEdge = draggedTile.currentX; - if (leftEdge < prev.targetX + prev.width / 2.0) { - swap(dragSlot - 1, dragSlot); - } - } - } - - /** Swaps the two adjacent slots {@code a} and {@code b} (one of them the dragged tile's) in {@link #order}, not the real tab model. */ - private void swap(int a, int b) { - int newSlot = dragSlot == a ? b : a; - order.remove(draggedTile); - order.add(newSlot, draggedTile); - dragSlot = newSlot; - retarget(false); - } - - /** Assigns each tile's slot target from the current {@code order}; the dragged tile follows the cursor instead, unless {@code includeDragged}. */ - private void retarget(boolean includeDragged) { - double x = stripStartX; - for (Tile t : order) { - if (t != draggedTile || includeDragged) t.targetX = x; - x += t.width; - } - } - - /** - * Commits the reorder to the real tab model in one shot. Doing this once here, - * rather than per swap while dragging, matters because reordering the real - * model can rebuild tab components (new labels, new listeners), which would - * otherwise yank the component out from under an in-flight mouse grab. - */ - private void endDrag() { - releasing = true; - if (dragSlot != startSlot) reorder.moveTab(startSlot, dragSlot); - retarget(true); - } - - private void tick() { - boolean settled = true; - for (Tile t : order) { - if (t == draggedTile && !releasing) continue; - double diff = t.targetX - t.currentX; - if (Math.abs(diff) < SETTLE_EPSILON) { - t.currentX = t.targetX; - } else { - t.currentX += diff * EASE; - settled = false; - } - } - overlay.repaint(); - if (releasing && settled) { - timer.stop(); - overlay.tiles = null; - overlay.onTop = null; - overlay.setVisible(false); - order = null; - draggedTile = null; - } - } - - /** One tab's snapshot, animating from {@link #currentX} toward {@link #targetX}. */ - private static final class Tile { - final BufferedImage image; - final int x, y, width, height; - double currentX; - double targetX; - - Tile(BufferedImage image, int x, int y, int width, int height) { - this.image = image; - this.x = x; - this.y = y; - this.width = width; - this.height = height; - this.currentX = x; - this.targetX = x; - } - } - - /** A transparent overlay on the glass pane that paints every tab's animated snapshot. */ - private static final class Overlay extends JComponent { - List tiles; - /** Painted last (on top) so it stays above tabs it's currently overlapping while dragged. */ - Tile onTop; - Point origin = new Point(); - - Overlay() { - setOpaque(false); - } - - /** Never claims mouse events, so drags keep reaching the component that was actually pressed. */ - @Override - public boolean contains(int x, int y) { - return false; - } - - @Override - protected void paintComponent(Graphics g) { - if (tiles == null) return; - Graphics2D g2 = (Graphics2D) g.create(); - g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.9f)); - for (Tile t : tiles) { - if (t != onTop) draw(g2, t); - } - if (onTop != null) draw(g2, onTop); - g2.dispose(); - } - - private void draw(Graphics2D g2, Tile t) { - g2.drawImage(t.image, origin.x + (int) Math.round(t.currentX), origin.y + t.y, null); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/TextZoom.java b/ts3-client/swing/src/main/java/com/ts3client/ui/TextZoom.java deleted file mode 100644 index d870263..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/TextZoom.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.ts3client.ui; - -import javax.swing.JEditorPane; -import javax.swing.JViewport; -import javax.swing.SwingUtilities; -import javax.swing.text.BadLocationException; -import javax.swing.text.Document; -import javax.swing.text.SimpleAttributeSet; -import javax.swing.text.StyledDocument; -import java.awt.Component; -import java.awt.Point; -import java.awt.event.MouseWheelEvent; -import java.util.Collections; -import java.util.Set; -import java.util.WeakHashMap; -import java.util.function.DoubleConsumer; - -/** - * A zoom level for the text and pictures of {@link HtmlStyles} panes, changed with - * Ctrl+mouse wheel over any of them and applied to all of them, in a browser's steps. - */ -final class TextZoom { - - private static final double[] LEVELS = {0.5, 0.67, 0.75, 0.8, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3}; - - private final Set panes = Collections.newSetFromMap(new WeakHashMap<>()); - private final DoubleConsumer onChange; - private double factor; - - /** @param onChange told the new factor after every change, e.g. to save it */ - TextZoom(double factor, DoubleConsumer onChange) { - this.factor = nearestLevel(factor); - this.onChange = onChange; - } - - /** The zoom of {@code c}, an {@link HtmlStyles} pane, or 1 if it has none. */ - static float of(Component c) { - return c instanceof JEditorPane pane && pane.getClientProperty(TextZoom.class) instanceof TextZoom zoom - ? (float) zoom.factor : 1f; - } - - /** Zooms {@code pane} with this zoom, and lets Ctrl+wheel over it change it. */ - void attach(JEditorPane pane) { - if (pane.getClientProperty(TextZoom.class) == this) return; - pane.putClientProperty(TextZoom.class, this); - panes.add(pane); - pane.addMouseWheelListener(e -> onWheel(pane, e)); - if (factor != 1) relayout(pane); - } - - private void onWheel(JEditorPane pane, MouseWheelEvent e) { - if (!e.isControlDown()) { - // Listening for the wheel takes it from the scroll pane, so hand plain scrolling on. - Component parent = pane.getParent(); - if (parent != null) parent.dispatchEvent(SwingUtilities.convertMouseEvent(pane, e, parent)); - return; - } - e.consume(); - if (e.getWheelRotation() != 0) step(e.getWheelRotation() < 0 ? 1 : -1); - } - - private void step(int direction) { - int i = indexOf(factor); - int next = Math.max(0, Math.min(LEVELS.length - 1, i + direction)); - if (next == i) return; - factor = LEVELS[next]; - for (JEditorPane pane : panes) relayout(pane); - onChange.accept(factor); - } - - /** Lays {@code pane} out again at the new size, keeping the same text in view. */ - private static void relayout(JEditorPane pane) { - Document doc = pane.getDocument(); - if (!(doc instanceof StyledDocument styled) || doc.getLength() == 0) return; - // An empty change over everything makes every view fetch its font and size again. - if (!(pane.getParent() instanceof JViewport viewport)) { - styled.setCharacterAttributes(0, doc.getLength(), new SimpleAttributeSet(), false); - return; - } - - Point top = viewport.getViewPosition(); - boolean atEnd = top.y + viewport.getExtentSize().height >= pane.getHeight(); - int anchor = pane.viewToModel2D(top); - styled.setCharacterAttributes(0, doc.getLength(), new SimpleAttributeSet(), false); - viewport.getParent().validate(); - int max = Math.max(0, pane.getHeight() - viewport.getExtentSize().height); - int y = max; - if (!atEnd) { - try { - y = Math.min(max, pane.modelToView2D(anchor).getBounds().y); - } catch (BadLocationException ignored) { - // Cannot happen: the text has not changed, only its size. - } - } - viewport.setViewPosition(new Point(top.x, y)); - } - - private static double nearestLevel(double factor) { - return LEVELS[indexOf(factor)]; - } - - private static int indexOf(double factor) { - int best = 0; - for (int i = 1; i < LEVELS.length; i++) { - if (Math.abs(LEVELS[i] - factor) < Math.abs(LEVELS[best] - factor)) best = i; - } - return best; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/Theme.java b/ts3-client/swing/src/main/java/com/ts3client/ui/Theme.java deleted file mode 100644 index 58f6d2c..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/Theme.java +++ /dev/null @@ -1,183 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.ui.FlatUIUtils; -import com.formdev.flatlaf.util.UIScale; - -import javax.swing.UIManager; -import java.awt.Color; -import java.awt.Font; - -/** - * The palette and fonts the client paints with, on top of the active look-and-feel. - * - *

    Surfaces (window, tree, chat background) and fonts come straight from the - * look-and-feel, so the client follows whatever FlatLaf theme is installed. The - * status colours TeamSpeak gives meaning to — talking, away, muted, channel and - * server names — are ours, in a light and a dark variant; {@link #refresh()} picks - * the variant matching the installed theme. - */ -public final class Theme { - - private static boolean dark; - - private Theme() { - } - - /** Re-reads the installed look-and-feel; call after changing it. */ - static void refresh() { - Color bg = UIManager.getColor("Panel.background"); - dark = bg != null && luminance(bg) < 0.5; - } - - public static boolean isDark() { - return dark; - } - - // ---- fonts ---- - - public static Font uiFont() { - Font f = UIManager.getFont("Label.font"); - return f != null ? f : new Font("SansSerif", Font.PLAIN, UIScale.scale(12)); - } - - public static Font uiBold() { - return uiFont().deriveFont(Font.BOLD); - } - - /** A notch below the UI font, for secondary labels. */ - public static Font uiSmall() { - Font f = uiFont(); - return f.deriveFont(Math.max(9f, f.getSize2D() - 2f)); - } - - // ---- surfaces, from the look-and-feel ---- - - public static Color windowBg() { - return ui("Panel.background", 0xF0F0F0, 0x282828); - } - - public static Color toolbarBg() { - return ui("ToolBar.background", 0xE6E9ED, 0x282828); - } - - public static Color statusBg() { - return windowBg(); - } - - public static Color treeBg() { - return ui("Tree.background", 0xFFFFFF, 0x1E1E1E); - } - - public static Color treeText() { - return ui("Tree.foreground", 0x1E1E1E, 0xE0E0E0); - } - - public static Color treeSelection() { - return ui("Tree.selectionBackground", 0xCFE3FB, 0x364B6F); - } - - /** - * Behind the row the pointer is over: the same wash the menu bar puts behind a hovered - * menu. The look-and-feel states it as a shift of whatever surface it sits on, and the - * menu bar resolves it against the window, so this does too — a row hover and a menu - * hover then carry the very same colour. - */ - public static Color hover() { - return FlatUIUtils.deriveColor(ui("MenuBar.hoverBackground", 0xE6E6E6, 0x3D3D3D), windowBg()); - } - - public static Color chatBg() { - return ui("TextPane.background", 0xFAFAFA, 0x1E1E1E); - } - - public static Color border() { - return ui("Component.borderColor", 0xD0D0D0, 0x3E3E3E); - } - - public static Color chatText() { - return ui("TextPane.foreground", 0x202020, 0xE0E0E0); - } - - /** Behind every match of a find bar's query. */ - public static Color searchMatch() { - return pick(0xFFEBA3, 0x5C4E1A); - } - - /** Behind the match a find bar is on. */ - public static Color searchCurrent() { - return pick(0xFFB84D, 0x9C6A12); - } - - // ---- status colours ---- - - public static Color channelText() { - return pick(0x21486B, 0xFFFFFF); - } - - /** The colour of a chat line about what happened on the server. */ - public static Color chatEvent() { - return pick(0x21486B, 0x8FBCE6); - } - - public static Color serverText() { - return pick(0x123456, 0xDCE8F5); - } - - public static Color talking() { - return pick(0x33B35A, 0x4CC479); - } - - public static Color idleClient() { - return pick(0x6E7B87, 0x9AA6B2); - } - - public static Color away() { - return pick(0xC98A1B, 0xE0A83C); - } - - public static Color muted() { - return pick(0xC0392B, 0xE05C4C); - } - - /** TeamSpeak's {@code CustomColor::ClientFriend}, lifted for the dark scheme. */ - public static Color friend() { - return pick(0x008000, 0x5CC96A); - } - - /** TeamSpeak's {@code CustomColor::ClientBlocked}, lifted for the dark scheme. */ - public static Color blocked() { - return pick(0xFF0000, 0xF06A5E); - } - - public static Color accent() { - return pick(0x2C7BE5, 0x5C9BEE); - } - - public static Color chatSystem() { - return pick(0x8A8A8A, 0x9A9A9A); - } - - public static Color chatName() { - return accent(); - } - - /** Links that leave the client, distinct from the colour used for identities. */ - public static Color link() { - return pick(0x1A5FB4, 0x6EA8FF); - } - - private static Color pick(int light, int darkRgb) { - return new Color(dark ? darkRgb : light); - } - - private static Color ui(String key, int lightFallback, int darkFallback) { - // Returned as the look-and-feel's own UIResource colour, so components painted with - // it are recoloured automatically when the look-and-feel is switched. - Color c = UIManager.getColor(key); - return c != null ? c : pick(lightFallback, darkFallback); - } - - private static double luminance(Color c) { - return (0.2126 * c.getRed() + 0.7152 * c.getGreen() + 0.0722 * c.getBlue()) / 255.0; - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/TrayController.java b/ts3-client/swing/src/main/java/com/ts3client/ui/TrayController.java deleted file mode 100644 index 6d304b0..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/TrayController.java +++ /dev/null @@ -1,253 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.session.SelfState; -import com.ts3client.ui.tray.AwtTray; -import com.ts3client.ui.tray.TrayBackend; -import com.ts3client.ui.tray.X11Tray; - -import javax.swing.ImageIcon; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; -import javax.swing.KeyStroke; -import javax.swing.SwingUtilities; -import javax.swing.event.PopupMenuEvent; -import javax.swing.event.PopupMenuListener; -import java.awt.Frame; -import java.awt.Image; -import java.awt.MenuItem; -import java.awt.PopupMenu; -import java.awt.Window; -import java.awt.event.KeyEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.function.IntFunction; - -/** - * The system tray icon. It shows the local client's state on the active server — - * the same badge the tree draws next to a nickname, so it turns green while - * speaking and into the muted microphone or speaker when muted — and brings the - * window back to the front when clicked. - * - *

    The icon is docked by {@link X11Tray} where the panel can show a transparent - * one, and by {@link AwtTray} everywhere else. On a desktop with no tray at all - * nothing is installed and every call here is a no-op. - */ -final class TrayController { - - private final MainFrame frame; - private final Runnable onQuit; - - private final TrayBackend tray; - - /** What is on screen now, so repeated updates don't touch the tray. */ - private SelfState state; - private String tooltip = ""; - - /** The context menu while it is on screen, and the window it hangs off. */ - private JPopupMenu openMenu; - private JDialog openAnchor; - - TrayController(MainFrame frame, Runnable onQuit) { - this.frame = frame; - this.onQuit = onQuit; - this.tray = install(); - } - - /** What happened when the icon was installed, for the diagnostics in the chat log. */ - String status() { - return tray == null - ? "System tray: no icon could be installed (run with -Dts3j.tray.debug=true for why)." - : "System tray: " + tray.description() + "."; - } - - /** @return the backend that took the icon, or {@code null} when none could */ - private TrayBackend install() { - TrayBackend.Listener listener = new TrayBackend.Listener() { - @Override - public void activated() { - SwingUtilities.invokeLater(TrayController.this::show); - } - - @Override - public void menuRequested(int x, int y) { - SwingUtilities.invokeLater(() -> showMenu(x, y)); - } - }; - // -Dts3j.tray=awt|x11 pins the backend; by default the transparent one is - // tried first and AWT's picks up whatever it leaves. - String choice = System.getProperty("ts3j.tray", "auto"); - IntFunction initial = size -> icon(SelfState.DISCONNECTED, size).getImage(); - TrayBackend backend = choice.equals("awt") ? null : X11Tray.create(listener, initial); - if (backend == null && !choice.equals("x11")) { - backend = AwtTray.create(listener, buildAwtMenu(), initial); - } - return backend; - } - - /** Shows the state of the given server, named by {@code serverName} in the tooltip. */ - void update(SelfState newState, String serverName) { - if (tray == null) return; - String newTooltip = "TS3J — " + (serverName == null || serverName.isBlank() - ? newState.label() - : serverName + ": " + newState.label()); - if (newState == state && newTooltip.equals(tooltip)) return; - state = newState; - tooltip = newTooltip; - tray.setIcon(size -> icon(newState, size).getImage()); - tray.setTooltip(newTooltip); - } - - /** Redraws after the icon pack changed. */ - void refreshIcon() { - if (tray == null || state == null) return; - SelfState current = state; - tray.setIcon(size -> icon(current, size).getImage()); - } - - void dispose() { - if (tray != null) tray.dispose(); - } - - /** The backend that took the icon, or {@code null} when none could. */ - TrayBackend backend() { - return tray; - } - - /** The icon a state is drawn with, from the active icon pack. */ - private static ImageIcon icon(SelfState state, int size) { - return switch (state) { - case DISCONNECTED -> Icons.app(size); - case DEAFENED -> Icons.speakerMuted(size); - case MIC_MUTED -> Icons.micMuted(size); - case MIC_LOCAL_MUTED -> Icons.micLocalMuted(size); - case AWAY -> Icons.clientAway(size); - case COMMANDER_TALKING -> Icons.clientCommanderTalking(size); - case COMMANDER -> Icons.clientCommander(size); - case TALKING -> Icons.clientTalking(size); - case IDLE -> Icons.clientIdle(size); - }; - } - - // ---- menus ---- - - /** The menu for AWT's icon, which shows one of its own. */ - private PopupMenu buildAwtMenu() { - PopupMenu menu = new PopupMenu(); - MenuItem showItem = new MenuItem("Show TS3J"); - showItem.addActionListener(e -> SwingUtilities.invokeLater(this::show)); - MenuItem quitItem = new MenuItem("Quit"); - quitItem.addActionListener(e -> SwingUtilities.invokeLater(onQuit)); - menu.add(showItem); - menu.addSeparator(); - menu.add(quitItem); - return menu; - } - - /** - * The same menu for backends that have none — a Swing popup needs a component to - * hang off, so it is given an empty window at the pointer. - * - *

    Swing dismisses a popup from events it sees itself, and it sees none of the - * clicks that land on the desktop or another application, so the little window is - * made focusable and the menu closed as soon as it loses the focus. Escape and a - * second click on the icon close it too. - */ - private void showMenu(int x, int y) { - if (openMenu != null) { // a second click on the icon: close it again - hideMenu(); - return; - } - JDialog anchor = new JDialog(frame); - anchor.setUndecorated(true); - anchor.setFocusableWindowState(true); - anchor.setAlwaysOnTop(true); - anchor.setLocation(x, y); - anchor.setSize(1, 1); - anchor.setVisible(true); - anchor.toFront(); - anchor.requestFocus(); - anchor.addWindowFocusListener(new WindowAdapter() { - @Override - public void windowLostFocus(WindowEvent e) { - // The menu's own popup window may take the focus instead; only the - // focus moving away from the menu altogether closes it. - if (!ownedBy(e.getOppositeWindow(), anchor)) hideMenu(); - } - }); - - anchor.getRootPane().registerKeyboardAction(e -> hideMenu(), - KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), - JComponent.WHEN_IN_FOCUSED_WINDOW); - - JPopupMenu menu = new JPopupMenu(); - JMenuItem showItem = new JMenuItem("Show TS3J", Icons.app()); - showItem.addActionListener(e -> show()); - JMenuItem quitItem = new JMenuItem("Quit", Icons.of("QUIT")); - quitItem.addActionListener(e -> onQuit.run()); - menu.add(showItem); - menu.addSeparator(); - menu.add(quitItem); - menu.addPopupMenuListener(new PopupMenuListener() { - @Override - public void popupMenuWillBecomeVisible(PopupMenuEvent e) { - } - - @Override - public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { - closed(anchor); - } - - @Override - public void popupMenuCanceled(PopupMenuEvent e) { - closed(anchor); - } - }); - openMenu = menu; - openAnchor = anchor; - menu.show(anchor, 0, 0); - } - - /** @return whether {@code window} is {@code owner} or one of its child windows */ - private static boolean ownedBy(Window window, Window owner) { - for (Window w = window; w != null; w = w.getOwner()) { - if (w == owner) return true; - } - return false; - } - - private void hideMenu() { - if (openMenu != null) openMenu.setVisible(false); // the listener cleans up - closed(openAnchor); - } - - private void closed(JDialog anchor) { - openMenu = null; - openAnchor = null; - if (anchor != null) anchor.dispose(); - } - - /** - * Brings the window back from the taskbar or an iconified state. - * - *

    A window manager ignores {@link Frame#toFront()} from an application that is - * not focused, which is every time the tray icon is used, so the backend is asked - * first — it can make the request the window manager does honour. - */ - void show() { - hideMenu(); - frame.setVisible(true); - frame.setExtendedState(frame.getExtendedState() & ~Frame.ICONIFIED); - // Deferred so the window is mapped before anything tries to raise it. - SwingUtilities.invokeLater(() -> { - if (tray != null && tray.activateWindow(frame.getTitle())) return; - // Whatever Swing can manage: asking to be on top for a moment gets the - // window in front even where a plain raise is refused. - frame.setAlwaysOnTop(true); - frame.toFront(); - frame.requestFocus(); - frame.setAlwaysOnTop(false); - }); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/TrayNotifications.java b/ts3-client/swing/src/main/java/com/ts3client/ui/TrayNotifications.java deleted file mode 100644 index 6a96df3..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/TrayNotifications.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.ts3client.ui; - -import com.ts3client.notify.desktop.DesktopNotifications; -import com.ts3client.ui.tray.AwtTray; - -/** - * Desktop notifications as messages from AWT's tray icon, for Windows and macOS: they - * land in the system's notification centre. A message cannot be replaced or taken back. - */ -final class TrayNotifications implements DesktopNotifications { - - private final AwtTray tray; - - TrayNotifications(AwtTray tray) { - this.tray = tray; - } - - @Override - public int show(Notice notice, int replaces) { - tray.showMessage(notice.title(), notice.body(), notice.onOpen()); - return 1; - } - - @Override - public void close(int id) { - } - - @Override - public boolean canReply() { - return false; - } - - @Override - public void shutdown() { - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/VoiceActivationSection.java b/ts3-client/swing/src/main/java/com/ts3client/ui/VoiceActivationSection.java deleted file mode 100644 index bb982b3..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/VoiceActivationSection.java +++ /dev/null @@ -1,336 +0,0 @@ -package com.ts3client.ui; - -import com.formdev.flatlaf.util.ScaledEmptyBorder; -import com.formdev.flatlaf.util.UIScale; -import com.ts3client.audio.AudioBackend; -import com.ts3client.audio.InputLevel; -import com.ts3client.audio.VoiceInput; -import com.ts3client.config.Settings; -import com.ts3client.hotkey.Hotkey; -import com.ts3client.hotkey.HotkeyAction; - -import javax.swing.ButtonGroup; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JSlider; -import javax.swing.JToggleButton; -import java.awt.BorderLayout; -import java.awt.GridBagConstraints; -import java.awt.Insets; -import java.util.List; -import java.util.function.Consumer; -import java.util.function.Supplier; - -/** - * The Capture page's activation section: input mode (push-to-talk / continuous / voice - * activation), the detection tuning, and a live input meter. - * - *

    Owns the microphone test (start/stop button, loopback, indicator): it runs a real - * capture chain built from what the Capture and Playback pages have on screen, via - * {@code audioSnapshot}. - */ -final class VoiceActivationSection { - - private final VoiceInput liveMic; - private final HotkeyService hotkeys; - private final HotkeysPanel hotkeysPanel; - private final Supplier audioSnapshot; - private final MicrophoneTest micTest; - - private final JRadioButton vadRadio; - private final JRadioButton pttRadio; - private final JRadioButton contRadio; - private final JComboBox vadModeCombo; - private final JSlider thresholdSlider; - private final JSlider speechSlider; - private final JCheckBox vadOverPttCheck; - private final LevelMeter meter; - private JToggleButton testButton; - private JCheckBox loopbackCheck; - private JLabel talkIndicator; - private final JButton pttKeyButton; - - private final JLabel thresholdLabel; - private final JLabel speechLabel; - private final JPanel testControls; - - VoiceActivationSection(Settings settings, AudioBackend audio, VoiceInput liveMic, HotkeyService hotkeys, - HotkeysPanel hotkeysPanel, Supplier audioSnapshot) { - this.liveMic = liveMic; - this.micTest = new MicrophoneTest(audio, this::onTestLevel, this::onTestTalking); - this.hotkeys = hotkeys; - this.hotkeysPanel = hotkeysPanel; - this.audioSnapshot = audioSnapshot; - - pttRadio = new JRadioButton("Push-To-Talk"); - contRadio = new JRadioButton("Continuous Transmission"); - vadRadio = new JRadioButton("Voice Activity Detection"); - ButtonGroup group = new ButtonGroup(); - group.add(pttRadio); - group.add(contRadio); - group.add(vadRadio); - switch (settings.inputMode) { - case PUSH_TO_TALK: - pttRadio.setSelected(true); - break; - case CONTINUOUS: - contRadio.setSelected(true); - break; - default: - vadRadio.setSelected(true); - } - - pttKeyButton = new JButton(pushToTalkHotkeyText()); - pttKeyButton.setToolTipText("Push-to-talk is a global hotkey; this opens its binding"); - pttKeyButton.addActionListener(e -> editPushToTalkHotkey()); - - vadOverPttCheck = new JCheckBox("Add Voice Activity Detection", settings.vadOverPtt); - vadOverPttCheck.addActionListener(e -> - micTest.configure(m -> m.setVadOverPtt(vadOverPttCheck.isSelected()))); - - vadModeCombo = new JComboBox<>(new String[]{"Automatic", "Volume Gate", "Hybrid"}); - vadModeCombo.setSelectedIndex(vadModeIndex(settings.vadMode)); - vadModeCombo.addActionListener(e -> micTest.configure(m -> m.setVadMode(currentVadMode()))); - vadModeCombo.setToolTipText("Automatic: intelligent speech detection.
    " - + "Volume Gate: transmit when loud enough.
    " - + "Hybrid: loud enough and detected as speech."); - - thresholdSlider = new JSlider((int) InputLevel.MIN_DB, (int) InputLevel.MAX_DB, - (int) Math.round(settings.vadThresholdDb)); - thresholdLabel = new JLabel(Math.round(settings.vadThresholdDb) + " dB"); - speechSlider = new JSlider(0, 100, (int) Math.round(settings.speechThreshold * 100)); - speechLabel = new JLabel(Math.round(settings.speechThreshold * 100) + "%"); - - meter = new LevelMeter(); - meter.setThreshold(settings.vadThresholdDb); - testControls = buildTestControls(); - - thresholdSlider.addChangeListener(e -> { - meter.setThreshold(thresholdSlider.getValue()); - thresholdLabel.setText(thresholdSlider.getValue() + " dB"); - applyLive(m -> m.setThresholdDb(thresholdSlider.getValue())); - }); - speechSlider.addChangeListener(e -> { - speechLabel.setText(speechSlider.getValue() + "%"); - applyLive(m -> m.setSpeechThreshold(speechSlider.getValue() / 100.0)); - }); - - Runnable syncEnabled = () -> { - boolean vad = vadRadio.isSelected(); - boolean ptt = pttRadio.isSelected(); - boolean vadContext = vad || (ptt && vadOverPttCheck.isSelected()); - Settings.VadMode vm = currentVadMode(); - boolean usesGate = vm != Settings.VadMode.AUTOMATIC; - boolean usesSpeech = vm != Settings.VadMode.VOLUME_GATE; - - vadModeCombo.setEnabled(vadContext); - thresholdSlider.setEnabled(vadContext && usesGate); - speechSlider.setEnabled(vadContext && usesSpeech); - pttKeyButton.setEnabled(ptt); - vadOverPttCheck.setEnabled(ptt); - meter.setShowThreshold(vadContext && usesGate); - - if (liveMic != null) { - liveMic.setMode(ptt ? Settings.InputMode.PUSH_TO_TALK - : vad ? Settings.InputMode.VOICE_ACTIVATION - : Settings.InputMode.CONTINUOUS); - liveMic.setVadMode(vm); - liveMic.setVadOverPtt(vadOverPttCheck.isSelected()); - } - }; - vadRadio.addActionListener(e -> syncEnabled.run()); - pttRadio.addActionListener(e -> syncEnabled.run()); - contRadio.addActionListener(e -> syncEnabled.run()); - vadModeCombo.addActionListener(e -> syncEnabled.run()); - vadOverPttCheck.addActionListener(e -> syncEnabled.run()); - syncEnabled.run(); - } - - /** Adds the section's rows to {@code form} from {@code row} on; returns the next free row. */ - int layOut(JPanel form, GridBagConstraints c, int row) { - FormPanel.addRow(form, c, row++, pttRadio, pttKeyButton); - FormPanel.addWide(form, c, row++, indented(vadOverPttCheck)); - FormPanel.addWide(form, c, row++, contRadio); - FormPanel.addRow(form, c, row++, vadRadio, vadModeCombo); - FormPanel.addRow(form, c, row++, indented(new JLabel("Volume gate:")), - FormPanel.sliderWithLabel(thresholdSlider, thresholdLabel)); - FormPanel.addRow(form, c, row++, indented(new JLabel("Speech threshold:")), - FormPanel.sliderWithLabel(speechSlider, speechLabel)); - - Insets insets = c.insets; - c.insets = UIScale.scale(new Insets(10, 4, 4, 4)); - FormPanel.addWide(form, c, row++, meter); - c.insets = insets; - FormPanel.addWide(form, c, row++, testControls); - return row; - } - - /** Lines a dependent control up under the text of the radio button it belongs to. */ - private static JComponent indented(JComponent comp) { - JPanel p = new JPanel(new BorderLayout()); - p.setBorder(new ScaledEmptyBorder(0, 22, 0, 0)); - p.add(comp, BorderLayout.CENTER); - return p; - } - - /** Copies the form into {@code target}, without touching anything else. */ - void writeInto(Settings target) { - target.inputMode = pttRadio.isSelected() ? Settings.InputMode.PUSH_TO_TALK - : contRadio.isSelected() ? Settings.InputMode.CONTINUOUS - : Settings.InputMode.VOICE_ACTIVATION; - target.vadMode = currentVadMode(); - target.vadThresholdDb = thresholdSlider.getValue(); - target.speechThreshold = speechSlider.getValue() / 100.0; - target.vadOverPtt = vadOverPttCheck.isSelected(); - } - - /** Applies a change to the microphone test, if it is running. */ - void configureTest(Consumer change) { - micTest.configure(change); - } - - /** The playback device to loop the test through. */ - void setTestOutputDevice(String deviceId) { - micTest.setOutputDevice(deviceId); - } - - /** Restarts the test chain, if running, so a device change takes effect. */ - void restartTest() { - if (micTest.isRunning()) { - boolean loopback = loopbackCheck.isSelected(); - if (micTest.start(audioSnapshot.get())) { - micTest.setLoopback(loopback); - } else { - setTesting(false); - testButton.setSelected(false); - } - } - } - - void stopTest() { - micTest.stop(); - } - - private static int vadModeIndex(Settings.VadMode m) { - switch (m) { - case AUTOMATIC: - return 0; - case VOLUME_GATE: - return 1; - default: - return 2; - } - } - - private Settings.VadMode currentVadMode() { - switch (vadModeCombo.getSelectedIndex()) { - case 0: - return Settings.VadMode.AUTOMATIC; - case 1: - return Settings.VadMode.VOLUME_GATE; - default: - return Settings.VadMode.HYBRID; - } - } - - private String pushToTalkHotkeyText() { - Hotkey ptt = hotkeys.find(HotkeyAction.PTT_ACTIVATE); - return ptt == null ? "No hotkey assigned" : hotkeys.display(ptt.combo); - } - - /** - * Push-to-talk is an ordinary hotkey, so this shortcut edits that binding — adding - * it when there is none — rather than keeping a key of its own. - */ - private void editPushToTalkHotkey() { - Hotkey existing = hotkeys.find(HotkeyAction.PTT_ACTIVATE); - HotkeyDialog dlg = new HotkeyDialog(javax.swing.SwingUtilities.getWindowAncestor(pttKeyButton), - hotkeys, existing == null ? new Hotkey(HotkeyAction.PTT_ACTIVATE, null) : existing); - dlg.setVisible(true); - if (!dlg.isConfirmed()) return; - List updated = new java.util.ArrayList<>(); - for (Hotkey h : hotkeys.all()) { - if (h != existing) updated.add(h.copy()); - } - updated.add(dlg.result()); - hotkeys.replaceAll(updated); - pttKeyButton.setText(pushToTalkHotkeyText()); - hotkeysPanel.reload(); - } - - /** Applies a live change to the connected microphone and to the test one alike. */ - private void applyLive(Consumer change) { - if (liveMic != null) change.accept(liveMic); - micTest.configure(change); - } - - // ---- microphone test ---- - - /** - * The test row: a toggle that runs the capture chain, an indicator showing whether the - * gate is open, and an optional loopback so you can hear what is being sent. - */ - private JPanel buildTestControls() { - JPanel row = new JPanel(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 8, 0)); - - testButton = new JToggleButton("Begin Test"); - testButton.setToolTipText("Run the capture chain exactly as it runs while connected, " - + "so the bar and the indicator show what would actually be transmitted."); - testButton.addActionListener(e -> setTesting(testButton.isSelected())); - - loopbackCheck = new JCheckBox("Hear myself"); - loopbackCheck.setToolTipText("Play the transmitted audio back through the playback " - + "device. Use headphones to avoid feedback."); - loopbackCheck.setEnabled(false); - loopbackCheck.addActionListener(e -> micTest.setLoopback(loopbackCheck.isSelected())); - - talkIndicator = new JLabel("Not transmitting", Icons.clientIdle(), JLabel.LEFT); - talkIndicator.setToolTipText("Lights up while your microphone is open, exactly as " - + "other users would see you in the channel list."); - - row.add(testButton); - row.add(loopbackCheck); - row.add(talkIndicator); - return row; - } - - private void setTesting(boolean on) { - if (on && !micTest.start(audioSnapshot.get())) { - testButton.setSelected(false); - testButton.setText("Begin Test"); - loopbackCheck.setEnabled(false); - resetTestIndicators(); - talkIndicator.setText("Capture device unavailable"); - return; - } - if (!on) { - micTest.stop(); - loopbackCheck.setSelected(false); - resetTestIndicators(); - } - testButton.setText(on ? "Stop Test" : "Begin Test"); - loopbackCheck.setEnabled(on); - } - - private void resetTestIndicators() { - onTestTalking(false); - onTestLevel(InputLevel.SILENCE_DB); - } - - private void onTestLevel(double db) { - if (meter != null) meter.setLevel(db); - } - - private void onTestTalking(boolean talking) { - if (meter != null) meter.setTransmitting(talking); - if (talkIndicator != null) { - talkIndicator.setIcon(talking ? Icons.clientTalking() : Icons.clientIdle()); - talkIndicator.setText(talking ? "Transmitting" : "Not transmitting"); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/WindowClass.java b/ts3-client/swing/src/main/java/com/ts3client/ui/WindowClass.java deleted file mode 100644 index 4571156..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/WindowClass.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.ts3client.ui; - -import java.awt.GraphicsEnvironment; -import java.awt.Toolkit; -import java.lang.reflect.Field; -import java.util.Locale; - -/** - * Gives the client's windows their own X11 {@code WM_CLASS}. - * - *

    AWT names it after the class at the bottom of the stack that first touched the - * toolkit — for a Swing app that is usually {@code java-awt-EventDispatchThread}, - * which every other Java program shares. Task bars group windows and look up their - * launcher by that class (Plasma does so on Wayland too, through Xwayland), so the - * client ended up filed under "Java" together with unrelated programs. - * - *

    The name lives in a private field of {@code sun.awt.X11.XToolkit}; reaching it - * needs {@code --add-opens java.desktop/sun.awt.X11=ALL-UNNAMED}, which the jar's - * manifest grants. Without it the default name stays. - */ -public final class WindowClass { - - /** Matches {@code StartupWMClass} in a launcher's {@code .desktop} file. */ - public static final String NAME = "ts3j-client"; - - private WindowClass() { - } - - /** Call before the first window is created. */ - public static void apply() { - if (!System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("linux") - || GraphicsEnvironment.isHeadless()) { - return; - } - Toolkit toolkit = Toolkit.getDefaultToolkit(); - if (!toolkit.getClass().getName().equals("sun.awt.X11.XToolkit")) return; - try { - Field field = toolkit.getClass().getDeclaredField("awtAppClassName"); - field.setAccessible(true); - field.set(null, NAME); - } catch (ReflectiveOperationException | RuntimeException e) { - System.err.println("Cannot set the window class (run with " - + "--add-opens java.desktop/sun.awt.X11=ALL-UNNAMED): " + e); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/tray/AwtTray.java b/ts3-client/swing/src/main/java/com/ts3client/ui/tray/AwtTray.java deleted file mode 100644 index 281d4c5..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/tray/AwtTray.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.ts3client.ui.tray; - -import java.awt.AWTException; -import java.awt.Dimension; -import java.awt.Image; -import java.awt.PopupMenu; -import java.awt.SystemTray; -import java.awt.TrayIcon; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.function.IntFunction; - -/** - * The tray icon AWT itself provides — used where {@link X11Tray} cannot help: - * Windows and macOS, and X11 panels that do not offer a transparent visual. - * - *

    On X11 the toolkit draws the icon onto an opaque background, which is the - * price of this fallback; the menu, on the other hand, is the desktop's own. - */ -public final class AwtTray implements TrayBackend { - - private final TrayIcon icon; - private final int size; - /** What a click on the message last shown does, until it is used. */ - private volatile Runnable messageClick; - - /** - * @param menu the icon's context menu, or {@code null} to have right clicks - * reported to {@code listener} instead - * @param initial the image to dock with, rendered at the tray's icon size - * @return the icon, or {@code null} when this desktop has no tray at all - */ - public static AwtTray create(Listener listener, PopupMenu menu, IntFunction initial) { - if (!SystemTray.isSupported()) { - TrayLog.debug("this desktop has no system tray"); - return null; - } - try { - AwtTray tray = new AwtTray(listener, menu, initial); - TrayLog.debug("using AWT's tray icon, " + tray.size + "px (it draws a background)"); - return tray; - } catch (AWTException | UnsupportedOperationException e) { - TrayLog.debug("AWT would not add the icon: " + e.getMessage()); - return null; - } - } - - private AwtTray(Listener listener, PopupMenu menu, IntFunction initial) - throws AWTException { - Dimension traySize = SystemTray.getSystemTray().getTrayIconSize(); - size = Math.max(16, Math.min(traySize.width, traySize.height)); - - // Added with its final image and tooltip: some panels take the icon they are - // handed at that moment and ignore later changes. - icon = new TrayIcon(initial.apply(size), "TS3J"); - if (menu != null) icon.setPopupMenu(menu); - // The action event only fires on a double click (and not at all on some - // desktops), so listen for the click itself. - icon.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON1) { - listener.activated(); - } else if (menu == null && e.isPopupTrigger()) { - listener.menuRequested(e.getXOnScreen(), e.getYOnScreen()); - } - } - }); - // Fired by a click on a message (and on some desktops a double click on the icon). - icon.addActionListener(e -> { - Runnable click = messageClick; - messageClick = null; - if (click != null) click.run(); - }); - SystemTray.getSystemTray().add(icon); - } - - /** - * Shows a message by the icon, which Windows turns into a toast in its notification - * centre and macOS into a banner in its own. - */ - public void showMessage(String title, String body, Runnable onClick) { - messageClick = onClick; - icon.displayMessage(title, body, TrayIcon.MessageType.NONE); - } - - @Override - public void setIcon(IntFunction render) { - Image image = render.apply(size); - if (image != null) icon.setImage(image); - } - - @Override - public void setTooltip(String tooltip) { - icon.setToolTip(tooltip); - } - - @Override - public String description() { - return "AWT's own icon, " + size + "px (the desktop draws a background behind it)"; - } - - @Override - public void dispose() { - SystemTray.getSystemTray().remove(icon); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/tray/TrayBackend.java b/ts3-client/swing/src/main/java/com/ts3client/ui/tray/TrayBackend.java deleted file mode 100644 index 91807b0..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/tray/TrayBackend.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.ts3client.ui.tray; - -import java.awt.Image; -import java.util.function.IntFunction; - -/** A tray icon, however the desktop happens to provide one. */ -public interface TrayBackend { - - /** - * Sets the icon to show. - * - * @param render draws it at the size the tray asks for — panels differ, and the - * size can change while the icon is docked - */ - void setIcon(IntFunction render); - - /** Sets the text the panel shows on hover, where it supports one. */ - void setTooltip(String tooltip); - - /** Takes the icon out of the tray again. */ - void dispose(); - - /** How this icon is being shown, for the client's own diagnostics. */ - String description(); - - /** - * Asks the window manager to bring a window of this application to the front. - * Swing cannot: a window manager ignores a raise from an application that does - * not have the focus, which is exactly the case when the tray icon is used. - * - * @param title the window's title - * @return {@code false} when this backend cannot ask, and the caller should try - * whatever Swing can do - */ - default boolean activateWindow(String title) { - return false; - } - - /** What the user did with the icon. */ - interface Listener { - - /** The icon was clicked (or activated from the keyboard). */ - void activated(); - - /** - * A context menu was asked for at a screen position. Only called by backends - * that have no menu of their own. - */ - void menuRequested(int x, int y); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/tray/TrayLog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/tray/TrayLog.java deleted file mode 100644 index a9bb3c0..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/tray/TrayLog.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.ts3client.ui.tray; - -/** - * Diagnostics for the tray icon, off unless {@code -Dts3j.tray.debug=true} is given. - * - *

    Which backend ends up with the icon depends on what the panel offers, and a - * panel that quietly ignores a docking request leaves nothing to see, so it is - * worth being able to ask. - */ -final class TrayLog { - - private static final boolean ENABLED = Boolean.getBoolean("ts3j.tray.debug"); - - private TrayLog() { - } - - static void debug(String message) { - if (ENABLED) System.err.println("tray: " + message); - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/tray/X11.java b/ts3-client/swing/src/main/java/com/ts3client/ui/tray/X11.java deleted file mode 100644 index abc5fb8..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/tray/X11.java +++ /dev/null @@ -1,470 +0,0 @@ -package com.ts3client.ui.tray; - -import java.lang.foreign.AddressLayout; -import java.lang.foreign.Arena; -import java.lang.foreign.FunctionDescriptor; -import java.lang.foreign.Linker; -import java.lang.foreign.MemorySegment; -import java.lang.foreign.SymbolLookup; -import java.lang.foreign.ValueLayout; -import java.lang.invoke.MethodHandle; -import java.nio.charset.StandardCharsets; - -/** - * Raw binding to {@code libX11} through the Foreign Function & Memory API, with - * just the calls {@link X11Tray} needs. - * - *

    This class is the only place that knows about Xlib's ABI: the entry points, the - * protocol constants and the offsets of the few structures that are read or written - * directly. Loading is lazy and failure is expected — on a machine with no X11 (or a - * pure Wayland session) {@link #isAvailable()} returns {@code false} and the caller - * falls back to AWT's own tray icon. - * - *

    Offsets are those of the LP64 ABI, in which {@code XID}, {@code Atom} and - * {@code long} are 64 bits wide and every field is naturally aligned. - */ -final class X11 { - - private X11() { - } - - static final AddressLayout PTR = ValueLayout.ADDRESS; - static final ValueLayout.OfInt INT = ValueLayout.JAVA_INT; - static final ValueLayout.OfLong LONG = ValueLayout.JAVA_LONG; - - // ---- protocol constants (X.h) ---- - - static final int INPUT_OUTPUT = 1; - static final int ALLOC_NONE = 0; - static final int PROP_MODE_REPLACE = 0; - static final int Z_PIXMAP = 2; - static final int SUCCESS = 0; - - /** Fields of {@code XSetWindowAttributes} passed to {@code XCreateWindow}. */ - static final long CW_BACK_PIXEL = 1L << 1; - static final long CW_BORDER_PIXEL = 1L << 3; - static final long CW_EVENT_MASK = 1L << 11; - static final long CW_COLORMAP = 1L << 13; - - static final long BUTTON_PRESS_MASK = 1L << 2; - static final long SUBSTRUCTURE_NOTIFY_MASK = 1L << 19; - static final long SUBSTRUCTURE_REDIRECT_MASK = 1L << 20; - static final long EXPOSURE_MASK = 1L << 15; - static final long STRUCTURE_NOTIFY_MASK = 1L << 17; - static final long NO_EVENT_MASK = 0L; - - static final int BUTTON_PRESS = 4; - static final int EXPOSE = 12; - static final int MAP_NOTIFY = 19; - static final int REPARENT_NOTIFY = 21; - static final int CONFIGURE_NOTIFY = 22; - static final int CLIENT_MESSAGE = 33; - - /** Predefined atoms (Xatom.h). */ - static final long XA_STRING = 31; - static final long XA_VISUALID = 32; - - static final long VISUAL_ID_MASK = 0x1; - /** {@code AnyPropertyType}: read a property whatever its type. */ - static final long ANY_PROPERTY_TYPE = 0; - - // ---- structure layout ---- - - /** {@code XEvent} is a union; 192 bytes is its size on every LP64 platform. */ - static final long EVENT_SIZE = 192; - static final long EVENT_TYPE = 0; - - /** {@code XExposeEvent} / {@code XConfigureEvent} / {@code XButtonEvent} share this prefix. */ - static final long EVENT_WINDOW = 32; - - /** {@code XConfigureEvent}: the reconfigured window, then its new geometry. */ - static final long CONFIGURE_WINDOW = 40; - static final long CONFIGURE_WIDTH = 56; - static final long CONFIGURE_HEIGHT = 60; - - /** {@code XReparentEvent}: the reparented window and its new parent. */ - static final long REPARENT_WINDOW = 40; - static final long REPARENT_PARENT = 48; - - /** {@code XButtonEvent}. */ - static final long BUTTON_X_ROOT = 72; - static final long BUTTON_Y_ROOT = 76; - static final long BUTTON_BUTTON = 84; - - /** {@code XClientMessageEvent}. */ - static final long CLIENT_MESSAGE_TYPE = 40; - static final long CLIENT_MESSAGE_FORMAT = 48; - static final long CLIENT_MESSAGE_DATA = 56; - - /** {@code XSetWindowAttributes}. */ - static final long ATTRIBUTES_SIZE = 112; - static final long ATTRIBUTES_BACKGROUND_PIXEL = 8; - static final long ATTRIBUTES_BORDER_PIXEL = 24; - static final long ATTRIBUTES_EVENT_MASK = 72; - static final long ATTRIBUTES_COLORMAP = 96; - - /** {@code XSizeHints} fields we set, and its {@code flags} bits (Xutil.h). */ - static final long SIZE_HINTS_SIZE = 80; - static final long SIZE_HINTS_FLAGS = 0; - static final long SIZE_HINTS_MIN_WIDTH = 24; - static final long SIZE_HINTS_MIN_HEIGHT = 28; - static final long SIZE_HINTS_MAX_WIDTH = 32; - static final long SIZE_HINTS_MAX_HEIGHT = 36; - static final long SIZE_HINTS_BASE_WIDTH = 64; - static final long SIZE_HINTS_BASE_HEIGHT = 68; - static final long P_MIN_SIZE = 1L << 4; - static final long P_MAX_SIZE = 1L << 5; - static final long P_BASE_SIZE = 1L << 8; - - /** {@code XVisualInfo}. */ - static final long VISUAL_INFO_SIZE = 64; - static final long VISUAL_INFO_VISUAL = 0; - static final long VISUAL_INFO_VISUALID = 8; - static final long VISUAL_INFO_DEPTH = 20; - - /** {@code XImage}: only the data pointer is touched, to unhook it before freeing. */ - static final long IMAGE_DATA = 16; - - private static final Linker LINKER = Linker.nativeLinker(); - private static final String[] LIBRARY_NAMES = {"libX11.so.6", "libX11.so"}; - - private static final class Handles { - static final SymbolLookup LOOKUP = load(); - - static final MethodHandle X_OPEN_DISPLAY = - downcall("XOpenDisplay", FunctionDescriptor.of(PTR, PTR)); - static final MethodHandle X_CLOSE_DISPLAY = - downcall("XCloseDisplay", FunctionDescriptor.of(INT, PTR)); - static final MethodHandle X_INTERN_ATOM = - downcall("XInternAtom", FunctionDescriptor.of(LONG, PTR, PTR, INT)); - static final MethodHandle X_GET_SELECTION_OWNER = - downcall("XGetSelectionOwner", FunctionDescriptor.of(LONG, PTR, LONG)); - static final MethodHandle X_DEFAULT_SCREEN = - downcall("XDefaultScreen", FunctionDescriptor.of(INT, PTR)); - static final MethodHandle X_ROOT_WINDOW = - downcall("XRootWindow", FunctionDescriptor.of(LONG, PTR, INT)); - static final MethodHandle X_GET_WINDOW_PROPERTY = - downcall("XGetWindowProperty", FunctionDescriptor.of(INT, PTR, LONG, LONG, LONG, LONG, - INT, LONG, PTR, PTR, PTR, PTR, PTR)); - static final MethodHandle X_GET_VISUAL_INFO = - downcall("XGetVisualInfo", FunctionDescriptor.of(PTR, PTR, LONG, PTR, PTR)); - static final MethodHandle X_FREE = - downcall("XFree", FunctionDescriptor.of(INT, PTR)); - static final MethodHandle X_CREATE_COLORMAP = - downcall("XCreateColormap", FunctionDescriptor.of(LONG, PTR, LONG, PTR, INT)); - static final MethodHandle X_CREATE_WINDOW = - downcall("XCreateWindow", FunctionDescriptor.of(LONG, PTR, LONG, INT, INT, INT, INT, - INT, INT, INT, PTR, LONG, PTR)); - static final MethodHandle X_DESTROY_WINDOW = - downcall("XDestroyWindow", FunctionDescriptor.of(INT, PTR, LONG)); - static final MethodHandle X_CHANGE_PROPERTY = - downcall("XChangeProperty", FunctionDescriptor.of(INT, PTR, LONG, LONG, LONG, INT, - INT, PTR, INT)); - static final MethodHandle X_SELECT_INPUT = - downcall("XSelectInput", FunctionDescriptor.of(INT, PTR, LONG, LONG)); - static final MethodHandle X_SEND_EVENT = - downcall("XSendEvent", FunctionDescriptor.of(INT, PTR, LONG, INT, LONG, PTR)); - static final MethodHandle X_QUERY_TREE = - downcall("XQueryTree", FunctionDescriptor.of(INT, PTR, LONG, PTR, PTR, PTR, PTR)); - static final MethodHandle X_SET_WM_NORMAL_HINTS = - downcall("XSetWMNormalHints", FunctionDescriptor.ofVoid(PTR, LONG, PTR)); - static final MethodHandle X_RESIZE_WINDOW = - downcall("XResizeWindow", FunctionDescriptor.of(INT, PTR, LONG, INT, INT)); - static final MethodHandle X_MAP_WINDOW = - downcall("XMapWindow", FunctionDescriptor.of(INT, PTR, LONG)); - static final MethodHandle X_UNMAP_WINDOW = - downcall("XUnmapWindow", FunctionDescriptor.of(INT, PTR, LONG)); - static final MethodHandle X_FLUSH = - downcall("XFlush", FunctionDescriptor.of(INT, PTR)); - static final MethodHandle X_PENDING = - downcall("XPending", FunctionDescriptor.of(INT, PTR)); - static final MethodHandle X_NEXT_EVENT = - downcall("XNextEvent", FunctionDescriptor.of(INT, PTR, PTR)); - static final MethodHandle X_CREATE_GC = - downcall("XCreateGC", FunctionDescriptor.of(PTR, PTR, LONG, LONG, PTR)); - static final MethodHandle X_FREE_GC = - downcall("XFreeGC", FunctionDescriptor.of(INT, PTR, PTR)); - static final MethodHandle X_CREATE_IMAGE = - downcall("XCreateImage", FunctionDescriptor.of(PTR, PTR, PTR, INT, INT, INT, PTR, - INT, INT, INT, INT)); - static final MethodHandle X_PUT_IMAGE = - downcall("XPutImage", FunctionDescriptor.of(INT, PTR, LONG, PTR, PTR, INT, INT, INT, - INT, INT, INT)); - - private static SymbolLookup load() { - IllegalArgumentException last = null; - for (String name : LIBRARY_NAMES) { - try { - return SymbolLookup.libraryLookup(name, Arena.global()); - } catch (IllegalArgumentException e) { - last = e; - } - } - throw (last != null) ? last : new IllegalArgumentException("libX11 not found"); - } - - private static MethodHandle downcall(String symbol, FunctionDescriptor descriptor) { - return LINKER.downcallHandle( - LOOKUP.find(symbol).orElseThrow(() -> - new UnsatisfiedLinkError("libX11: unresolved symbol " + symbol)), - descriptor); - } - } - - /** {@code true} when libX11 could be loaded and every symbol we need resolved. */ - static boolean isAvailable() { - try { - return Handles.LOOKUP != null; - } catch (Throwable t) { - return false; - } - } - - // ---- display ---- - - /** @return the display, or {@link MemorySegment#NULL} when it cannot be opened */ - static MemorySegment openDisplay() { - return (MemorySegment) call(Handles.X_OPEN_DISPLAY, MemorySegment.NULL); - } - - static void closeDisplay(MemorySegment display) { - call(Handles.X_CLOSE_DISPLAY, display); - } - - static int defaultScreen(MemorySegment display) { - return (int) call(Handles.X_DEFAULT_SCREEN, display); - } - - static long rootWindow(MemorySegment display, int screen) { - return (long) call(Handles.X_ROOT_WINDOW, display, screen); - } - - static long internAtom(MemorySegment display, Arena arena, String name) { - return (long) call(Handles.X_INTERN_ATOM, display, arena.allocateFrom(name), 0); - } - - static long selectionOwner(MemorySegment display, long atom) { - return (long) call(Handles.X_GET_SELECTION_OWNER, display, atom); - } - - static void flush(MemorySegment display) { - call(Handles.X_FLUSH, display); - } - - // ---- properties ---- - - /** - * Reads a single 32-bit property value (which Xlib hands back as a C {@code long}). - * - * @return the value, or {@code 0} when the window has no such property - */ - static long cardinalProperty(MemorySegment display, Arena arena, long window, long property, - long type) { - MemorySegment actualType = arena.allocate(LONG); - MemorySegment actualFormat = arena.allocate(INT); - MemorySegment items = arena.allocate(LONG); - MemorySegment bytesAfter = arena.allocate(LONG); - MemorySegment data = arena.allocate(PTR); - int status = (int) call(Handles.X_GET_WINDOW_PROPERTY, display, window, property, 0L, 1L, 0, - type, actualType, actualFormat, items, bytesAfter, data); - MemorySegment values = data.get(PTR, 0); - if (status != SUCCESS || values.equals(MemorySegment.NULL)) return 0; - long value = items.get(LONG, 0) > 0 - ? values.reinterpret(Long.BYTES).get(LONG, 0) - : 0; - call(Handles.X_FREE, values); - return value; - } - - static void setCardinals(MemorySegment display, Arena arena, long window, long property, - long type, long... values) { - MemorySegment data = arena.allocate(LONG, values.length); - for (int i = 0; i < values.length; i++) data.setAtIndex(LONG, i, values[i]); - call(Handles.X_CHANGE_PROPERTY, display, window, property, type, 32, PROP_MODE_REPLACE, - data, values.length); - } - - static void setText(MemorySegment display, Arena arena, long window, long property, long type, - String text) { - byte[] bytes = text.getBytes(StandardCharsets.UTF_8); - MemorySegment data = arena.allocate(bytes.length + 1); - MemorySegment.copy(bytes, 0, data, ValueLayout.JAVA_BYTE, 0, bytes.length); - call(Handles.X_CHANGE_PROPERTY, display, window, property, type, 8, PROP_MODE_REPLACE, - data, bytes.length); - } - - /** @return the children of a window, oldest first */ - static long[] children(MemorySegment display, Arena arena, long window) { - MemorySegment rootReturn = arena.allocate(LONG); - MemorySegment parentReturn = arena.allocate(LONG); - MemorySegment childrenReturn = arena.allocate(PTR); - MemorySegment countReturn = arena.allocate(INT); - int status = (int) call(Handles.X_QUERY_TREE, display, window, rootReturn, parentReturn, - childrenReturn, countReturn); - MemorySegment list = childrenReturn.get(PTR, 0); - if (status == 0 || list.equals(MemorySegment.NULL)) return new long[0]; - int count = countReturn.get(INT, 0); - long[] ids = new long[count]; - MemorySegment windows = list.reinterpret((long) count * Long.BYTES); - for (int i = 0; i < count; i++) ids[i] = windows.getAtIndex(LONG, i); - call(Handles.X_FREE, list); - return ids; - } - - /** - * Reads a text property. - * - * @return its value as UTF-8, or {@code null} when the window has no such property - */ - static String textProperty(MemorySegment display, Arena arena, long window, long property) { - MemorySegment actualType = arena.allocate(LONG); - MemorySegment actualFormat = arena.allocate(INT); - MemorySegment items = arena.allocate(LONG); - MemorySegment bytesAfter = arena.allocate(LONG); - MemorySegment data = arena.allocate(PTR); - int status = (int) call(Handles.X_GET_WINDOW_PROPERTY, display, window, property, 0L, 1024L, - 0, ANY_PROPERTY_TYPE, actualType, actualFormat, items, bytesAfter, data); - MemorySegment value = data.get(PTR, 0); - if (status != SUCCESS || value.equals(MemorySegment.NULL)) return null; - long length = items.get(LONG, 0); - byte[] bytes = value.reinterpret(length).toArray(ValueLayout.JAVA_BYTE); - call(Handles.X_FREE, value); - return new String(bytes, StandardCharsets.UTF_8); - } - - /** @return {@code true} when the window carries the property at all */ - static boolean hasProperty(MemorySegment display, Arena arena, long window, long property) { - MemorySegment actualType = arena.allocate(LONG); - MemorySegment actualFormat = arena.allocate(INT); - MemorySegment items = arena.allocate(LONG); - MemorySegment bytesAfter = arena.allocate(LONG); - MemorySegment data = arena.allocate(PTR); - int status = (int) call(Handles.X_GET_WINDOW_PROPERTY, display, window, property, 0L, 0L, 0, - ANY_PROPERTY_TYPE, actualType, actualFormat, items, bytesAfter, data); - MemorySegment value = data.get(PTR, 0); - if (!value.equals(MemorySegment.NULL)) call(Handles.X_FREE, value); - return status == SUCCESS && actualType.get(LONG, 0) != 0; - } - - // ---- visuals ---- - - /** - * Looks a visual up by id. - * - * @return its {@code XVisualInfo} (owned by Xlib, to be released with {@link #free}) - * or {@link MemorySegment#NULL} when the id is unknown - */ - static MemorySegment visualInfo(MemorySegment display, Arena arena, long visualId) { - MemorySegment template = arena.allocate(VISUAL_INFO_SIZE); - template.set(LONG, VISUAL_INFO_VISUALID, visualId); - MemorySegment count = arena.allocate(INT); - MemorySegment info = (MemorySegment) call(Handles.X_GET_VISUAL_INFO, display, - VISUAL_ID_MASK, template, count); - if (info.equals(MemorySegment.NULL) || count.get(INT, 0) < 1) return MemorySegment.NULL; - return info.reinterpret(VISUAL_INFO_SIZE); - } - - static void free(MemorySegment pointer) { - call(Handles.X_FREE, pointer); - } - - // ---- windows ---- - - static long createColormap(MemorySegment display, long window, MemorySegment visual) { - return (long) call(Handles.X_CREATE_COLORMAP, display, window, visual, ALLOC_NONE); - } - - static long createWindow(MemorySegment display, long parent, int width, int height, int depth, - MemorySegment visual, MemorySegment attributes, long valueMask) { - return (long) call(Handles.X_CREATE_WINDOW, display, parent, 0, 0, width, height, 0, depth, - INPUT_OUTPUT, visual, valueMask, attributes); - } - - static void destroyWindow(MemorySegment display, long window) { - call(Handles.X_DESTROY_WINDOW, display, window); - } - - static void selectInput(MemorySegment display, long window, long mask) { - call(Handles.X_SELECT_INPUT, display, window, mask); - } - - /** - * Tells the panel how big the icon wants to be. XEmbed trays lay their children - * out from these hints; without them a panel is free to allocate a sliver. - */ - static void setSizeHints(MemorySegment display, Arena arena, long window, int size) { - MemorySegment hints = arena.allocate(SIZE_HINTS_SIZE); - hints.fill((byte) 0); - hints.set(LONG, SIZE_HINTS_FLAGS, P_MIN_SIZE | P_MAX_SIZE | P_BASE_SIZE); - hints.set(INT, SIZE_HINTS_MIN_WIDTH, size); - hints.set(INT, SIZE_HINTS_MIN_HEIGHT, size); - hints.set(INT, SIZE_HINTS_MAX_WIDTH, size); - hints.set(INT, SIZE_HINTS_MAX_HEIGHT, size); - hints.set(INT, SIZE_HINTS_BASE_WIDTH, size); - hints.set(INT, SIZE_HINTS_BASE_HEIGHT, size); - call(Handles.X_SET_WM_NORMAL_HINTS, display, window, hints); - } - - static void resizeWindow(MemorySegment display, long window, int width, int height) { - call(Handles.X_RESIZE_WINDOW, display, window, width, height); - } - - static void mapWindow(MemorySegment display, long window) { - call(Handles.X_MAP_WINDOW, display, window); - } - - static void unmapWindow(MemorySegment display, long window) { - call(Handles.X_UNMAP_WINDOW, display, window); - } - - // ---- events ---- - - static int pending(MemorySegment display) { - return (int) call(Handles.X_PENDING, display); - } - - static void nextEvent(MemorySegment display, MemorySegment event) { - call(Handles.X_NEXT_EVENT, display, event); - } - - static void sendEvent(MemorySegment display, long window, long mask, MemorySegment event) { - call(Handles.X_SEND_EVENT, display, window, 0, mask, event); - } - - // ---- drawing ---- - - static MemorySegment createGC(MemorySegment display, long drawable) { - return (MemorySegment) call(Handles.X_CREATE_GC, display, drawable, 0L, MemorySegment.NULL); - } - - static void freeGC(MemorySegment display, MemorySegment gc) { - call(Handles.X_FREE_GC, display, gc); - } - - /** Wraps a caller-owned pixel buffer in an {@code XImage} of 32-bit ARGB pixels. */ - static MemorySegment createImage(MemorySegment display, MemorySegment visual, int depth, - MemorySegment data, int width, int height) { - MemorySegment image = (MemorySegment) call(Handles.X_CREATE_IMAGE, display, visual, depth, - Z_PIXMAP, 0, data, width, height, 32, 0); - return image.equals(MemorySegment.NULL) ? image : image.reinterpret(IMAGE_DATA + 8); - } - - /** Frees the {@code XImage} without touching the pixel buffer, which is ours. */ - static void destroyImage(MemorySegment image) { - image.set(PTR, IMAGE_DATA, MemorySegment.NULL); - call(Handles.X_FREE, image); - } - - static void putImage(MemorySegment display, long drawable, MemorySegment gc, - MemorySegment image, int width, int height) { - call(Handles.X_PUT_IMAGE, display, drawable, gc, image, 0, 0, 0, 0, width, height); - } - - private static Object call(MethodHandle handle, Object... args) { - try { - return handle.invokeWithArguments(args); - } catch (Throwable t) { - throw new IllegalStateException("libX11 call failed", t); - } - } -} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/tray/X11Tray.java b/ts3-client/swing/src/main/java/com/ts3client/ui/tray/X11Tray.java deleted file mode 100644 index f17a581..0000000 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/tray/X11Tray.java +++ /dev/null @@ -1,508 +0,0 @@ -package com.ts3client.ui.tray; - -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.RenderingHints; -import java.awt.image.BufferedImage; -import java.awt.image.DataBufferInt; -import java.lang.foreign.Arena; -import java.lang.foreign.MemorySegment; -import java.lang.foreign.ValueLayout; -import java.util.function.IntFunction; -import java.util.function.LongPredicate; - -/** - * A tray icon docked into the panel's notification area by hand, over the - * freedesktop system tray protocol. - * - *

    AWT can do this too, but its icon is never transparent on X11: the toolkit - * embeds an ordinary window of the screen's default (opaque) visual and fills it - * with a background colour before drawing, so every icon sits on a coloured box. - * Panels that support transparency — MATE's, Xfce's, GNOME's — advertise an ARGB - * visual in {@code _NET_SYSTEM_TRAY_VISUAL} and composite the icon themselves; - * all that is needed is to dock a window of that visual, which is what - * this class does. - * - *

    Everything here runs on one thread of its own, which owns the display - * connection and pumps the X event queue; the rest of the client only posts new - * icons to it. - */ -public final class X11Tray implements TrayBackend { - - /** The size to ask for; the panel resizes us to whatever it wants. */ - private static final int DEFAULT_SIZE = 24; - private static final int POLL_MS = 40; - /** How long to give the panel to adopt the icon before falling back to AWT. */ - private static final int DOCK_TIMEOUT_MS = 500; - /** Anything narrower than this is a sliver, not an icon the panel meant to give us. */ - private static final int MIN_SENSIBLE_SIZE = 8; - /** A tall panel should still not get a huge icon. */ - private static final int MAX_ICON_SIZE = 64; - /** - * Panels that composite the icon themselves need not send us a single expose, so - * the icon is also repainted at this interval — it costs one 24×24 image. - */ - private static final int REPAINT_MS = 2000; - - /** {@code _NET_SYSTEM_TRAY_OPCODE} message: dock this window. */ - private static final long SYSTEM_TRAY_REQUEST_DOCK = 0; - /** {@code _XEMBED_INFO} flag: the icon wants to be mapped. */ - private static final long XEMBED_MAPPED = 1; - - private final Listener listener; - /** Lives as long as the icon: the display connection and every buffer we pass to it. */ - private final Arena arena = Arena.ofShared(); - - private final MemorySegment display; - private final long root; - private final long window; - private final MemorySegment visual; - private final int depth; - private final MemorySegment gc; - - private final long selectionAtom; - private final long opcodeAtom; - private final long managerAtom; - - private final Thread thread; - private volatile boolean running = true; - /** Set once the panel has reparented the icon into itself. */ - private volatile boolean docked; - /** The square size last asked of the panel, so we ask only once per size. */ - private int requested; - - /** The icon and the size the panel gave us, both read by the event thread. */ - private volatile IntFunction render; - private volatile int width = DEFAULT_SIZE; - private volatile int height = DEFAULT_SIZE; - private volatile boolean dirty = true; - - /** The pixel buffer handed to X, kept until the icon's size changes. */ - private MemorySegment pixels; - private long lastDrawn; - private MemorySegment image; - private int imageWidth; - private int imageHeight; - - /** - * Docks an icon into the notification area. - * - * @return the icon, or {@code null} when this is not an X11 session, there is no - * notification area, or it cannot show transparent icons — the caller should then - * fall back to AWT's tray, which works everywhere but always draws a background - */ - public static X11Tray create(Listener listener, IntFunction initial) { - if (!X11.isAvailable()) { - TrayLog.debug("libX11 is not available"); - return null; - } - try { - X11Tray tray = new X11Tray(listener, initial); - TrayLog.debug("docked into the notification area, " + tray.width + "x" + tray.height - + " in an ARGB visual"); - return tray; - } catch (RuntimeException e) { - TrayLog.debug("not usable: " + e.getMessage()); - return null; - } - } - - private X11Tray(Listener listener, IntFunction initial) { - this.listener = listener; - this.render = initial; - - display = X11.openDisplay(); - if (display.equals(MemorySegment.NULL)) throw new Unsupported("no display"); - boolean ok = false; - try { - int screen = X11.defaultScreen(display); - root = X11.rootWindow(display, screen); - - selectionAtom = X11.internAtom(display, arena, "_NET_SYSTEM_TRAY_S" + screen); - opcodeAtom = X11.internAtom(display, arena, "_NET_SYSTEM_TRAY_OPCODE"); - managerAtom = X11.internAtom(display, arena, "MANAGER"); - - long manager = X11.selectionOwner(display, selectionAtom); - if (manager == 0) throw new Unsupported("no notification area"); - - visual = argbVisual(manager); - depth = 32; // argbVisual() accepts nothing else - window = createWindow(); - gc = X11.createGC(display, window); - - // Panels announce themselves with a MANAGER message when they (re)start, - // which is our cue to dock again. - X11.selectInput(display, root, X11.STRUCTURE_NOTIFY_MASK); - requestDock(manager); - // Docking is a request, not a call: a panel that ignores it would leave us - // with an invisible window and the user with no icon at all. - if (!awaitDock()) throw new Unsupported("the notification area did not adopt the icon"); - - thread = new Thread(this::pump, "x11-tray"); - thread.setDaemon(true); - thread.start(); - ok = true; - } finally { - if (!ok) { - X11.closeDisplay(display); - arena.close(); - } - } - } - - // ---- setup ---- - - /** - * @return the visual the panel wants transparent icons drawn in - * @throws Unsupported when it offers none, so nothing would be gained over AWT - */ - private MemorySegment argbVisual(long manager) { - long visualAtom = X11.internAtom(display, arena, "_NET_SYSTEM_TRAY_VISUAL"); - long visualId = X11.cardinalProperty(display, arena, manager, visualAtom, X11.XA_VISUALID); - if (visualId == 0) throw new Unsupported("the notification area is not transparent"); - - MemorySegment info = X11.visualInfo(display, arena, visualId); - if (info.equals(MemorySegment.NULL)) throw new Unsupported("unknown visual " + visualId); - try { - int visualDepth = info.get(ValueLayout.JAVA_INT, X11.VISUAL_INFO_DEPTH); - if (visualDepth != 32) { - throw new Unsupported("visual " + visualId + " has depth " + visualDepth); - } - // The XVisualInfo itself is Xlib's, but the Visual it points at outlives it. - return info.get(X11.PTR, X11.VISUAL_INFO_VISUAL); - } finally { - X11.free(info); - } - } - - private long createWindow() { - MemorySegment attributes = arena.allocate(X11.ATTRIBUTES_SIZE); - // Fully transparent background, and no border pixmap inherited from the root: - // a window whose depth differs from its parent's must name its own. - attributes.set(ValueLayout.JAVA_LONG, X11.ATTRIBUTES_BACKGROUND_PIXEL, 0); - attributes.set(ValueLayout.JAVA_LONG, X11.ATTRIBUTES_BORDER_PIXEL, 0); - attributes.set(ValueLayout.JAVA_LONG, X11.ATTRIBUTES_COLORMAP, - X11.createColormap(display, root, visual)); - attributes.set(ValueLayout.JAVA_LONG, X11.ATTRIBUTES_EVENT_MASK, - X11.EXPOSURE_MASK | X11.STRUCTURE_NOTIFY_MASK | X11.BUTTON_PRESS_MASK); - long mask = X11.CW_BACK_PIXEL | X11.CW_BORDER_PIXEL | X11.CW_COLORMAP | X11.CW_EVENT_MASK; - - long id = X11.createWindow(display, root, DEFAULT_SIZE, DEFAULT_SIZE, depth, visual, - attributes, mask); - if (id == 0) throw new Unsupported("could not create the icon window"); - - // Panels lay their icons out from these; without them MATE's allocates a - // one-pixel-wide sliver, which looks exactly like no icon at all. - X11.setSizeHints(display, arena, id, DEFAULT_SIZE); - - X11.setText(display, arena, id, X11.internAtom(display, arena, "WM_NAME"), - X11.XA_STRING, "TS3J"); - // XEMBED protocol version 0, and "please map me". - long xembedInfo = X11.internAtom(display, arena, "_XEMBED_INFO"); - X11.setCardinals(display, arena, id, xembedInfo, xembedInfo, 0, XEMBED_MAPPED); - return id; - } - - /** Asks the notification area to adopt our window. */ - private void requestDock(long manager) { - MemorySegment event = arena.allocate(X11.EVENT_SIZE); - event.fill((byte) 0); - event.set(ValueLayout.JAVA_INT, X11.EVENT_TYPE, X11.CLIENT_MESSAGE); - event.set(ValueLayout.JAVA_LONG, X11.EVENT_WINDOW, manager); - event.set(ValueLayout.JAVA_LONG, X11.CLIENT_MESSAGE_TYPE, opcodeAtom); - event.set(ValueLayout.JAVA_INT, X11.CLIENT_MESSAGE_FORMAT, 32); - event.set(ValueLayout.JAVA_LONG, X11.CLIENT_MESSAGE_DATA, 0); // CurrentTime - event.set(ValueLayout.JAVA_LONG, X11.CLIENT_MESSAGE_DATA + 8, SYSTEM_TRAY_REQUEST_DOCK); - event.set(ValueLayout.JAVA_LONG, X11.CLIENT_MESSAGE_DATA + 16, window); - X11.sendEvent(display, manager, X11.NO_EVENT_MASK, event); - X11.flush(display); - } - - /** - * Waits for the panel to reparent the icon into itself. - * - * @return {@code false} when it did not within {@link #DOCK_TIMEOUT_MS} - */ - private boolean awaitDock() { - MemorySegment event = arena.allocate(X11.EVENT_SIZE); - long deadline = System.currentTimeMillis() + DOCK_TIMEOUT_MS; - while (!docked && System.currentTimeMillis() < deadline) { - while (!docked && X11.pending(display) > 0) { - X11.nextEvent(display, event); - handle(event); - } - if (docked) break; - try { - Thread.sleep(POLL_MS); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return false; - } - } - return docked; - } - - // ---- TrayBackend ---- - - @Override - public void setIcon(IntFunction render) { - this.render = render; - dirty = true; - } - - @Override - public void setTooltip(String tooltip) { - // Panels take the tooltip from the icon window's name; those that don't show - // nothing, which is what AWT's own icon does on X11 anyway. - synchronized (this) { - if (!running) return; - X11.setText(display, arena, window, X11.internAtom(display, arena, "WM_NAME"), - X11.XA_STRING, tooltip); - X11.setText(display, arena, window, X11.internAtom(display, arena, "_NET_WM_NAME"), - X11.internAtom(display, arena, "UTF8_STRING"), tooltip); - X11.flush(display); - } - } - - /** - * Sends the window manager an {@code _NET_ACTIVE_WINDOW} request for the named - * window — the EWMH way of saying "the user asked for this window", which is - * honoured where a plain raise is not. - */ - @Override - public boolean activateWindow(String title) { - synchronized (this) { - if (!running) return false; - long target = findWindow(title); - if (target == 0) { - TrayLog.debug("no window named \"" + title + "\" to activate"); - return false; - } - TrayLog.debug("activating window 0x" + Long.toHexString(target)); - - MemorySegment event = arena.allocate(X11.EVENT_SIZE); - event.fill((byte) 0); - event.set(ValueLayout.JAVA_INT, X11.EVENT_TYPE, X11.CLIENT_MESSAGE); - event.set(ValueLayout.JAVA_LONG, X11.EVENT_WINDOW, target); - event.set(ValueLayout.JAVA_LONG, X11.CLIENT_MESSAGE_TYPE, - X11.internAtom(display, arena, "_NET_ACTIVE_WINDOW")); - event.set(ValueLayout.JAVA_INT, X11.CLIENT_MESSAGE_FORMAT, 32); - // Source indication 2: a pager or tray acting for the user, which window - // managers accept without their focus-stealing rules getting in the way. - event.set(ValueLayout.JAVA_LONG, X11.CLIENT_MESSAGE_DATA, 2); - X11.sendEvent(display, root, - X11.SUBSTRUCTURE_NOTIFY_MASK | X11.SUBSTRUCTURE_REDIRECT_MASK, event); - X11.flush(display); - return true; - } - } - - /** - * Finds one of this process' own top-level windows: the one with the given title - * for choice, else any window the window manager is managing for us. - * - *

    Windows are matched by {@code _NET_WM_PID} rather than by name alone, and - * the title is read from {@code _NET_WM_NAME} because {@code WM_NAME} cannot - * carry anything outside Latin-1. - */ - private long findWindow(String title) { - long pid = ProcessHandle.current().pid(); - long pidAtom = X11.internAtom(display, arena, "_NET_WM_PID"); - long nameAtom = X11.internAtom(display, arena, "_NET_WM_NAME"); - long stateAtom = X11.internAtom(display, arena, "WM_STATE"); - - long found = findWindow(root, 0, w -> - X11.cardinalProperty(display, arena, w, pidAtom, X11.ANY_PROPERTY_TYPE) == pid - && title.equals(X11.textProperty(display, arena, w, nameAtom))); - if (found != 0) return found; - return findWindow(root, 0, w -> - X11.cardinalProperty(display, arena, w, pidAtom, X11.ANY_PROPERTY_TYPE) == pid - && X11.hasProperty(display, arena, w, stateAtom)); - } - - /** - * Walks the window tree below {@code parent}. Only the top few levels are looked - * at: a reparenting window manager puts client windows one or two frames below - * the root. - */ - private long findWindow(long parent, int depth, LongPredicate match) { - if (depth > 3) return 0; - for (long child : X11.children(display, arena, parent)) { - if (match.test(child)) return child; - long found = findWindow(child, depth + 1, match); - if (found != 0) return found; - } - return 0; - } - - @Override - public String description() { - return "docked into the notification area, " + width + "x" + height + ", transparent"; - } - - @Override - public void dispose() { - if (!running) return; - running = false; - try { - thread.join(500); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - synchronized (this) { - if (image != null) X11.destroyImage(image); - X11.freeGC(display, gc); - X11.destroyWindow(display, window); - X11.closeDisplay(display); - } - arena.close(); - } - - // ---- event thread ---- - - private void pump() { - MemorySegment event = arena.allocate(X11.EVENT_SIZE); - while (running) { - try { - synchronized (this) { - while (running && X11.pending(display) > 0) { - X11.nextEvent(display, event); - handle(event); - } - boolean due = System.currentTimeMillis() - lastDrawn >= REPAINT_MS; - if (running && (dirty || due)) { - dirty = false; - lastDrawn = System.currentTimeMillis(); - draw(); - } - } - Thread.sleep(POLL_MS); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return; - } catch (RuntimeException e) { - TrayLog.debug("the display connection failed: " + e.getMessage()); - return; // the display died with the panel or the session - } - } - } - - private void handle(MemorySegment event) { - switch (event.get(ValueLayout.JAVA_INT, X11.EVENT_TYPE)) { - case X11.EXPOSE -> dirty = true; - case X11.CONFIGURE_NOTIFY -> { - if (event.get(ValueLayout.JAVA_LONG, X11.CONFIGURE_WINDOW) != window) return; - int w = event.get(ValueLayout.JAVA_INT, X11.CONFIGURE_WIDTH); - int h = event.get(ValueLayout.JAVA_INT, X11.CONFIGURE_HEIGHT); - if (w == width && h == height) return; - width = w; - height = h; - dirty = true; - askForSquare(); - } - case X11.REPARENT_NOTIFY -> { - if (event.get(ValueLayout.JAVA_LONG, X11.REPARENT_WINDOW) != window) return; - if (event.get(ValueLayout.JAVA_LONG, X11.REPARENT_PARENT) == root) { - // The panel went away and handed the window back to the root; hide - // it so it does not turn up in the middle of the screen. - docked = false; - X11.unmapWindow(display, window); - } else { - // Adopted. The panel is meant to map us because of _XEMBED_INFO, - // but mapping ourselves costs nothing and does not depend on it. - docked = true; - X11.mapWindow(display, window); - dirty = true; - } - } - case X11.MAP_NOTIFY -> dirty = true; - case X11.BUTTON_PRESS -> { - long button = event.get(ValueLayout.JAVA_INT, X11.BUTTON_BUTTON); - int x = event.get(ValueLayout.JAVA_INT, X11.BUTTON_X_ROOT); - int y = event.get(ValueLayout.JAVA_INT, X11.BUTTON_Y_ROOT); - if (button == 1) { - listener.activated(); - } else if (button == 3) { - listener.menuRequested(x, y); - } - } - case X11.CLIENT_MESSAGE -> { - // A panel started: dock into it. - if (event.get(ValueLayout.JAVA_LONG, X11.CLIENT_MESSAGE_TYPE) != managerAtom) return; - if (event.get(ValueLayout.JAVA_LONG, X11.CLIENT_MESSAGE_DATA + 8) != selectionAtom) { - return; - } - long manager = event.get(ValueLayout.JAVA_LONG, X11.CLIENT_MESSAGE_DATA + 16); - if (manager != 0) { - requestDock(manager); - X11.mapWindow(display, window); - dirty = true; - } - } - default -> { - } - } - } - - /** - * Asks for a square icon when the panel has given us a sliver — its idea of the - * icon size is then the other side, and a panel that lays out from the size hints - * grants it. Each size is asked for once, so a panel that refuses cannot put us - * in a loop. - */ - private void askForSquare() { - int narrow = Math.min(width, height); - int wide = Math.max(width, height); - // Only a sliver is worth arguing about; any sane allocation is left alone. - if (narrow >= MIN_SENSIBLE_SIZE) return; - int wanted = Math.min(wide, MAX_ICON_SIZE); - if (wanted <= 0 || wanted == requested) return; - requested = wanted; - X11.setSizeHints(display, arena, window, wanted); - X11.resizeWindow(display, window, wanted, wanted); - X11.flush(display); - } - - /** Paints the current icon over the whole window, alpha and all. */ - private void draw() { - IntFunction painter = render; - if (painter == null) return; - int w = width; - int h = height; - if (w <= 0 || h <= 0) return; - - if (image == null || imageWidth != w || imageHeight != h) { - if (image != null) X11.destroyImage(image); - pixels = arena.allocate((long) w * h * Integer.BYTES); - image = X11.createImage(display, visual, depth, pixels, w, h); - imageWidth = w; - imageHeight = h; - if (image.equals(MemorySegment.NULL)) { - image = null; - return; - } - } - - // X wants the pixels premultiplied, in the server's own byte order — which - // for a 32-bit ARGB visual on a local display is an int per pixel. - BufferedImage buffer = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE); - Graphics2D g = buffer.createGraphics(); - g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, - RenderingHints.VALUE_INTERPOLATION_BILINEAR); - Image icon = painter.apply(Math.min(w, h)); - if (icon != null) g.drawImage(icon, 0, 0, w, h, null); - g.dispose(); - - int[] data = ((DataBufferInt) buffer.getRaster().getDataBuffer()).getData(); - MemorySegment.copy(data, 0, pixels, ValueLayout.JAVA_INT, 0, data.length); - X11.putImage(display, window, gc, image, w, h); - X11.flush(display); - } - - /** Thrown while setting up when this desktop cannot do what we need. */ - private static final class Unsupported extends RuntimeException { - Unsupported(String message) { - super(message); - } - } -} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/Main.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/Main.java new file mode 100644 index 0000000..ec2faa5 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/Main.java @@ -0,0 +1,48 @@ +package eu.lixko.ts3j.client; + +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.session.ServerLink; +import eu.lixko.ts3j.client.ui.DesktopEntry; +import eu.lixko.ts3j.client.ui.DisplayScale; +import eu.lixko.ts3j.client.ui.IconTheme; +import eu.lixko.ts3j.client.ui.InstanceChannel; +import eu.lixko.ts3j.client.ui.LookAndFeelManager; +import eu.lixko.ts3j.client.ui.MainFrame; +import eu.lixko.ts3j.client.ui.WindowClass; + +import javax.swing.SwingUtilities; +import java.util.Arrays; + +/** + * Application entry point. Loads settings, installs the look-and-feel and shows the + * main window on the Swing event dispatch thread. + */ +public final class Main { + + public static void main(String[] args) { + // ts3j is verbose by default; keep the console quiet unless asked for its protocol log + // (-Dts3j.debug=true, written to stderr). + try { + com.github.manevolent.ts3j.util.Ts3Debugging.setEnabled(Boolean.getBoolean("ts3j.debug")); + } catch (Throwable ignored) { + } + + // A link a browser opened goes to the instance already running, if there is one. + final String link = Arrays.stream(args).filter(ServerLink::isLink).findFirst().orElse(null); + if (link != null && InstanceChannel.send(link)) return; + + final Settings settings = Settings.load(); + DisplayScale.configure(settings.uiScale); + WindowClass.apply(); + + SwingUtilities.invokeLater(() -> { + LookAndFeelManager.install(settings.appearance); + IconTheme.get().reload(settings); + DesktopEntry.install(); + MainFrame frame = new MainFrame(settings); + frame.setVisible(true); + InstanceChannel.listen(href -> SwingUtilities.invokeLater(() -> frame.openLink(href))); + if (link != null) frame.openLink(link); + }); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ApplicationPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ApplicationPanel.java new file mode 100644 index 0000000..2b39a93 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ApplicationPanel.java @@ -0,0 +1,35 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.config.Settings; + +import javax.swing.JCheckBox; +import java.awt.GridBagConstraints; + +/** Options page for general behaviour: the muted-microphone warning and the reported client version. */ +final class ApplicationPanel extends FormPanel { + + private final Settings settings; + private final JCheckBox mutedWarning; + private final ClientVersionPanel clientVersion; + + ApplicationPanel(Settings settings) { + this.settings = settings; + GridBagConstraints c = gbc(); + + mutedWarning = new JCheckBox("Warn when talking while microphone is muted", settings.mutedTalkWarning); + clientVersion = new ClientVersionPanel(settings); + + int row = 0; + addSection(this, c, row++, "Misc"); + addWide(this, c, row++, mutedWarning); + addSection(this, c, row++, "Client Version"); + addWide(this, c, row++, clientVersion); + addFiller(this, c, row); + } + + /** Copies the page into the settings; the caller saves them. */ + void apply() { + settings.mutedTalkWarning = mutedWarning.isSelected(); + clientVersion.apply(); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AttachmentTransferHandler.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AttachmentTransferHandler.java new file mode 100644 index 0000000..a5df171 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AttachmentTransferHandler.java @@ -0,0 +1,128 @@ +package eu.lixko.ts3j.client.ui; + +import javax.swing.JComponent; +import javax.swing.TransferHandler; +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.datatransfer.Clipboard; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.Transferable; +import java.awt.datatransfer.UnsupportedFlavorException; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +/** + * Takes files and pictures dropped or pasted onto a chat view as files to share, and leaves + * everything else (text, client links) to the component's own handler. + */ +final class AttachmentTransferHandler extends TransferHandler { + + interface Sink { + /** @return whether the files were taken */ + boolean files(List files); + + boolean image(BufferedImage image); + } + + /** How file managers that Java does not translate hand over files. */ + private static final DataFlavor URI_LIST = flavor("text/uri-list;class=java.lang.String"); + + private final TransferHandler delegate; + private final Sink sink; + + AttachmentTransferHandler(TransferHandler delegate, Sink sink) { + this.delegate = delegate; + this.sink = sink; + } + + @Override + public boolean canImport(TransferSupport support) { + if (isFiles(support.getDataFlavors()) || isPicture(support.getDataFlavors())) return true; + return delegate != null && delegate.canImport(support); + } + + @Override + public boolean importData(TransferSupport support) { + DataFlavor[] flavors = support.getDataFlavors(); + Transferable t = support.getTransferable(); + try { + if (isFiles(flavors)) { + List files = files(t); + if (!files.isEmpty()) return sink.files(files); + } else if (isPicture(flavors)) { + return sink.image(buffered((Image) t.getTransferData(DataFlavor.imageFlavor))); + } + } catch (UnsupportedFlavorException | IOException e) { + return false; + } + return delegate != null && delegate.importData(support); + } + + @Override + public int getSourceActions(JComponent c) { + return delegate == null ? NONE : delegate.getSourceActions(c); + } + + @Override + public void exportToClipboard(JComponent comp, Clipboard clip, int action) { + if (delegate != null) delegate.exportToClipboard(comp, clip, action); + } + + private static boolean isFiles(DataFlavor[] flavors) { + for (DataFlavor f : flavors) { + if (f.equals(DataFlavor.javaFileListFlavor) || f.equals(URI_LIST)) return true; + } + return false; + } + + /** A picture alone: one that comes with text is text that also offers a rendering of itself. */ + private static boolean isPicture(DataFlavor[] flavors) { + boolean image = false; + for (DataFlavor f : flavors) { + if (f.equals(DataFlavor.imageFlavor)) image = true; + else if (f.equals(DataFlavor.stringFlavor)) return false; + } + return image; + } + + @SuppressWarnings("unchecked") + private static List files(Transferable t) throws UnsupportedFlavorException, IOException { + if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { + return new ArrayList<>((List) t.getTransferData(DataFlavor.javaFileListFlavor)); + } + List files = new ArrayList<>(); + for (String line : ((String) t.getTransferData(URI_LIST)).split("\r?\n")) { + line = line.trim(); + if (line.isEmpty() || line.startsWith("#")) continue; + try { + URI uri = URI.create(line); + if (!"file".equals(uri.getScheme())) return List.of(); + files.add(new File(uri)); + } catch (IllegalArgumentException e) { + return List.of(); + } + } + return files; + } + + private static BufferedImage buffered(Image image) { + if (image instanceof BufferedImage b) return b; + BufferedImage b = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB); + Graphics2D g = b.createGraphics(); + g.drawImage(image, 0, 0, null); + g.dispose(); + return b; + } + + private static DataFlavor flavor(String mime) { + try { + return new DataFlavor(mime); + } catch (ClassNotFoundException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AudioDevices.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AudioDevices.java new file mode 100644 index 0000000..d717946 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AudioDevices.java @@ -0,0 +1,39 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.audio.AudioDevice; + +import javax.swing.JComboBox; +import java.util.List; + +/** The device pickers of the Playback and Capture pages. */ +final class AudioDevices { + + private static final String HINT = "Named devices are PipeWire's, and are routed through it " + + "(so per-application volume and rerouting keep working).
    " + + "ALSA: entries talk to the sound card directly, taking it exclusively."; + + private AudioDevices() { + } + + /** A picker over {@code devices} with {@code selectedId} chosen, or the first (default) one. */ + static JComboBox combo(List devices, String selectedId) { + JComboBox combo = new JComboBox<>(devices.toArray(new AudioDevice[0])); + combo.setToolTipText(HINT); + if (combo.getItemCount() == 0) return combo; + combo.setSelectedIndex(0); + if (selectedId != null && !selectedId.isEmpty()) { + for (int i = 0; i < combo.getItemCount(); i++) { + if (selectedId.equals(combo.getItemAt(i).id())) { + combo.setSelectedIndex(i); + break; + } + } + } + return combo; + } + + static String selectedId(JComboBox combo) { + AudioDevice d = (AudioDevice) combo.getSelectedItem(); + return d == null ? "" : d.id(); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AvatarActions.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AvatarActions.java new file mode 100644 index 0000000..04141f7 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AvatarActions.java @@ -0,0 +1,76 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.net.ClientEntry; +import eu.lixko.ts3j.client.net.TeamspeakConnection; +import eu.lixko.ts3j.client.net.avatar.Avatar; + +import javax.swing.JFileChooser; +import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; +import javax.swing.filechooser.FileNameExtensionFilter; +import java.awt.Component; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; + +/** Sets, takes and deletes our avatar on one server, reporting failures in a dialog. */ +final class AvatarActions { + + /** Where the last avatar was picked from, for every server alike. */ + private static File lastDirectory; + + private final Component owner; + private final TeamspeakConnection conn; + + AvatarActions(Component owner, TeamspeakConnection conn) { + this.owner = owner; + this.conn = conn; + } + + /** Asks for an image and uploads it as our avatar. */ + void choose() { + if (!conn.isConnected()) return; + JFileChooser chooser = new JFileChooser(lastDirectory); + chooser.setDialogTitle("Select your avatar"); + chooser.setFileFilter(new FileNameExtensionFilter("Images", "png", "jpg", "jpeg", "gif", "bmp")); + if (chooser.showOpenDialog(owner) != JFileChooser.APPROVE_OPTION) return; + File file = chooser.getSelectedFile(); + lastDirectory = file.getParentFile(); + conn.setAvatar(file, error -> fail("Error uploading avatar: ", error)); + } + + /** Uploads someone else's avatar as ours. */ + void steal(Avatar avatar) { + if (!conn.isConnected()) return; + File file; + try { + file = Files.createTempFile("avatar", "." + avatar.format().extension).toFile(); + Files.write(file.toPath(), avatar.data()); + } catch (IOException e) { + fail("Error uploading avatar: ", e.getMessage()); + return; + } + conn.setAvatar(file, error -> { + file.delete(); + fail("Error uploading avatar: ", error); + }); + } + + void delete() { + if (!conn.isConnected()) return; + conn.removeAvatar(error -> fail("Error deleting avatar: ", error)); + } + + /** Deletes another client's avatar for everyone. */ + void deleteOf(ClientEntry client) { + if (!conn.isConnected()) return; + conn.removeAvatarOf(client, error -> fail("Error deleting avatar: ", error)); + } + + /** Shows {@code error}, if there is one; callable from any thread. */ + private void fail(String what, String error) { + if (error == null) return; + SwingUtilities.invokeLater(() -> + JOptionPane.showMessageDialog(owner, what + error, "Error", JOptionPane.ERROR_MESSAGE)); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AvatarHtml.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AvatarHtml.java new file mode 100644 index 0000000..adcb507 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AvatarHtml.java @@ -0,0 +1,61 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.net.avatar.Avatar; + +import javax.imageio.ImageIO; +import javax.imageio.ImageReader; +import javax.imageio.stream.ImageInputStream; +import java.awt.Dimension; +import java.io.ByteArrayInputStream; +import java.util.Iterator; + +/** + * Renders an avatar as an HTML {@code } for the info views. Swing's HTML renderer + * loads images by URL and plays animated GIFs on its own, so the tag simply points at + * the repository's on-disk copy, drawn at the interface scale and fitted to a box while + * keeping its aspect ratio. + */ +final class AvatarHtml { + + /** The largest box an avatar is drawn in, as in the official client's info frame. */ + static final int MAX_SIZE = 200; + + private AvatarHtml() { + } + + /** @return the tag, or an empty string if the avatar cannot be shown */ + static String imgTag(Avatar avatar, int maxSize) { + if (avatar == null || avatar.file() == null) return ""; + Dimension natural = dimensions(avatar.data()); + Dimension size = fit(natural == null ? null : UIScale.scale(natural), maxSize); + String dims = size == null ? "" : " width='" + size.width + "' height='" + size.height + "'"; + return ""; + } + + /** Reads only the image header, which is cheap even for a large animation. */ + static Dimension dimensions(byte[] data) { + try (ImageInputStream in = ImageIO.createImageInputStream(new ByteArrayInputStream(data))) { + Iterator readers = ImageIO.getImageReaders(in); + if (!readers.hasNext()) return null; + ImageReader reader = readers.next(); + try { + reader.setInput(in); + return new Dimension(reader.getWidth(0), reader.getHeight(0)); + } finally { + reader.dispose(); + } + } catch (Exception e) { + return null; + } + } + + /** Scales {@code size} down (never up) to fit a square box of {@code max}. */ + static Dimension fit(Dimension size, int max) { + if (size == null || size.width <= 0 || size.height <= 0) return null; + if (size.width <= max && size.height <= max) return size; + double scale = Math.min((double) max / size.width, (double) max / size.height); + return new Dimension(Math.max(1, (int) Math.round(size.width * scale)), + Math.max(1, (int) Math.round(size.height * scale))); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AwayMessagesDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AwayMessagesDialog.java new file mode 100644 index 0000000..45b0c90 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/AwayMessagesDialog.java @@ -0,0 +1,149 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.config.AwayMessages; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.ListSelectionModel; +import javax.swing.table.AbstractTableModel; +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Frame; + +/** + * Editor for the away-message presets: a plain list of entries that are renamed + * by double-clicking them, plus Add and Remove. + * + *

    Backed by a one-column table because that is what gives Swing's list look + * inline editing for free. Every change is written straight through to the + * {@link AwayMessages} store. + */ +public final class AwayMessagesDialog extends JDialog { + + private final AwayMessages messages; + private final Runnable onChanged; + private final Model model = new Model(); + private final JTable table = new JTable(model); + + public AwayMessagesDialog(Frame owner, AwayMessages messages, Runnable onChanged) { + super(owner, "Away Message Presets", true); + this.messages = messages; + this.onChanged = onChanged; + + table.setTableHeader(null); + table.setShowGrid(false); + table.setFillsViewportHeight(true); + table.setRowHeight(Math.max(UIScale.scale(20), table.getRowHeight())); + table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + // Single click selects, double click starts editing — like a renameable list. + table.putClientProperty("JTable.autoStartsEdit", Boolean.FALSE); + + JScrollPane scroll = new JScrollPane(table); + scroll.setBorder(new ScaledEmptyBorder(8, 8, 4, 8)); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(scroll, BorderLayout.CENTER); + getContentPane().add(buildButtons(), BorderLayout.SOUTH); + + Dialogs.closeOnEscape(this, this::closeDialog); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + setSize(UIScale.scale(new Dimension(360, 300))); + setLocationRelativeTo(owner); + } + + private JPanel buildButtons() { + JPanel buttons = new JPanel(); + buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS)); + buttons.setBorder(new ScaledEmptyBorder(0, 8, 8, 8)); + addButton(buttons, "Add", this::addEntry); + addButton(buttons, "Remove", this::removeSelected); + buttons.add(Box.createHorizontalGlue()); + addButton(buttons, "Close", this::closeDialog); + return buttons; + } + + private void addButton(JPanel panel, String text, Runnable action) { + JButton b = new JButton(text); + b.addActionListener(e -> action.run()); + panel.add(b); + panel.add(Box.createHorizontalStrut(UIScale.scale(4))); + } + + private void addEntry() { + stopEditing(); + messages.add("New away message"); + int row = messages.all().size() - 1; + model.fireTableRowsInserted(row, row); + table.setRowSelectionInterval(row, row); + table.scrollRectToVisible(table.getCellRect(row, 0, true)); + persist(); + table.editCellAt(row, 0); + if (table.getEditorComponent() != null) table.getEditorComponent().requestFocusInWindow(); + } + + private void removeSelected() { + stopEditing(); + int row = table.getSelectedRow(); + if (row < 0) return; + messages.remove(row); + model.fireTableRowsDeleted(row, row); + if (!messages.all().isEmpty()) { + int next = Math.min(row, messages.all().size() - 1); + table.setRowSelectionInterval(next, next); + } + persist(); + } + + private void closeDialog() { + stopEditing(); + dispose(); + } + + /** Flushes a cell that is still being edited so its text is not lost. */ + private void stopEditing() { + if (table.isEditing()) table.getCellEditor().stopCellEditing(); + } + + private void persist() { + messages.save(); + if (onChanged != null) onChanged.run(); + } + + private final class Model extends AbstractTableModel { + + @Override + public int getRowCount() { + return messages.all().size(); + } + + @Override + public int getColumnCount() { + return 1; + } + + @Override + public Object getValueAt(int row, int column) { + return messages.all().get(row); + } + + @Override + public boolean isCellEditable(int row, int column) { + return true; + } + + @Override + public void setValueAt(Object value, int row, int column) { + String text = value == null ? "" : value.toString().trim(); + if (text.isEmpty()) return; // an emptied entry keeps its old text + messages.set(row, text); + persist(); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanAddDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanAddDialog.java new file mode 100644 index 0000000..610a116 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanAddDialog.java @@ -0,0 +1,257 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.config.BanReasonPresets; +import eu.lixko.ts3j.client.net.ban.BanEntry; +import eu.lixko.ts3j.client.net.ban.BanPattern; +import eu.lixko.ts3j.client.net.ban.BanRule; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Frame; + +/** + * The ban list's "Add Ban" / "Edit Ban" dialog, laid out like the official client's: + * an IP and a nickname pattern with a choice of how to read them, a unique + * identifier, a myTeamSpeak id, the reason (with saved presets) and the duration. + * + *

    OK stays disabled until the ban has at least one thing to match and its patterns + * are valid expressions; a pattern the server would reject is flagged in red. + */ +final class BanAddDialog extends JDialog { + + private static final String NO_PRESET = "None"; + private static final Color INVALID_BG = new Color(0xC0, 0x00, 0x00); + + private final BanReasonPresets presets; + private final Color fieldBg; + private final Color fieldFg; + + private final JTextField ipField = new JTextField(30); + private final JTextField nameField = new JTextField(30); + private final JComboBox patternBox = new JComboBox<>(BanPattern.values()); + private final JTextField uidField = new JTextField(30); + private final JTextField mytsidField = new JTextField(30); + private final JComboBox presetBox = new JComboBox<>(); + private final JTextField reasonField = ReasonDialog.reasonField(BanRule.REASON_LIMIT); + private final BanDurationPicker duration; + private final JButton ok = new JButton("OK"); + + private BanRule result; + + /** + * @param existing the ban being edited, or {@code null} to add a new one + * @param maxSeconds the longest ban the server lets us hand out, or 0 for no limit + */ + BanAddDialog(Frame owner, BanReasonPresets presets, BanEntry existing, long maxSeconds) { + super(owner, existing == null ? "Add Ban" : "Edit Ban", true); + this.presets = presets; + this.duration = new BanDurationPicker(maxSeconds); + fieldBg = ipField.getBackground(); + fieldFg = ipField.getForeground(); + + patternBox.setRenderer(new PatternRenderer()); + patternBox.addActionListener(e -> checkValid()); + for (JTextField f : new JTextField[] {ipField, nameField, uidField, mytsidField}) { + f.setAlignmentX(Component.LEFT_ALIGNMENT); + ReasonDialog.fixHeight(f); + onEdit(f, this::checkValid); + } + duration.onChange(this::checkValid); + reasonField.addActionListener(e -> { + if (ok.isEnabled()) accept(); + }); + + JPanel form = new JPanel(); + form.setLayout(new BoxLayout(form, BoxLayout.Y_AXIS)); + form.setBorder(new ScaledEmptyBorder(12, 12, 8, 12)); + form.add(ReasonDialog.label("IP:")); + form.add(ipField); + form.add(Box.createVerticalStrut(UIScale.scale(8))); + form.add(ReasonDialog.label("Name:")); + form.add(nameField); + form.add(Box.createVerticalStrut(UIScale.scale(8))); + form.add(patternRow()); + form.add(Box.createVerticalStrut(UIScale.scale(8))); + form.add(ReasonDialog.label("Unique ID:")); + form.add(uidField); + form.add(Box.createVerticalStrut(UIScale.scale(8))); + form.add(ReasonDialog.label("myTeamSpeak ID:")); + form.add(mytsidField); + form.add(Box.createVerticalStrut(UIScale.scale(12))); + form.add(reasonRow()); + form.add(reasonField); + form.add(Box.createVerticalStrut(UIScale.scale(8))); + form.add(ReasonDialog.label("Duration:")); + form.add(duration); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(form, BorderLayout.CENTER); + getContentPane().add(buttons(), BorderLayout.SOUTH); + + if (existing != null) load(existing); + rebuildPresets(); + checkValid(); + + ReasonDialog.focusWhenShown(ipField); + Dialogs.closeOnEscape(this); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + pack(); + setResizable(false); + setLocationRelativeTo(owner); + } + + // ---- construction ---- + + private JPanel patternRow() { + JPanel row = new JPanel(); + row.setLayout(new BoxLayout(row, BoxLayout.X_AXIS)); + row.setAlignmentX(Component.LEFT_ALIGNMENT); + row.add(new JLabel("Interpret IP/Name as:")); + row.add(Box.createHorizontalStrut(UIScale.scale(8))); + row.add(patternBox); + row.add(Box.createHorizontalGlue()); + ReasonDialog.fixHeight(row); + return row; + } + + private JPanel reasonRow() { + JButton save = new JButton("Save preset"); + save.addActionListener(e -> savePreset()); + presetBox.addActionListener(e -> { + int i = presetBox.getSelectedIndex(); + if (i > 0) reasonField.setText(presetBox.getItemAt(i)); + }); + + JPanel row = new JPanel(); + row.setLayout(new BoxLayout(row, BoxLayout.X_AXIS)); + row.setAlignmentX(Component.LEFT_ALIGNMENT); + row.setBorder(new ScaledEmptyBorder(0, 0, 4, 0)); + row.add(new JLabel("Reason:")); + row.add(Box.createHorizontalGlue()); + row.add(new JLabel("Preset:")); + row.add(Box.createHorizontalStrut(UIScale.scale(6))); + row.add(presetBox); + row.add(Box.createHorizontalStrut(UIScale.scale(6))); + row.add(save); + ReasonDialog.fixHeight(row); + return row; + } + + private JPanel buttons() { + JPanel panel = new JPanel(new BorderLayout()); + JPanel right = new JPanel(); + JButton cancel = new JButton("Cancel"); + ok.addActionListener(e -> accept()); + cancel.addActionListener(e -> dispose()); + right.add(ok); + right.add(cancel); + panel.add(right, BorderLayout.EAST); + getRootPane().setDefaultButton(ok); + return panel; + } + + // ---- behaviour ---- + + /** Shows an existing ban the way it was most likely typed in. */ + private void load(BanEntry ban) { + BanPattern.Decoded decoded = BanPattern.decode(ban.ip, ban.name); + patternBox.setSelectedItem(decoded.pattern); + ipField.setText(decoded.ip); + nameField.setText(decoded.name); + uidField.setText(ban.uid); + mytsidField.setText(ban.mytsid); + reasonField.setText(ban.reason); + duration.setSeconds(ban.durationSeconds); + } + + private BanPattern pattern() { + return (BanPattern) patternBox.getSelectedItem(); + } + + private BanRule rule() { + return new BanRule(pattern().ipToRegex(ipField.getText()), pattern().nameToRegex(nameField.getText()), + uidField.getText(), mytsidField.getText(), duration.getSeconds(), reasonField.getText()); + } + + private void checkValid() { + BanRule rule = rule(); + boolean ipOk = BanPattern.isValidRegex(rule.ipRegex); + boolean nameOk = BanPattern.isValidRegex(rule.nameRegex); + flag(ipField, ipOk); + flag(nameField, nameOk); + ok.setEnabled(rule.hasTarget() && ipOk && nameOk); + } + + private void flag(JTextField field, boolean valid) { + field.setBackground(valid ? fieldBg : INVALID_BG); + field.setForeground(valid ? fieldFg : Color.WHITE); + } + + private void accept() { + result = rule(); + dispose(); + } + + private void savePreset() { + String reason = reasonField.getText().trim(); + if (reason.isEmpty()) return; + presets.add(reason); + presets.save(); + rebuildPresets(); + presetBox.setSelectedIndex(1); + } + + private void rebuildPresets() { + presetBox.removeAllItems(); + presetBox.addItem(NO_PRESET); + for (String preset : presets.all()) presetBox.addItem(preset); + presetBox.setSelectedIndex(0); + } + + private static void onEdit(JTextField field, Runnable listener) { + field.getDocument().addDocumentListener(new DocumentListener() { + @Override + public void insertUpdate(DocumentEvent e) { + listener.run(); + } + + @Override + public void removeUpdate(DocumentEvent e) { + listener.run(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + listener.run(); + } + }); + } + + /** The ban as confirmed with OK, or {@code null} when the dialog was cancelled. */ + BanRule getRule() { + return result; + } + + private static final class PatternRenderer extends javax.swing.DefaultListCellRenderer { + @Override + public Component getListCellRendererComponent(javax.swing.JList list, Object value, int index, + boolean selected, boolean focused) { + super.getListCellRendererComponent(list, value, index, selected, focused); + if (value instanceof BanPattern) setText(((BanPattern) value).label()); + return this; + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanDialog.java new file mode 100644 index 0000000..8dd4ef0 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanDialog.java @@ -0,0 +1,86 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.net.ban.BanRule; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JPanel; +import javax.swing.JTextField; +import java.awt.BorderLayout; +import java.awt.Frame; + +/** + * Asks for a ban's reason and duration, like the official client's ban dialog: + * either a number of seconds, minutes, hours or days, or permanent. + */ +final class BanDialog extends JDialog { + + private final JTextField reasonField = ReasonDialog.reasonField(BanRule.REASON_LIMIT); + private final BanDurationPicker duration; + + private boolean confirmed; + + /** + * @param maxSeconds the longest ban the server lets us hand out, or 0 for no limit + */ + BanDialog(Frame owner, String nickname, long maxSeconds) { + super(owner, "Ban Client", true); + duration = new BanDurationPicker(maxSeconds); + + JPanel form = new JPanel(); + form.setLayout(new BoxLayout(form, BoxLayout.Y_AXIS)); + form.setBorder(new ScaledEmptyBorder(12, 12, 8, 12)); + form.add(ReasonDialog.label("Ban " + nickname + " from the server.")); + form.add(Box.createVerticalStrut(UIScale.scale(8))); + form.add(ReasonDialog.label("Reason:")); + form.add(reasonField); + form.add(Box.createVerticalStrut(UIScale.scale(8))); + form.add(ReasonDialog.label("Duration:")); + form.add(duration); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(form, BorderLayout.CENTER); + getContentPane().add(buttons(), BorderLayout.SOUTH); + + ReasonDialog.focusWhenShown(reasonField); + Dialogs.closeOnEscape(this); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + pack(); + setResizable(false); + setLocationRelativeTo(owner); + } + + private JPanel buttons() { + JPanel panel = new JPanel(new BorderLayout()); + JPanel right = new JPanel(); + JButton ok = new JButton("Ban"); + JButton cancel = new JButton("Cancel"); + ok.addActionListener(e -> { + confirmed = true; + dispose(); + }); + cancel.addActionListener(e -> dispose()); + right.add(ok); + right.add(cancel); + panel.add(right, BorderLayout.EAST); + getRootPane().setDefaultButton(ok); + return panel; + } + + boolean isConfirmed() { + return confirmed; + } + + String getReason() { + return reasonField.getText().trim(); + } + + /** The ban's length in seconds, or 0 for a permanent ban. */ + long getSeconds() { + return duration.getSeconds(); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanDurationPicker.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanDurationPicker.java new file mode 100644 index 0000000..651108c --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanDurationPicker.java @@ -0,0 +1,86 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.net.ban.BanUnit; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.DefaultListCellRenderer; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JSpinner; +import javax.swing.SpinnerNumberModel; +import java.awt.Component; + +/** + * A ban's length as the official client asks for it: an amount of seconds, minutes, + * hours or days, or "permanent", plus a button that jumps to the longest ban the + * server lets us hand out ({@code i_client_ban_max_bantime}). + */ +final class BanDurationPicker extends JPanel { + + private final JSpinner amount = new JSpinner(new SpinnerNumberModel(30, 1, 999_999_999, 1)); + private final JComboBox unit = new JComboBox<>(BanUnit.values()); + private final JButton max = new JButton("Max"); + + /** + * @param maxSeconds the longest ban the server allows, or 0 when there is no limit + */ + BanDurationPicker(long maxSeconds) { + setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); + setAlignmentX(Component.LEFT_ALIGNMENT); + setOpaque(false); + + unit.setSelectedItem(BanUnit.MINUTES); + unit.setRenderer(new DefaultListCellRenderer() { + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, + boolean selected, boolean focused) { + return super.getListCellRendererComponent(list, ((BanUnit) value).label(), index, selected, focused); + } + }); + unit.addActionListener(e -> amount.setEnabled(!isPermanent())); + max.setToolTipText("Set duration to maximum value"); + max.addActionListener(e -> setSeconds(maxSeconds)); + + add(amount); + add(Box.createHorizontalStrut(UIScale.scale(4))); + add(unit); + add(Box.createHorizontalStrut(UIScale.scale(4))); + add(max); + add(Box.createHorizontalGlue()); + ReasonDialog.fixHeight(this); + } + + boolean isPermanent() { + return unit() == BanUnit.PERMANENT; + } + + private BanUnit unit() { + return (BanUnit) unit.getSelectedItem(); + } + + /** The ban's length in seconds, or 0 for a permanent ban. */ + long getSeconds() { + return unit().toSeconds(((Number) amount.getValue()).longValue()); + } + + /** Shows a length in the largest unit that divides it evenly; 0 is permanent. */ + void setSeconds(long seconds) { + BanUnit fit = BanUnit.largestFor(seconds); + unit.setSelectedItem(fit); + if (fit != BanUnit.PERMANENT) amount.setValue((int) Math.min(fit.amountOf(seconds), 999_999_999)); + } + + /** Called back whenever the length changes, however it changes. */ + void onChange(Runnable listener) { + amount.addChangeListener(e -> listener.run()); + unit.addActionListener(e -> listener.run()); + } + + JSpinner amountField() { + return amount; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanListDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanListDialog.java new file mode 100644 index 0000000..c5c4c10 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanListDialog.java @@ -0,0 +1,646 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.config.BanReasonPresets; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.net.TeamspeakConnection; +import eu.lixko.ts3j.client.net.ban.BanEntry; +import eu.lixko.ts3j.client.net.ban.BanRule; + +import javax.swing.AbstractAction; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.KeyStroke; +import javax.swing.ListSelectionModel; +import javax.swing.RowFilter; +import javax.swing.SwingUtilities; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.JTableHeader; +import javax.swing.table.TableColumn; +import javax.swing.table.TableColumnModel; +import javax.swing.table.TableRowSorter; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.event.ActionEvent; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * The server's ban list, as the official client's Tools > Ban List window: Add, + * Remove and Edit above a searchable table, Reload and the own-ban filters below it. + * Which columns show is chosen from the header's context menu and remembered. + * + *

    One per server tab and modeless, so it can stay open while the server is used; + * the tab closes it when the connection goes away. + */ +final class BanListDialog extends JDialog { + + private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + /** The table's columns, in the official order; the split-out target columns start hidden. */ + private enum Column { + TARGETS("Name/IP/UID/myTSID", 280, true), + NAME("Name", 120, false), + IP("IP", 120, false), + UID("UID", 200, false), + MYTSID("myTSID", 200, false), + REASON("Reason", 160, true), + CREATOR("Creator", 100, true), + CREATED("Created", 140, true), + EXPIRES("Expires", 140, true), + ENFORCED("Enforced", 70, true); + + final String title; + final int width; + final boolean shownByDefault; + + Column(String title, int width, boolean shownByDefault) { + this.title = title; + this.width = width; + this.shownByDefault = shownByDefault; + } + } + + private final Frame owner; + private final TeamspeakConnection conn; + private final Settings settings; + private final BanReasonPresets presets; + + private final BanTableModel tableModel = new BanTableModel(); + private final JTable table = new BanTable(); + private final TableRowSorter sorter = new TableRowSorter<>(tableModel); + /** Every column the table can show, in model order, whether currently shown or not. */ + private final List allColumns = new ArrayList<>(); + private final Set visibleColumns = EnumSet.noneOf(Column.class); + + private final JButton addButton = new JButton("Add", Icons.of("ADD")); + private final JButton removeButton = new JButton("Remove", Icons.of("DELETE")); + private final JButton editButton = new JButton("Edit", Icons.of("EDIT")); + private final SearchField searchField = new SearchField(); + private final JCheckBox onlyOwn = new JCheckBox("Show only own bans"); + private final JCheckBox highlightOwn = new JCheckBox("Highlight own bans"); + private final JLabel status = new JLabel(" "); + + private boolean loading; + + BanListDialog(Frame owner, TeamspeakConnection conn, Settings settings, BanReasonPresets presets) { + super(owner, "Ban List", false); + this.owner = owner; + this.conn = conn; + this.settings = settings; + this.presets = presets; + + JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(6))); + content.setBackground(Theme.windowBg()); + content.setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); + content.add(buildToolbar(), BorderLayout.NORTH); + content.add(buildTable(), BorderLayout.CENTER); + content.add(buildBottom(), BorderLayout.SOUTH); + setContentPane(content); + bindKeys(); + + serverNameChanged(); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + setPreferredSize(UIScale.scale(new Dimension(920, 460))); + pack(); + setLocationRelativeTo(owner); + reload(); + } + + // ---- construction ---- + + private JPanel buildToolbar() { + JPanel bar = new JPanel(); + bar.setLayout(new BoxLayout(bar, BoxLayout.X_AXIS)); + bar.setOpaque(false); + + addButton.setToolTipText("Add new ban
    (Ctrl+N)"); + removeButton.setToolTipText("Remove selected bans
    (Delete)"); + editButton.setToolTipText("Edit selected ban
    (Return)"); + searchField.setToolTipText("Search bans by text
    (Ctrl+F)"); + addButton.addActionListener(e -> addBan()); + removeButton.addActionListener(e -> removeBans()); + editButton.addActionListener(e -> editBan()); + searchField.getDocument().addDocumentListener(new DocumentListener() { + @Override + public void insertUpdate(DocumentEvent e) { + applyFilter(); + } + + @Override + public void removeUpdate(DocumentEvent e) { + applyFilter(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + applyFilter(); + } + }); + searchField.setMaximumSize(new Dimension(Integer.MAX_VALUE, searchField.getPreferredSize().height)); + + bar.add(addButton); + bar.add(Box.createHorizontalStrut(UIScale.scale(6))); + bar.add(removeButton); + bar.add(Box.createHorizontalStrut(UIScale.scale(6))); + bar.add(editButton); + bar.add(Box.createHorizontalStrut(UIScale.scale(16))); + bar.add(searchField); + return bar; + } + + private JScrollPane buildTable() { + table.setFont(Theme.uiFont()); + table.setRowHeight(UIScale.scale(20)); + table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); + table.setFillsViewportHeight(true); + table.setAutoCreateColumnsFromModel(false); + table.setRowSorter(sorter); + table.getSelectionModel().addListSelectionListener(e -> updateButtons()); + table.setComponentPopupMenu(tablePopup()); + table.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2 + && table.rowAtPoint(e.getPoint()) >= 0) { + editBan(); + } + } + }); + + BanCellRenderer renderer = new BanCellRenderer(); + for (Column c : Column.values()) { + TableColumn column = new TableColumn(c.ordinal(), c.width); + column.setHeaderValue(c.title); + column.setCellRenderer(renderer); + allColumns.add(column); + } + visibleColumns.addAll(savedColumns()); + applyColumns(); + + JTableHeader header = table.getTableHeader(); + header.setReorderingAllowed(true); + header.addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + if (e.isPopupTrigger()) headerPopup().show(header, e.getX(), e.getY()); + } + + @Override + public void mouseReleased(MouseEvent e) { + if (e.isPopupTrigger()) headerPopup().show(header, e.getX(), e.getY()); + } + }); + + JScrollPane scroll = new JScrollPane(table); + scroll.getViewport().setBackground(Theme.treeBg()); + return scroll; + } + + private JPanel buildBottom() { + JButton reload = new JButton("Reload", Icons.of("REFRESH")); + reload.addActionListener(e -> reload()); + onlyOwn.setToolTipText("Show only bans created by you"); + onlyOwn.setOpaque(false); + onlyOwn.addActionListener(e -> applyFilter()); + highlightOwn.setToolTipText("Mark bans created by you as bold"); + highlightOwn.setOpaque(false); + highlightOwn.setSelected(settings.banHighlightOwn); + highlightOwn.addActionListener(e -> { + settings.banHighlightOwn = highlightOwn.isSelected(); + settings.save(); + table.repaint(); + }); + + JPanel options = new JPanel(); + options.setLayout(new BoxLayout(options, BoxLayout.X_AXIS)); + options.setOpaque(false); + options.add(reload); + options.add(Box.createHorizontalStrut(UIScale.scale(12))); + options.add(onlyOwn); + options.add(Box.createHorizontalStrut(UIScale.scale(12))); + options.add(highlightOwn); + options.add(Box.createHorizontalGlue()); + + JButton close = new JButton("Close"); + close.addActionListener(e -> dispose()); + JPanel closeRow = new JPanel(new BorderLayout()); + closeRow.setOpaque(false); + closeRow.add(close, BorderLayout.EAST); + + JPanel bottom = new JPanel(new BorderLayout(0, UIScale.scale(8))); + bottom.setOpaque(false); + bottom.add(status, BorderLayout.NORTH); + bottom.add(options, BorderLayout.CENTER); + bottom.add(closeRow, BorderLayout.SOUTH); + status.setForeground(Theme.chatEvent()); + return bottom; + } + + private JPopupMenu tablePopup() { + JPopupMenu menu = new JPopupMenu(); + menu.add(item("Add", "ADD", this::addBan)); + menu.add(item("Remove", "DELETE", this::removeBans)); + menu.add(item("Edit", "EDIT", this::editBan)); + menu.addSeparator(); + menu.add(item("Reload", "REFRESH", this::reload)); + return menu; + } + + private static JMenuItem item(String text, String icon, Runnable action) { + JMenuItem item = new JMenuItem(text, Icons.of(icon)); + item.addActionListener(e -> action.run()); + return item; + } + + private JPopupMenu headerPopup() { + JPopupMenu menu = new JPopupMenu(); + for (Column c : Column.values()) { + JCheckBoxMenuItem item = new JCheckBoxMenuItem(c.title, visibleColumns.contains(c)); + // the last column stays, or there would be nothing left to right-click on + item.setEnabled(!item.isSelected() || visibleColumns.size() > 1); + item.addActionListener(e -> { + if (item.isSelected()) visibleColumns.add(c); + else visibleColumns.remove(c); + applyColumns(); + saveColumns(); + }); + menu.add(item); + } + return menu; + } + + private void bindKeys() { + bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control N"), this::addBan); + bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control F"), + searchField::requestFocusInWindow); + bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control W"), this::dispose); + bind(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), + this::removeBans); + bind(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), + this::editBan); + Dialogs.closeOnEscape(this); + } + + private static void bind(JComponent target, int condition, KeyStroke key, Runnable action) { + String name = "ts3-banlist-" + key; + target.getInputMap(condition).put(key, name); + target.getActionMap().put(name, new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + action.run(); + } + }); + } + + // ---- columns ---- + + private Set savedColumns() { + Set columns = EnumSet.noneOf(Column.class); + for (String name : settings.banListColumns.split(",")) { + try { + if (!name.isBlank()) columns.add(Column.valueOf(name.trim())); + } catch (IllegalArgumentException ignored) { + // a column from another version; skipped + } + } + if (columns.isEmpty()) { + for (Column c : Column.values()) if (c.shownByDefault) columns.add(c); + } + return columns; + } + + private void saveColumns() { + settings.banListColumns = visibleColumns.stream().map(Enum::name).collect(Collectors.joining(",")); + settings.save(); + } + + /** Rebuilds the column model so it holds exactly the visible columns, in model order. */ + private void applyColumns() { + TableColumnModel columns = table.getColumnModel(); + while (columns.getColumnCount() > 0) columns.removeColumn(columns.getColumn(0)); + for (TableColumn column : allColumns) { + if (visibleColumns.contains(Column.values()[column.getModelIndex()])) columns.addColumn(column); + } + } + + // ---- data ---- + + /** Follows the server's name, as the official window's "Ban List - " title does. */ + void serverNameChanged() { + String name = conn.getModel().getServerName(); + setTitle(name == null || name.isBlank() ? "Ban List" : "Ban List - " + name); + } + + /** The connection is gone; a ban list without a server is meaningless. */ + void connectionLost() { + dispose(); + } + + private void reload() { + if (loading) return; + loading = true; + status.setText("Loading…"); + conn.requestBanList((bans, error) -> SwingUtilities.invokeLater(() -> { + loading = false; + if (!isDisplayable()) return; + if (error != null) { + tableModel.setBans(List.of()); + status.setText(isPermissionError(error) + ? "You have insufficient permissions to view the ban list." + : "Failed to request ban list: " + error); + updateButtons(); + return; + } + tableModel.setBans(bans); + status.setText(bans.size() == 1 ? "1 ban" : bans.size() + " bans"); + updateButtons(); + })); + } + + private static boolean isPermissionError(String message) { + String m = message.toLowerCase(Locale.ROOT); + return m.contains("insufficient") || m.contains("permission"); + } + + private void applyFilter() { + String needle = searchField.getText().trim().toLowerCase(Locale.ROOT); + boolean own = onlyOwn.isSelected(); + String self = conn.getSelfUniqueId(); + sorter.setRowFilter(new RowFilter<>() { + @Override + public boolean include(Entry entry) { + BanEntry ban = tableModel.get(entry.getIdentifier()); + if (own && !ban.createdBy(self)) return false; + if (needle.isEmpty()) return true; + for (Column c : Column.values()) { + if (tableModel.text(ban, c).toLowerCase(Locale.ROOT).contains(needle)) return true; + } + return false; + } + }); + } + + private List selectedBans() { + List selected = new ArrayList<>(); + for (int row : table.getSelectedRows()) selected.add(tableModel.get(table.convertRowIndexToModel(row))); + return selected; + } + + // ---- permissions ---- + + private boolean can(String permission) { + return conn.getModel().permits(permission); + } + + private boolean canDelete(List bans) { + return conn.getModel().canDeleteBans(bans, conn.getSelfUniqueId()); + } + + private void updateButtons() { + List selected = selectedBans(); + addButton.setEnabled(can("b_client_ban_create")); + removeButton.setEnabled(!selected.isEmpty() && canDelete(selected)); + editButton.setEnabled(selected.size() == 1 && conn.getModel().canEditBan(selected.get(0), conn.getSelfUniqueId())); + } + + // ---- actions ---- + + private long maxBanSeconds() { + return conn.getModel().maxBanSeconds(); + } + + private void addBan() { + if (!addButton.isEnabled()) return; + BanAddDialog dialog = new BanAddDialog(owner, presets, null, maxBanSeconds()); + dialog.setVisible(true); + BanRule rule = dialog.getRule(); + if (rule == null) return; + conn.addBan(rule, error -> afterChange(error, "Error adding ban: ", + () -> JOptionPane.showMessageDialog(this, "Your ban was successfully added.", "Ban List", + JOptionPane.INFORMATION_MESSAGE))); + } + + private void editBan() { + if (!editButton.isEnabled()) return; + BanEntry ban = selectedBans().get(0); + BanAddDialog dialog = new BanAddDialog(owner, presets, ban, maxBanSeconds()); + dialog.setVisible(true); + BanRule rule = dialog.getRule(); + if (rule == null) return; + conn.replaceBan(ban.id, rule, error -> afterChange(error, "Error editing ban: ", null)); + } + + private void removeBans() { + if (!removeButton.isEnabled()) return; + List bans = selectedBans(); + int answer = JOptionPane.showConfirmDialog(this, "Do you really want to delete the selected ban(s)?", + "Delete bans", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); + if (answer != JOptionPane.YES_OPTION) return; + List ids = bans.stream().map(b -> b.id).collect(Collectors.toList()); + conn.deleteBans(ids, error -> afterChange(error, "Error deleting ban: ", null)); + } + + /** Reports a failed change, or re-reads the list so the table shows what the server now holds. */ + private void afterChange(String error, String errorPrefix, Runnable onSuccess) { + SwingUtilities.invokeLater(() -> { + if (!isDisplayable()) return; + if (error != null) { + JOptionPane.showMessageDialog(this, errorPrefix + error, "Ban List", JOptionPane.ERROR_MESSAGE); + } else if (onSuccess != null) { + onSuccess.run(); + } + reload(); + }); + } + + // ---- table ---- + + private final class BanTableModel extends AbstractTableModel { + + private List bans = List.of(); + + void setBans(List bans) { + this.bans = new ArrayList<>(bans); + fireTableDataChanged(); + } + + BanEntry get(int row) { + return bans.get(row); + } + + @Override + public int getRowCount() { + return bans.size(); + } + + @Override + public int getColumnCount() { + return Column.values().length; + } + + @Override + public String getColumnName(int column) { + return Column.values()[column].title; + } + + @Override + public Class getColumnClass(int column) { + switch (Column.values()[column]) { + case CREATED: + case EXPIRES: + return Long.class; + case ENFORCED: + return Integer.class; + default: + return String.class; + } + } + + /** Sortable values: the date columns sort by time, with "infinite" last. */ + @Override + public Object getValueAt(int row, int column) { + BanEntry ban = bans.get(row); + switch (Column.values()[column]) { + case CREATED: + return ban.createdEpochSeconds; + case EXPIRES: + return ban.isPermanent() ? Long.MAX_VALUE : ban.expiresEpochSeconds(); + case ENFORCED: + return ban.enforcements; + default: + return text(ban, Column.values()[column]); + } + } + + /** What a cell shows (and what the search field matches). */ + String text(BanEntry ban, Column column) { + switch (column) { + case TARGETS: + return ban.targets(); + case NAME: + return ban.name; + case IP: + return ban.ip; + case UID: + return ban.uid; + case MYTSID: + return ban.mytsid; + case REASON: + return ban.reason; + case CREATOR: + return ban.invokerName; + case CREATED: + return date(ban.createdEpochSeconds); + case EXPIRES: + return ban.isPermanent() ? "infinite" : date(ban.expiresEpochSeconds()); + case ENFORCED: + return Integer.toString(ban.enforcements); + default: + return ""; + } + } + } + + private static String date(long epochSeconds) { + if (epochSeconds <= 0) return ""; + return DATE.format(Instant.ofEpochSecond(epochSeconds).atZone(ZoneId.systemDefault())); + } + + /** Shows the displayed text for every column and bolds our own bans when asked to. */ + private final class BanCellRenderer extends DefaultTableCellRenderer { + @Override + public Component getTableCellRendererComponent(JTable t, Object value, boolean selected, + boolean focused, int row, int column) { + BanEntry ban = tableModel.get(t.convertRowIndexToModel(row)); + Column c = Column.values()[t.convertColumnIndexToModel(column)]; + super.getTableCellRendererComponent(t, tableModel.text(ban, c), selected, focused, row, column); + boolean bold = highlightOwn.isSelected() && ban.createdBy(conn.getSelfUniqueId()); + setFont(bold ? Theme.uiBold() : Theme.uiFont()); + setHorizontalAlignment(c == Column.ENFORCED ? RIGHT : LEFT); + return this; + } + } + + /** A table whose rows carry the official client's tooltip of a ban's details. */ + private final class BanTable extends JTable { + BanTable() { + super(tableModel); + } + + @Override + public String getToolTipText(MouseEvent e) { + int row = rowAtPoint(e.getPoint()); + if (row < 0) return null; + BanEntry ban = tableModel.get(convertRowIndexToModel(row)); + return "" + + tooltipRow("Last name", ban.lastNickname) + + tooltipRow("Creator", ban.invokerName) + + tooltipRow("Created", date(ban.createdEpochSeconds)) + + tooltipRow("Expires", ban.isPermanent() ? "infinite" : date(ban.expiresEpochSeconds())) + + tooltipRow("Enforced", Integer.toString(ban.enforcements)) + + "
    "; + } + } + + private static String tooltipRow(String label, String value) { + return "" + label + ":" + escape(value) + + ""; + } + + private static String escape(String s) { + return s.replace("&", "&").replace("<", "<").replace(">", ">"); + } + + /** A text field that shows "Search" while it is empty. */ + private static final class SearchField extends javax.swing.JTextField { + SearchField() { + super(20); + } + + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + if (!getText().isEmpty()) return; + Graphics2D g2 = (Graphics2D) g.create(); + g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + g2.setColor(Theme.chatEvent()); + g2.setFont(getFont().deriveFont(Font.ITALIC)); + int y = (getHeight() + g2.getFontMetrics().getAscent() - g2.getFontMetrics().getDescent()) / 2; + g2.drawString("Search", getInsets().left + UIScale.scale(2), y); + g2.dispose(); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BookmarksDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BookmarksDialog.java new file mode 100644 index 0000000..b5f073d --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BookmarksDialog.java @@ -0,0 +1,318 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.config.Bookmark; +import eu.lixko.ts3j.client.config.Bookmarks; +import eu.lixko.ts3j.client.config.IdentityStore; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter; +import eu.lixko.ts3j.client.teamspeak.TeamSpeakSettingsDb; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.DefaultListCellRenderer; +import javax.swing.DefaultListModel; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JPasswordField; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.JTextField; +import javax.swing.ListSelectionModel; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.io.File; +import java.util.function.Consumer; + +/** + * Manage saved servers. Two columns: the bookmark list on the left, the + * selected bookmark's settings on the right. Edits are applied to the selected + * bookmark as soon as the selection changes or the dialog is closed. + */ +public final class BookmarksDialog extends JDialog { + + private final Bookmarks bookmarks; + private final IdentityStore identities; + private final Settings settings; + private final Consumer onConnect; + private final Runnable onChanged; + private final DefaultListModel listModel = new DefaultListModel<>(); + private final JList list = new JList<>(listModel); + + private final JTextField label = new JTextField(); + private final JTextField address = new JTextField(); + private final JTextField port = new JTextField(); + private final JTextField nick = new JTextField(); + private final JPasswordField password = new JPasswordField(); + private final JTextField channel = new JTextField(); + private final JPasswordField channelPassword = new JPasswordField(); + private final JCheckBox connectOnStartup = new JCheckBox("Connect on startup"); + private final IdentityChooser identity; + + private final JPanel details; + + /** Bookmark the form currently shows, so edits can be flushed back into it. */ + private Bookmark editing; + + public BookmarksDialog(Frame owner, Bookmarks bookmarks, IdentityStore identities, Settings settings, + Consumer onConnect, Runnable onChanged) { + super(owner, "Manage Bookmarks", true); + this.bookmarks = bookmarks; + this.identities = identities; + this.settings = settings; + this.onConnect = onConnect; + this.onChanged = onChanged; + this.identity = new IdentityChooser(identities, true, ""); + + list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + list.setVisibleRowCount(12); + list.setCellRenderer(new DefaultListCellRenderer() { + @Override + public Component getListCellRendererComponent(JList l, Object value, int index, + boolean selected, boolean focused) { + super.getListCellRendererComponent(l, value, index, selected, focused); + ImageIcon icon = GroupIcons.cached(((Bookmark) value).iconId); + setIcon(icon != null ? icon : Icons.of("SERVER_GREEN")); + return this; + } + }); + list.addListSelectionListener(e -> { + if (!e.getValueIsAdjusting()) onSelectionChanged(); + }); + + details = buildDetails(); + + JScrollPane listScroll = new JScrollPane(list); + listScroll.setPreferredSize(UIScale.scale(new Dimension(180, 320))); + + JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, listScroll, details); + split.setBorder(new ScaledEmptyBorder(8, 8, 4, 8)); + split.setResizeWeight(0.3); + split.setContinuousLayout(true); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(split, BorderLayout.CENTER); + getContentPane().add(buildButtons(), BorderLayout.SOUTH); + + reload(); + if (!listModel.isEmpty()) list.setSelectedIndex(0); + else showBookmark(null); + + Dialogs.closeOnEscape(this, this::closeDialog); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + addWindowListener(new java.awt.event.WindowAdapter() { + @Override + public void windowClosing(java.awt.event.WindowEvent e) { + commit(); + persist(); + } + }); + setSize(UIScale.scale(new Dimension(640, 400))); + setLocationRelativeTo(owner); + } + + // ---- UI construction ---- + + private JPanel buildDetails() { + JPanel panel = new JPanel(new GridBagLayout()); + panel.setBorder(new ScaledEmptyBorder(0, 8, 0, 0)); + + channel.setToolTipText("Channel path, e.g. \"Lobby/Games\", or a channel id. " + + "Leave empty for the server's default channel."); + connectOnStartup.setToolTipText("Connect to this server automatically when the client starts. " + + "Several bookmarks may be flagged; each opens its own tab."); + + int row = 0; + addRow(panel, row++, "Label:", label); + addRow(panel, row++, "Address:", address); + addRow(panel, row++, "Port:", port); + addRow(panel, row++, "Nickname:", nick); + addRow(panel, row++, "Password:", password); + addRow(panel, row++, "Default channel:", channel); + addRow(panel, row++, "Channel password:", channelPassword); + addRow(panel, row++, "Identity:", identity); + addRow(panel, row++, "", connectOnStartup); + + GridBagConstraints filler = new GridBagConstraints(); + filler.gridx = 0; + filler.gridy = row; + filler.weighty = 1; + filler.fill = GridBagConstraints.VERTICAL; + panel.add(Box.createVerticalGlue(), filler); + return panel; + } + + private void addRow(JPanel panel, int row, String text, java.awt.Component field) { + GridBagConstraints c = new GridBagConstraints(); + c.gridy = row; + c.insets = UIScale.scale(new Insets(2, 0, 2, 4)); + c.anchor = GridBagConstraints.WEST; + c.gridx = 0; + panel.add(new JLabel(text), c); + c.gridx = 1; + c.weightx = 1; + c.fill = GridBagConstraints.HORIZONTAL; + panel.add(field, c); + } + + private JPanel buildButtons() { + JPanel buttons = new JPanel(); + buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS)); + buttons.setBorder(new ScaledEmptyBorder(0, 8, 8, 8)); + addButton(buttons, "Add", this::addBookmark); + addButton(buttons, "Remove", this::removeSelected); + if (TeamSpeakSettingsDb.locate() != null) { + addButton(buttons, "Import from TeamSpeak 3…", this::importFromTeamSpeak) + .setToolTipText("Add the bookmarks of the TeamSpeak 3 client installed on this computer, " + + "along with the identities they connect with"); + } + buttons.add(Box.createHorizontalGlue()); + addButton(buttons, "Connect", this::connectSelected); + addButton(buttons, "Close", this::closeDialog); + return buttons; + } + + private JButton addButton(JPanel panel, String text, Runnable action) { + JButton b = new JButton(text); + b.addActionListener(e -> action.run()); + panel.add(b); + panel.add(Box.createHorizontalStrut(UIScale.scale(4))); + return b; + } + + // ---- Form <-> model ---- + + private void onSelectionChanged() { + commit(); + showBookmark(list.getSelectedValue()); + } + + private void showBookmark(Bookmark b) { + editing = b; + setEnabledRecursively(details, b != null); + label.setText(b == null ? "" : nullToEmpty(b.label)); + address.setText(b == null ? "" : nullToEmpty(b.address)); + port.setText(b == null ? "" : Integer.toString(b.port)); + nick.setText(b == null ? "" : nullToEmpty(b.nickname)); + password.setText(b == null ? "" : nullToEmpty(b.password)); + channel.setText(b == null ? "" : nullToEmpty(b.channel)); + channelPassword.setText(b == null ? "" : nullToEmpty(b.channelPassword)); + connectOnStartup.setSelected(b != null && b.connectOnStartup); + identity.setSelectedIdentityId(b == null ? "" : nullToEmpty(b.identityId)); + } + + /** Writes the form back into the bookmark it was loaded from. */ + private void commit() { + if (editing == null) return; + editing.label = label.getText().trim(); + editing.address = address.getText().trim(); + try { + editing.port = Integer.parseInt(port.getText().trim()); + } catch (NumberFormatException e) { + editing.port = 9987; + } + editing.nickname = nick.getText().trim(); + editing.password = new String(password.getPassword()); + editing.channel = channel.getText().trim(); + editing.channelPassword = new String(channelPassword.getPassword()); + editing.identityId = identity.getSelectedIdentityId(); + editing.connectOnStartup = connectOnStartup.isSelected(); + list.repaint(); + } + + // ---- Actions ---- + + private void addBookmark() { + commit(); + Bookmark b = new Bookmark("New bookmark", "", 9987, + System.getProperty("user.name", "TS3j User"), ""); + bookmarks.add(b); + reload(); + list.setSelectedValue(b, true); + persist(); + label.requestFocusInWindow(); + } + + private void removeSelected() { + int idx = list.getSelectedIndex(); + if (idx < 0) return; + editing = null; // dropped, nothing to flush back + bookmarks.remove(idx); + reload(); + if (!listModel.isEmpty()) list.setSelectedIndex(Math.min(idx, listModel.size() - 1)); + else showBookmark(null); + persist(); + } + + private void importFromTeamSpeak() { + File db = TeamSpeakSettingsDb.locate(); + if (db == null) return; + commit(); + try { + TeamSpeakImporter.Result result = new TeamSpeakImporter(identities, bookmarks, settings).importBookmarks(db); + identity.reload(); + reload(); + if (result.bookmarksAdded() > 0) list.setSelectedIndex(listModel.size() - result.bookmarksAdded()); + persist(); + JOptionPane.showMessageDialog(this, result.bookmarks() + " bookmark(s) read from " + db + + "\n" + result.bookmarksAdded() + " new, " + result.bookmarksKnown() + " already present; " + + result.identitiesAdded() + " identit" + (result.identitiesAdded() == 1 ? "y" : "ies") + " imported.", + "Import from TeamSpeak 3", JOptionPane.INFORMATION_MESSAGE); + } catch (Exception e) { + JOptionPane.showMessageDialog(this, "Could not read " + db + ":\n" + e.getMessage(), + "Import from TeamSpeak 3", JOptionPane.ERROR_MESSAGE); + } + } + + private void connectSelected() { + commit(); + Bookmark b = list.getSelectedValue(); + if (b == null) return; + if (b.address == null || b.address.isBlank()) { + JOptionPane.showMessageDialog(this, "Address is required."); + return; + } + persist(); + onConnect.accept(b); + dispose(); + } + + private void closeDialog() { + commit(); + persist(); + dispose(); + } + + private void reload() { + listModel.clear(); + for (Bookmark b : bookmarks.all()) listModel.addElement(b); + } + + private void persist() { + bookmarks.save(); + if (onChanged != null) onChanged.run(); + } + + private static void setEnabledRecursively(java.awt.Container container, boolean enabled) { + for (java.awt.Component c : container.getComponents()) { + c.setEnabled(enabled); + if (c instanceof java.awt.Container child) setEnabledRecursively(child, enabled); + } + } + + private static String nullToEmpty(String s) { + return s == null ? "" : s; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/CapturePanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/CapturePanel.java new file mode 100644 index 0000000..1cf9046 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/CapturePanel.java @@ -0,0 +1,129 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.audio.AudioBackend; +import eu.lixko.ts3j.client.audio.AudioDevice; +import eu.lixko.ts3j.client.audio.VoiceInput; +import eu.lixko.ts3j.client.config.Settings; + +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JSlider; +import java.awt.GridBagConstraints; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * Options page for everything on the way from the microphone to the server: the capture + * device and gain, how transmission is activated (with the microphone test), the + * pre-processing. Changes preview live on the connected microphone and the test alike. + */ +final class CapturePanel extends FormPanel { + + private static final String[] DENOISE_STEPS = {"Off", "6 dB", "12 dB", "18 dB", "21 dB"}; + + private final VoiceInput liveMic; + private final VoiceActivationSection activation; + + private final JComboBox inputCombo; + private final JSlider inputGain; + private final JSlider denoise; + private final JCheckBox typingCheck; + private final JCheckBox agcCheck; + private final JSlider agcBoost; + + CapturePanel(Settings settings, AudioBackend audio, VoiceInput liveMic, HotkeyService hotkeys, + HotkeysPanel hotkeysPanel, Supplier audioSnapshot) { + this.liveMic = liveMic; + this.activation = new VoiceActivationSection(settings, audio, liveMic, hotkeys, hotkeysPanel, audioSnapshot); + GridBagConstraints c = gbc(); + + inputCombo = AudioDevices.combo(audio.io().inputDevices(), settings.inputDevice); + limitWidth(inputCombo, FIELD_WIDTH); + inputCombo.addActionListener(e -> activation.restartTest()); + + inputGain = new JSlider(0, 200, (int) Math.round(settings.inputVolume * 100)); + JLabel gainLabel = new JLabel(inputGain.getValue() + "%"); + inputGain.addChangeListener(e -> { + gainLabel.setText(inputGain.getValue() + "%"); + applyLive(m -> m.setInputGain(inputGain.getValue() / 100.0)); + }); + + // Off, then TS3's four denoiser_level steps. + denoise = new JSlider(0, DENOISE_STEPS.length - 1, + settings.denoise ? Math.max(0, Math.min(3, settings.denoiserLevel)) + 1 : 0); + denoise.setMajorTickSpacing(1); + denoise.setPaintTicks(true); + denoise.setSnapToTicks(true); + JLabel denoiseLabel = new JLabel(DENOISE_STEPS[denoise.getValue()]); + typingCheck = new JCheckBox("Typing attenuation", settings.typingAttenuation); + agcCheck = new JCheckBox("Automatic gain control", settings.agc); + agcBoost = new JSlider(0, Settings.MAX_AGC_BOOST_DB, settings.agcBoostDb); + agcBoost.setMajorTickSpacing(5); + agcBoost.setPaintTicks(true); + limitWidth(agcBoost, SLIDER_WIDTH); + agcBoost.setToolTipText("Lets AGC bring up a quiet or distant voice further, " + + "at the cost of up to this many dB more background noise (0–20 dB)."); + + int row = 0; + addSection(this, c, row++, "Device"); + addRow(this, c, row++, new JLabel("Capture device:"), inputCombo); + addRow(this, c, row++, new JLabel("Microphone gain:"), sliderWithLabel(inputGain, gainLabel)); + addSection(this, c, row++, "Activation"); + row = activation.layOut(this, c, row); + addSection(this, c, row++, "Digital Signal Processing"); + addRow(this, c, row++, new JLabel("Remove background noise:"), sliderWithLabel(denoise, denoiseLabel)); + addWide(this, c, row++, typingCheck); + addWide(this, c, row++, agcCheck); + addRow(this, c, row++, new JLabel("Boost quiet speech:"), agcBoost); + addFiller(this, c, row); + + Runnable syncProcessing = () -> { + agcBoost.setEnabled(agcCheck.isSelected()); + applyLive(m -> { + applyDenoise(m); + m.setTypingAttenuation(typingCheck.isSelected()); + m.setAgc(agcCheck.isSelected()); + }); + }; + typingCheck.addActionListener(e -> syncProcessing.run()); + agcCheck.addActionListener(e -> syncProcessing.run()); + denoise.addChangeListener(e -> { + denoiseLabel.setText(DENOISE_STEPS[denoise.getValue()]); + applyLive(this::applyDenoise); + }); + agcBoost.addChangeListener(e -> applyLive(m -> m.setAgcBoost(agcBoost.getValue()))); + syncProcessing.run(); + } + + /** Copies the page into {@code target}, without touching anything else. */ + void writeInto(Settings target) { + target.inputDevice = AudioDevices.selectedId(inputCombo); + target.inputVolume = inputGain.getValue() / 100.0; + target.denoise = denoise.getValue() > 0; + if (target.denoise) target.denoiserLevel = denoise.getValue() - 1; + target.typingAttenuation = typingCheck.isSelected(); + target.agc = agcCheck.isSelected(); + target.agcBoostDb = agcBoost.getValue(); + activation.writeInto(target); + } + + private void applyDenoise(VoiceInput mic) { + mic.setNoiseSuppression(denoise.getValue() > 0); + if (denoise.getValue() > 0) mic.setDenoiserLevel(denoise.getValue() - 1); + } + + /** Applies a live change to the connected microphone and to the microphone test alike. */ + void applyLive(Consumer change) { + if (liveMic != null) change.accept(liveMic); + activation.configureTest(change); + } + + void setTestOutputDevice(String deviceId) { + activation.setTestOutputDevice(deviceId); + } + + void stopTest() { + activation.stopTest(); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelAdvancedPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelAdvancedPanel.java new file mode 100644 index 0000000..bd370b6 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelAdvancedPanel.java @@ -0,0 +1,199 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.net.ChannelSettings; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JSpinner; +import javax.swing.JTextField; +import javax.swing.SpinnerNumberModel; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; + +/** + * The channel editor's "Advanced" tab: the phonetic name, the delete delay of a temporary + * channel, voice encryption, and the two client limits. + */ +final class ChannelAdvancedPanel extends JPanel implements ChannelDialog.Tab { + + private final JTextField phoneticName = new JTextField(); + private final JSpinner deleteDelay = + Spinners.compact(new JSpinner(new SpinnerNumberModel(0, 0, ChannelSettings.MAX_DELETE_DELAY, 1))); + private final JButton deleteDelayMax = new JButton("max"); + private final JCheckBox encrypted = new JCheckBox("Voice Data encrypted"); + + private final JRadioButton maxUsersUnlimited = new JRadioButton("Unlimited"); + private final JRadioButton maxUsersLimited = new JRadioButton("Limited"); + private final JSpinner maxUsers = Spinners.compact(new JSpinner(new SpinnerNumberModel(16, 0, 65535, 1))); + + private final JRadioButton familyInherited = new JRadioButton("Inherited"); + private final JRadioButton familyUnlimited = new JRadioButton("Unlimited"); + private final JRadioButton familyLimited = new JRadioButton("Limited"); + private final JSpinner familyMaxUsers = + Spinners.compact(new JSpinner(new SpinnerNumberModel(16, 0, 65535, 1))); + + ChannelAdvancedPanel() { + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + setBorder(new ScaledEmptyBorder(8, 8, 8, 8)); + + phoneticName.setToolTipText("Set phonetic nickname used for this channel by text-to-speech."); + deleteDelay.setToolTipText("

    Delay in seconds after temporary channels are deleted" + + " after the last user left the channel.

    "); + deleteDelayMax.setToolTipText("Set delete delay to maximum value"); + deleteDelayMax.addActionListener(a -> deleteDelay.setValue(ChannelSettings.MAX_DELETE_DELAY)); + encrypted.setToolTipText("Voice data in this channel will be encrypted."); + + ButtonGroup users = new ButtonGroup(); + users.add(maxUsersUnlimited); + users.add(maxUsersLimited); + maxUsersUnlimited.setToolTipText("Unlimited number of clients can join this channel."); + maxUsersLimited.setToolTipText("Limit number of clients in this channel."); + maxUsersUnlimited.addActionListener(a -> syncLimits()); + maxUsersLimited.addActionListener(a -> syncLimits()); + + ButtonGroup family = new ButtonGroup(); + family.add(familyInherited); + family.add(familyUnlimited); + family.add(familyLimited); + familyInherited.setToolTipText("Inherit the client limit by parent channel."); + familyUnlimited.setToolTipText("The channel subtree can be joined by unlimited number of clients."); + familyLimited.setToolTipText("Limit the number of clients in the channel subtree."); + for (JRadioButton radio : new JRadioButton[]{familyInherited, familyUnlimited, familyLimited}) { + radio.addActionListener(a -> syncLimits()); + } + + JPanel other = otherSettings(); + other.setAlignmentX(0f); + fixHeight(other); + add(other); + add(Box.createVerticalStrut(UIScale.scale(6))); + + JPanel limits = new JPanel(); + limits.setLayout(new BoxLayout(limits, BoxLayout.X_AXIS)); + limits.add(limitBox("Max Users", new JRadioButton[]{maxUsersUnlimited, maxUsersLimited}, maxUsers)); + limits.add(Box.createHorizontalStrut(UIScale.scale(8))); + limits.add(limitBox("Family Max Users", + new JRadioButton[]{familyInherited, familyUnlimited, familyLimited}, familyMaxUsers)); + limits.setAlignmentX(0f); + fixHeight(limits); + add(limits); + add(Box.createVerticalGlue()); + } + + /** The delete delay only means anything for a channel that disappears on its own. */ + void setChannelType(ChannelSettings.Type type) { + boolean temporary = type == ChannelSettings.Type.TEMPORARY; + deleteDelay.setEnabled(temporary); + deleteDelayMax.setEnabled(temporary); + } + + @Override + public void read(ChannelSettings settings) { + phoneticName.setText(settings.phoneticName); + deleteDelay.setValue(Math.min(ChannelSettings.MAX_DELETE_DELAY, Math.max(0, settings.deleteDelay))); + encrypted.setSelected(settings.encrypted); + + if (settings.maxClientsUnlimited) maxUsersUnlimited.setSelected(true); + else maxUsersLimited.setSelected(true); + maxUsers.setValue(settings.maxClients); + + if (settings.familyInherited) familyInherited.setSelected(true); + else if (settings.familyUnlimited) familyUnlimited.setSelected(true); + else familyLimited.setSelected(true); + familyMaxUsers.setValue(settings.maxFamilyClients); + + setChannelType(settings.type); + syncLimits(); + } + + @Override + public void write(ChannelSettings settings) { + settings.phoneticName = phoneticName.getText(); + settings.deleteDelay = (Integer) deleteDelay.getValue(); + settings.encrypted = encrypted.isSelected(); + settings.maxClientsUnlimited = maxUsersUnlimited.isSelected(); + settings.maxClients = (Integer) maxUsers.getValue(); + settings.familyInherited = familyInherited.isSelected(); + settings.familyUnlimited = familyUnlimited.isSelected(); + settings.maxFamilyClients = (Integer) familyMaxUsers.getValue(); + } + + private void syncLimits() { + maxUsers.setEnabled(maxUsersLimited.isSelected()); + familyMaxUsers.setEnabled(familyLimited.isSelected()); + } + + private JPanel otherSettings() { + JPanel panel = new JPanel(new GridBagLayout()); + panel.setBorder(BorderFactory.createTitledBorder("Other Settings")); + GridBagConstraints c = new GridBagConstraints(); + c.insets = UIScale.scale(new Insets(3, 4, 3, 4)); + c.anchor = GridBagConstraints.WEST; + c.fill = GridBagConstraints.HORIZONTAL; + + c.gridx = 0; + c.gridy = 0; + panel.add(new JLabel("Phonetic Name:"), c); + c.gridx = 1; + c.weightx = 1; + panel.add(phoneticName, c); + + c.gridx = 0; + c.gridy = 1; + c.weightx = 0; + panel.add(new JLabel("Delete delay:"), c); + JPanel delay = new JPanel(new FlowLayout(FlowLayout.LEFT, UIScale.scale(4), 0)); + delay.add(deleteDelay); + delay.add(deleteDelayMax); + c.gridx = 1; + c.weightx = 1; + panel.add(delay, c); + + c.gridx = 1; + c.gridy = 2; + panel.add(encrypted, c); + return panel; + } + + /** + * A limit box: its choices stacked, with the count beside the last of them — + * "Limited", the only choice it belongs to. + */ + private JPanel limitBox(String title, JRadioButton[] choices, JSpinner spinner) { + JPanel box = new JPanel(); + box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS)); + box.setBorder(BorderFactory.createTitledBorder(title)); + for (int i = 0; i < choices.length; i++) { + JRadioButton radio = choices[i]; + radio.setAlignmentX(0f); + if (i < choices.length - 1) { + box.add(radio); + continue; + } + JPanel row = new JPanel(new FlowLayout(FlowLayout.LEFT, UIScale.scale(6), 0)); + row.setAlignmentX(0f); + row.add(radio); + row.add(spinner); + box.add(row); + } + box.add(Box.createVerticalGlue()); + return box; + } + + /** Keeps a section at its natural height, so the free space collects at the bottom. */ + private static void fixHeight(JPanel panel) { + panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, panel.getPreferredSize().height)); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelAudioPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelAudioPanel.java new file mode 100644 index 0000000..13f819a --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelAudioPanel.java @@ -0,0 +1,153 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.net.ChannelCodec; +import eu.lixko.ts3j.client.net.ChannelSettings; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.ButtonGroup; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JSlider; +import java.awt.BorderLayout; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; + +/** + * The channel editor's "Audio" tab: the codec preset, or the codec and quality picked by + * hand, with the bandwidth one talking client then costs. + */ +final class ChannelAudioPanel extends JPanel implements ChannelDialog.Tab { + + private final JRadioButton voiceMobile = new JRadioButton("Voice Mobile"); + private final JRadioButton voiceDesktop = new JRadioButton("Voice Desktop"); + private final JRadioButton music = new JRadioButton("Music"); + private final JRadioButton custom = new JRadioButton("Custom"); + private final JComboBox codec = new JComboBox<>(ChannelCodec.NAMES); + private final JSlider quality = new JSlider(0, 10, 6); + private final JLabel qualityValue = new JLabel("6"); + private final JLabel bandwidth = new JLabel(); + private final JPanel customSettings = new JPanel(new GridBagLayout()); + + ChannelAudioPanel() { + super(new BorderLayout(UIScale.scale(8), UIScale.scale(8))); + setBorder(new ScaledEmptyBorder(8, 8, 8, 8)); + + ButtonGroup presets = new ButtonGroup(); + presets.add(voiceMobile); + presets.add(voiceDesktop); + presets.add(music); + presets.add(custom); + voiceMobile.addActionListener(a -> applyPreset(ChannelCodec.Preset.VOICE_MOBILE)); + voiceDesktop.addActionListener(a -> applyPreset(ChannelCodec.Preset.VOICE_DESKTOP)); + music.addActionListener(a -> applyPreset(ChannelCodec.Preset.MUSIC)); + custom.addActionListener(a -> setCustomEnabled(true)); + + codec.addActionListener(a -> updateBandwidth()); + quality.setMajorTickSpacing(1); + quality.setPaintTicks(true); + quality.setSnapToTicks(true); + quality.addChangeListener(e -> updateBandwidth()); + + add(presetBox(), BorderLayout.WEST); + add(customBox(), BorderLayout.CENTER); + add(bandwidthRow(), BorderLayout.SOUTH); + } + + @Override + public void read(ChannelSettings settings) { + codec.setSelectedIndex(ChannelCodec.clampCodec(settings.codec)); + quality.setValue(Math.max(0, Math.min(ChannelCodec.MAX_QUALITY, settings.codecQuality))); + ChannelCodec.Preset preset = ChannelCodec.Preset.of(settings.codec, settings.codecQuality); + if (preset == null) custom.setSelected(true); + else switch (preset) { + case VOICE_MOBILE -> voiceMobile.setSelected(true); + case VOICE_DESKTOP -> voiceDesktop.setSelected(true); + case MUSIC -> music.setSelected(true); + } + setCustomEnabled(custom.isSelected()); + updateBandwidth(); + } + + @Override + public void write(ChannelSettings settings) { + settings.codec = codec.getSelectedIndex(); + settings.codecQuality = quality.getValue(); + } + + private void applyPreset(ChannelCodec.Preset preset) { + codec.setSelectedIndex(preset.codec); + quality.setValue(preset.quality); + setCustomEnabled(false); + updateBandwidth(); + } + + private void setCustomEnabled(boolean enabled) { + customSettings.setEnabled(enabled); + for (java.awt.Component child : customSettings.getComponents()) child.setEnabled(enabled); + } + + private void updateBandwidth() { + qualityValue.setText(Integer.toString(quality.getValue())); + bandwidth.setText(ChannelCodec.bandwidthText(codec.getSelectedIndex(), quality.getValue())); + } + + private JPanel presetBox() { + JPanel box = new JPanel(); + box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS)); + box.setBorder(BorderFactory.createTitledBorder("Presets")); + for (JRadioButton radio : new JRadioButton[]{voiceMobile, voiceDesktop, music, custom}) { + radio.setAlignmentX(0f); + box.add(radio); + } + box.add(Box.createVerticalGlue()); + return box; + } + + private JPanel customBox() { + customSettings.setBorder(BorderFactory.createTitledBorder("Custom Settings")); + GridBagConstraints c = new GridBagConstraints(); + c.insets = UIScale.scale(new Insets(4, 4, 4, 4)); + c.anchor = GridBagConstraints.WEST; + c.fill = GridBagConstraints.HORIZONTAL; + + c.gridx = 0; + c.gridy = 0; + customSettings.add(new JLabel("Codec:"), c); + c.gridx = 1; + c.weightx = 1; + c.gridwidth = 2; + customSettings.add(codec, c); + + c.gridwidth = 1; + c.gridx = 0; + c.gridy = 1; + c.weightx = 0; + customSettings.add(new JLabel("Quality:"), c); + c.gridx = 1; + c.weightx = 1; + customSettings.add(quality, c); + c.gridx = 2; + c.weightx = 0; + customSettings.add(qualityValue, c); + + c.gridx = 0; + c.gridy = 2; + c.weighty = 1; + customSettings.add(Box.createVerticalGlue(), c); + return customSettings; + } + + private JPanel bandwidthRow() { + JPanel row = new JPanel(new BorderLayout(UIScale.scale(6), 0)); + row.add(new JLabel("Bandwidth usage:"), BorderLayout.WEST); + row.add(bandwidth, BorderLayout.CENTER); + return row; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelDialog.java new file mode 100644 index 0000000..3ed3ad0 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelDialog.java @@ -0,0 +1,434 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.net.ChannelNode; +import eu.lixko.ts3j.client.net.ChannelSettings; +import eu.lixko.ts3j.client.net.TeamspeakConnection; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JPasswordField; +import javax.swing.JPopupMenu; +import javax.swing.JScrollPane; +import javax.swing.JTabbedPane; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.SwingUtilities; +import javax.swing.Timer; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.Window; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.List; +import java.util.Map; + +/** + * TeamSpeak's channel editor: the channel's name, icon, password, topic and description + * above four tabs holding everything else. The official client uses the same dialog to + * create a channel and to edit one, and so does this. + * + *

    When editing, the channel's properties are not in the tree model — the tree only + * carries what the server pushes for display — so the dialog opens empty and fills itself + * from a {@code channelinfo}, with its own permissions arriving separately. Saving sends + * only what was actually changed, because a {@code channeledit} carrying one property the + * client may not modify is refused as a whole. + * + *

    When creating, there is nothing to read: the dialog starts from the defaults its + * caller chose and sends a {@code channelcreate} carrying whatever deviates from a plain + * new channel, for the same reason. + */ +final class ChannelDialog extends JDialog { + + /** A tab that maps a part of the channel's settings onto its controls. */ + interface Tab { + void read(ChannelSettings settings); + + void write(ChannelSettings settings); + } + + /** How long, and how often, to keep looking for a channel icon that is still downloading. */ + private static final int ICON_RETRY_MS = 500; + private static final int ICON_RETRIES = 20; + + /** What the password field shows for an existing password, which is never readable. */ + private static final String PASSWORD_PLACEHOLDER = "••••••••"; + + private static final String NAME_TOOLTIP = "Name of this channel displayed in the tree." + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "
    Syntax: \"[?Spacer#]Text\"
    Where \"?\" stands for an alignment" + + " (r=right, c=center, l=left),
    \"*\" will repeat the text to fill the whole line.
    Change \"#\" to get a unique channel name.
    [lSpacer0] a left aligned text
    [cSpacer1] a centered text
    [rSpacer2] a right aligned text
    Use one of the three-character-blocks as text for a" + + " special spacer: \"---\", \"...\", \"-.-\", \"___\", \"-..\"
    "; + + private final TeamspeakConnection conn; + private final GroupIcons groupIcons; + /** The channel being edited, or {@code null} when a new one is being created. */ + private final ChannelNode channel; + /** Where a new channel goes; 0 is the top level. Unused when editing. */ + private final int parentId; + + private final JTextField name = new JTextField(); + private final JPasswordField password = new JPasswordField(); + private final JTextField topic = new JTextField(); + private final JTextArea description = new JTextArea(5, 40); + private final JButton iconButton = new JButton(); + private final JButton ok = new JButton("OK"); + + private final ChannelStandardPanel standardPanel; + private final ChannelAudioPanel audioPanel = new ChannelAudioPanel(); + private final ChannelPermissionsPanel permissionsPanel = new ChannelPermissionsPanel(); + private final ChannelAdvancedPanel advancedPanel = new ChannelAdvancedPanel(); + + /** The tabs backed by {@link ChannelSettings}; the permissions tab has its own source. */ + private final List settingsTabs; + + /** The channel as the server last described it; the baseline every change is measured against. */ + private ChannelSettings original; + private long iconId; + private boolean passwordEdited; + + /** The editor for an existing channel. */ + static ChannelDialog toEdit(Window owner, TeamspeakConnection conn, GroupIcons groupIcons, + ChannelNode channel) { + return new ChannelDialog(owner, conn, groupIcons, "Edit Channel: " + channel.name, + channel, channel.parentId, null); + } + + /** + * The editor for a channel that does not exist yet. + * + * @param parentId the channel it goes below, 0 being the top level + * @param defaults what the dialog opens with, e.g. the channel type its caller prefers + */ + static ChannelDialog toCreate(Window owner, TeamspeakConnection conn, GroupIcons groupIcons, + String title, int parentId, ChannelSettings defaults) { + return new ChannelDialog(owner, conn, groupIcons, title, null, parentId, defaults); + } + + private ChannelDialog(Window owner, TeamspeakConnection conn, GroupIcons groupIcons, String title, + ChannelNode channel, int parentId, ChannelSettings defaults) { + super(owner, title, ModalityType.APPLICATION_MODAL); + this.conn = conn; + this.groupIcons = groupIcons; + this.channel = channel; + this.parentId = parentId; + this.standardPanel = new ChannelStandardPanel(channel != null + ? conn.getModel().siblingsOf(channel.id) : conn.getModel().childrenOf(parentId)); + + standardPanel.onTypeChanged(advancedPanel::setChannelType); + settingsTabs = List.of(standardPanel, audioPanel, advancedPanel); + + JTabbedPane tabs = new JTabbedPane(); + tabs.addTab("Standard", standardPanel); + tabs.addTab("Audio", audioPanel); + tabs.addTab("Permissions", permissionsPanel); + tabs.addTab("Advanced", advancedPanel); + + // The tabs need no more than their natural height, so they sit at the bottom + // with the buttons and every spare pixel goes to the description instead. + JPanel bottom = new JPanel(new BorderLayout(0, UIScale.scale(6))); + bottom.add(tabs, BorderLayout.CENTER); + bottom.add(buttons(), BorderLayout.SOUTH); + + getContentPane().setLayout(new BorderLayout(0, UIScale.scale(6))); + getContentPane().add(header(), BorderLayout.CENTER); + getContentPane().add(bottom, BorderLayout.SOUTH); + + setEnabledForLoading(false); + Dialogs.closeOnEscape(this); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + setSize(UIScale.scale(new Dimension(560, 620))); + setMinimumSize(UIScale.scale(new Dimension(480, 520))); + setLocationRelativeTo(owner); + + if (channel != null) load(); + else prepareNew(defaults); + } + + // ---- layout ---- + + private JPanel header() { + JPanel panel = new JPanel(new GridBagLayout()); + panel.setBorder(new ScaledEmptyBorder(8, 8, 0, 8)); + GridBagConstraints c = new GridBagConstraints(); + c.insets = UIScale.scale(new Insets(3, 4, 3, 4)); + c.anchor = GridBagConstraints.WEST; + c.fill = GridBagConstraints.HORIZONTAL; + + name.setToolTipText(NAME_TOOLTIP); + password.setToolTipText("Optional password for this channel."); + topic.setToolTipText("Optional topic for this channel, displayed in the info area on the right."); + password.getDocument().addDocumentListener(new DocumentListener() { + @Override + public void insertUpdate(DocumentEvent e) { + passwordEdited = true; + } + + @Override + public void removeUpdate(DocumentEvent e) { + passwordEdited = true; + } + + @Override + public void changedUpdate(DocumentEvent e) { + passwordEdited = true; + } + }); + + c.gridx = 0; + c.gridy = 0; + panel.add(new JLabel("Name:"), c); + c.gridx = 1; + c.weightx = 1; + panel.add(name, c); + c.gridx = 2; + c.weightx = 0; + panel.add(iconField(), c); + + c.gridx = 0; + c.gridy = 1; + panel.add(new JLabel("Password:"), c); + c.gridx = 1; + c.gridwidth = 2; + c.weightx = 1; + panel.add(password, c); + + c.gridwidth = 1; + c.gridx = 0; + c.gridy = 2; + c.weightx = 0; + panel.add(new JLabel("Topic:"), c); + c.gridx = 1; + c.gridwidth = 2; + c.weightx = 1; + panel.add(topic, c); + + c.gridwidth = 1; + c.gridx = 0; + c.gridy = 3; + c.weightx = 0; + panel.add(new JLabel("Description:"), c); + JButton popOut = new JButton("Edit…"); + popOut.setToolTipText("Tear off description editor"); + popOut.addActionListener(a -> editDescription()); + c.gridx = 1; + c.gridwidth = 2; + c.fill = GridBagConstraints.NONE; + panel.add(popOut, c); + + description.setLineWrap(true); + description.setWrapStyleWord(true); + c.gridx = 0; + c.gridy = 4; + c.gridwidth = 3; + c.weightx = 1; + c.weighty = 1; + c.fill = GridBagConstraints.BOTH; + panel.add(new JScrollPane(description), c); + return panel; + } + + private JPanel iconField() { + iconButton.setToolTipText("Set channel icon."); + iconButton.setPreferredSize(UIScale.scale(new Dimension(26, 24))); + iconButton.setMargin(new Insets(1, 1, 1, 1)); + iconButton.addActionListener(a -> chooseIcon()); + iconButton.addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + if (e.isPopupTrigger()) showIconMenu(e); + } + + @Override + public void mouseReleased(MouseEvent e) { + if (e.isPopupTrigger()) showIconMenu(e); + } + }); + JPanel row = new JPanel(new BorderLayout(UIScale.scale(4), 0)); + row.add(new JLabel("Icon:"), BorderLayout.WEST); + row.add(iconButton, BorderLayout.CENTER); + return row; + } + + private JPanel buttons() { + JButton cancel = new JButton("Cancel"); + ok.addActionListener(a -> save()); + cancel.addActionListener(a -> dispose()); + JPanel panel = new JPanel(new BorderLayout()); + panel.setBorder(new ScaledEmptyBorder(0, 8, 8, 8)); + JPanel right = new JPanel(); + right.add(ok); + right.add(cancel); + panel.add(right, BorderLayout.EAST); + getRootPane().setDefaultButton(ok); + return panel; + } + + // ---- loading ---- + + private void load() { + conn.requestChannelSettings(channel.id, (settings, error) -> SwingUtilities.invokeLater(() -> { + if (error != null) { + JOptionPane.showMessageDialog(this, "Could not read the channel: " + error, + "Error", JOptionPane.ERROR_MESSAGE); + dispose(); + return; + } + apply(settings); + })); + conn.requestChannelPermissions(channel.id, (permissions, error) -> SwingUtilities.invokeLater(() -> { + if (error != null) permissionsPanel.showUnavailable("No permission to view channel permissions."); + else permissionsPanel.read(permissions); + })); + } + + /** + * Opens the dialog on a channel that does not exist yet. Its permissions start empty + * and editable — they are applied to the channel once the server has created it. + */ + private void prepareNew(ChannelSettings defaults) { + permissionsPanel.read(Map.of()); + apply(defaults); + name.selectAll(); + } + + private void apply(ChannelSettings settings) { + original = settings; + name.setText(settings.name); + topic.setText(settings.topic); + description.setText(settings.description); + description.setCaretPosition(0); + if (settings.hasPassword) password.setText(PASSWORD_PLACEHOLDER); + passwordEdited = false; + setIconId(settings.iconId); + for (Tab tab : settingsTabs) tab.read(settings); + setEnabledForLoading(true); + name.requestFocusInWindow(); + } + + private void setEnabledForLoading(boolean loaded) { + ok.setEnabled(loaded); + name.setEnabled(loaded); + password.setEnabled(loaded); + topic.setEnabled(loaded); + description.setEnabled(loaded); + iconButton.setEnabled(loaded); + } + + // ---- icon ---- + + private void setIconId(long id) { + setIconId(id, ICON_RETRIES); + } + + /** + * @param retries how many more times to look for an icon that is still downloading; + * one that never arrives (deleted, or not ours to read) simply stays blank + */ + private void setIconId(long id, int retries) { + iconId = id; + ImageIcon icon = groupIcons.icon(id); + iconButton.setIcon(icon); + if (icon != null || id == 0 || retries <= 0) return; + Timer retry = new Timer(ICON_RETRY_MS, null); + retry.setRepeats(false); + retry.addActionListener(e -> { + if (iconId == id) setIconId(id, retries - 1); + }); + retry.start(); + } + + private void chooseIcon() { + IconChooserDialog chooser = new IconChooserDialog(this, conn, groupIcons); + chooser.setVisible(true); + if (chooser.isAccepted()) setIconId(chooser.getIconId()); + } + + private void showIconMenu(MouseEvent e) { + JPopupMenu menu = new JPopupMenu(); + JMenuItem edit = new JMenuItem("Edit Icon"); + edit.addActionListener(a -> chooseIcon()); + JMenuItem remove = new JMenuItem("Remove Icon"); + remove.setEnabled(iconId != 0); + remove.addActionListener(a -> setIconId(0)); + menu.add(edit); + menu.add(remove); + menu.show(e.getComponent(), e.getX(), e.getY()); + } + + // ---- description ---- + + private void editDescription() { + DescriptionEditorDialog editor = new DescriptionEditorDialog(this, description.getText()); + editor.setVisible(true); + if (editor.isAccepted()) description.setText(editor.getDescription()); + } + + // ---- saving ---- + + private void save() { + if (original == null) return; + ChannelSettings edited = original.copy(); + edited.name = name.getText().trim(); + edited.topic = topic.getText(); + edited.description = description.getText(); + edited.password = passwordEdited ? new String(password.getPassword()) : null; + edited.iconId = iconId; + for (Tab tab : settingsTabs) tab.write(edited); + + if (edited.name.isEmpty()) { + JOptionPane.showMessageDialog(this, "The channel needs a name.", + "Error", JOptionPane.ERROR_MESSAGE); + return; + } + + if (channel == null) { + ok.setEnabled(false); + conn.createChannel(parentId, edited.creationParameters(), permissionsPanel.changed(), + (channelId, error) -> SwingUtilities.invokeLater( + () -> finish(error, "Could not create the channel: "))); + return; + } + + Map changes = edited.changesFrom(original); + Map setPermissions = permissionsPanel.changed(); + List clearedPermissions = permissionsPanel.cleared(); + if (changes.isEmpty() && setPermissions.isEmpty() && clearedPermissions.isEmpty()) { + dispose(); + return; + } + + ok.setEnabled(false); + conn.applyChannelEdit(channel.id, changes, setPermissions, clearedPermissions, + error -> SwingUtilities.invokeLater(() -> finish(error, "Could not save the channel: "))); + } + + /** Closes the dialog, or reports why the server would not have it and lets the user retry. */ + private void finish(String error, String errorPrefix) { + if (error == null) { + dispose(); + return; + } + ok.setEnabled(true); + JOptionPane.showMessageDialog(this, errorPrefix + error, "Error", JOptionPane.ERROR_MESSAGE); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelMenu.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelMenu.java new file mode 100644 index 0000000..cb7dfe9 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelMenu.java @@ -0,0 +1,82 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.net.ChannelNode; +import eu.lixko.ts3j.client.net.ChannelSettings; + +import javax.swing.JMenuItem; +import javax.swing.JPopupMenu; + +/** + * The context menu for a channel, shared by the server tree and channel links + * in the chat log. + */ +final class ChannelMenu { + + private ChannelMenu() { + } + + static JPopupMenu build(ChannelNode channel, ServerTreePanel.Actions actions) { + JPopupMenu menu = new JPopupMenu(); + JMenuItem join = new JMenuItem("Join channel", Icons.of("CHANNEL_SWITCH")); + join.addActionListener(a -> actions.joinChannel(channel.id)); + menu.add(join); + menu.addSeparator(); + // Both start out temporary: a channel made from another channel's menu is + // usually a throwaway one, and a permanent channel is a deliberate choice. + JMenuItem create = new JMenuItem("Create Channel", Icons.of("CHANNEL_CREATE")); + create.addActionListener(a -> actions.createChannel(null, ChannelSettings.Type.TEMPORARY)); + menu.add(create); + JMenuItem createSub = new JMenuItem("Create Sub-Channel", Icons.of("CHANNEL_CREATE_SUB")); + createSub.addActionListener(a -> actions.createChannel(channel, ChannelSettings.Type.TEMPORARY)); + menu.add(createSub); + JMenuItem edit = new JMenuItem("Edit Channel", Icons.of("CHANNEL_EDIT")); + edit.addActionListener(a -> actions.editChannel(channel)); + menu.add(edit); + JMenuItem delete = new JMenuItem("Delete Channel", Icons.of("CHANNEL_DELETE")); + delete.addActionListener(a -> actions.deleteChannel(channel)); + menu.add(delete); + menu.addSeparator(); + addSubscriptionItems(menu, channel, actions); + JMenuItem files = new JMenuItem("Browse files", Icons.of("FILETRANSFER")); + files.addActionListener(a -> actions.browseFiles(channel)); + menu.add(files); + return menu; + } + + /** + * The subscription entries, offered the way the official client does: the channel + * itself toggles, and the family entries appear only where they would do something. + */ + private static void addSubscriptionItems(JPopupMenu menu, ChannelNode channel, + ServerTreePanel.Actions actions) { + if (channel.subscribed) { + add(menu, "Unsubscribe from Channel", + () -> actions.setChannelSubscribed(channel, false, false), + "UNSUBSCRIBE_FROM_CHANNEL"); + } else { + add(menu, "Subscribe to Channel", + () -> actions.setChannelSubscribed(channel, false, true), + "SUBSCRIBE_TO_CHANNEL"); + } + if (!channel.children.isEmpty()) { + if (!channel.allSubscribed()) { + add(menu, "Subscribe to Channel Family", + () -> actions.setChannelSubscribed(channel, true, true), + "SUBSCRIBE_TO_CHANNEL_FAMILY", "SUBSCRIBE_TO_ALL_CHANNELS"); + } + if (channel.anySubscribed()) { + add(menu, "Unsubscribe from Channel Family", + () -> actions.setChannelSubscribed(channel, true, false), + "UNSUBSCRIBE_FROM_CHANNEL_FAMILY", "UNSUBSCRIBE_FROM_ALL_CHANNELS"); + } + } + menu.addSeparator(); + } + + /** Adds an item, icon-less when the pack has none of the given keys. */ + private static void add(JPopupMenu menu, String text, Runnable action, String... iconKeys) { + JMenuItem item = new JMenuItem(text, Icons.ofAny(iconKeys)); + item.addActionListener(a -> action.run()); + menu.add(item); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelPermissionsPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelPermissionsPanel.java new file mode 100644 index 0000000..3d05315 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelPermissionsPanel.java @@ -0,0 +1,151 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JSpinner; +import javax.swing.SpinnerNumberModel; +import java.awt.Color; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * The channel editor's "Permissions" tab: the needed-power permissions set on the channel + * itself, which is the subset of channel permissions TeamSpeak surfaces here. + * + *

    These are not channel properties but permissions, so they are read with + * {@code channelpermlist} and written with {@code channeladdperm}. A power left at zero is + * not a permission the channel carries: clearing a spinner back to zero removes the + * permission again so the channel inherits it, which is how the official client behaves. + */ +final class ChannelPermissionsPanel extends JPanel { + + /** The regular powers, in the order the official dialog lists them. */ + private static final String[][] REGULAR = { + {"i_channel_needed_join_power", "Join:"}, + {"i_channel_needed_subscribe_power", "Subscribe:"}, + {"i_channel_needed_description_view_power", "Desc. View:"}, + {"i_channel_needed_modify_power", "Modify:"}, + {"i_channel_needed_delete_power", "Delete:"}}; + + private static final String[][] FILE_TRANSFER = { + {"i_ft_needed_file_browse_power", "Browse:"}, + {"i_ft_needed_file_upload_power", "Upload:"}, + {"i_ft_needed_file_download_power", "Download:"}, + {"i_ft_needed_file_rename_power", "Rename:"}, + {"i_ft_needed_directory_create_power", "Dir. Create:"}}; + + private final Map spinners = new LinkedHashMap<>(); + /** The values the server reported, to tell an edited power from an untouched one. */ + private final Map original = new LinkedHashMap<>(); + private final JLabel status = new JLabel(" "); + + ChannelPermissionsPanel() { + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + setBorder(new ScaledEmptyBorder(8, 8, 8, 8)); + + JPanel groups = new JPanel(); + groups.setLayout(new BoxLayout(groups, BoxLayout.X_AXIS)); + groups.add(group("Regular Needed Powers", REGULAR)); + groups.add(Box.createHorizontalStrut(UIScale.scale(8))); + groups.add(group("File Transfer Needed Powers", FILE_TRANSFER)); + groups.setAlignmentX(0f); + add(groups); + + status.setAlignmentX(0f); + status.setBorder(new ScaledEmptyBorder(6, 2, 0, 2)); + add(status); + add(Box.createVerticalGlue()); + setEditable(false); + } + + /** Fills the spinners from a {@code channelpermlist} result and enables editing. */ + void read(Map permissions) { + original.clear(); + for (Map.Entry entry : spinners.entrySet()) { + int value = permissions.getOrDefault(entry.getKey(), 0); + original.put(entry.getKey(), value); + entry.getValue().setValue(value); + } + setEditable(true); + setStatus(" ", false); + } + + /** Greys the tab out with a reason, e.g. when the server refuses to show the permissions. */ + void showUnavailable(String message) { + setEditable(false); + setStatus(message, true); + } + + /** The permissions whose power was changed to a non-zero value. */ + Map changed() { + Map changed = new LinkedHashMap<>(); + for (Map.Entry entry : spinners.entrySet()) { + int value = (Integer) entry.getValue().getValue(); + if (value != 0 && value != original.getOrDefault(entry.getKey(), 0)) { + changed.put(entry.getKey(), value); + } + } + return changed; + } + + /** The permissions cleared back to zero, which are removed from the channel. */ + List cleared() { + List cleared = new ArrayList<>(); + for (Map.Entry entry : spinners.entrySet()) { + int value = (Integer) entry.getValue().getValue(); + if (value == 0 && original.getOrDefault(entry.getKey(), 0) != 0) cleared.add(entry.getKey()); + } + return cleared; + } + + void setStatus(String message, boolean error) { + status.setText(message == null || message.isEmpty() ? " " : message); + status.setForeground(error ? Color.RED.darker() : Theme.chatSystem()); + } + + private void setEditable(boolean editable) { + for (JSpinner spinner : spinners.values()) spinner.setEnabled(editable); + } + + private JPanel group(String title, String[][] permissions) { + JPanel panel = new JPanel(new GridBagLayout()); + panel.setBorder(BorderFactory.createTitledBorder(title)); + GridBagConstraints c = new GridBagConstraints(); + c.insets = UIScale.scale(new Insets(3, 4, 3, 4)); + c.anchor = GridBagConstraints.WEST; + c.fill = GridBagConstraints.HORIZONTAL; + int row = 0; + for (String[] permission : permissions) { + JSpinner spinner = Spinners.compact(new JSpinner(new SpinnerNumberModel(0, 0, 9999, 1))); + spinners.put(permission[0], spinner); + c.gridx = 0; + c.gridy = row; + c.weightx = 0; + panel.add(new JLabel(permission[1]), c); + c.gridx = 1; + c.weightx = 1; + c.fill = GridBagConstraints.NONE; + panel.add(spinner, c); + c.fill = GridBagConstraints.HORIZONTAL; + row++; + } + // Keeps the rows at the top of the group instead of centred in whatever height + // the tab happens to give it. + c.gridx = 0; + c.gridy = row; + c.weighty = 1; + panel.add(Box.createGlue(), c); + return panel; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelStandardPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelStandardPanel.java new file mode 100644 index 0000000..d36a335 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChannelStandardPanel.java @@ -0,0 +1,197 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.net.ChannelNode; +import eu.lixko.ts3j.client.net.ChannelSettings; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.ButtonGroup; +import javax.swing.DefaultComboBoxModel; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JSeparator; +import javax.swing.JSpinner; +import javax.swing.SpinnerNumberModel; +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.util.List; +import java.util.function.Consumer; + +/** + * The channel editor's "Standard" tab: how long the channel lives, whether it is the + * server's default one, where it sorts among its siblings, and its moderation setting. + */ +final class ChannelStandardPanel extends JPanel implements ChannelDialog.Tab { + + private final JRadioButton temporary = new JRadioButton("Temporary"); + private final JRadioButton semiPermanent = new JRadioButton("Semi-Permanent"); + private final JRadioButton permanent = new JRadioButton("Permanent"); + private final JCheckBox defaultChannel = new JCheckBox("Default Channel"); + private final JComboBox sortAfter = new JComboBox<>(); + private final JSpinner talkPower = new JSpinner(new SpinnerNumberModel(0, 0, 9999, 1)); + + private Consumer typeListener; + + /** + * @param siblings the channels this one shares a parent with, in tree order and + * excluding the channel being edited + */ + ChannelStandardPanel(List siblings) { + super(new BorderLayout(UIScale.scale(8), UIScale.scale(8))); + setBorder(new ScaledEmptyBorder(8, 8, 8, 8)); + + temporary.setToolTipText("Channel will be deleted when the last user left."); + semiPermanent.setToolTipText("Channel exists until server is restarted."); + permanent.setToolTipText("Channel will exist until manually deleted."); + ButtonGroup types = new ButtonGroup(); + types.add(temporary); + types.add(semiPermanent); + types.add(permanent); + for (JRadioButton radio : new JRadioButton[]{temporary, semiPermanent, permanent}) { + radio.addActionListener(a -> fireTypeChanged()); + } + + defaultChannel.setToolTipText("The default channel is the place where new clients join on login." + + "
    There can be only one default channel for the whole server."); + + DefaultComboBoxModel order = new DefaultComboBoxModel<>(); + order.addElement(new SortEntry(0, "(first)")); + for (ChannelNode sibling : siblings) order.addElement(new SortEntry(sibling.id, sibling.name)); + sortAfter.setModel(order); + sortAfter.setToolTipText("Channel will be sorted below this channel."); + sortAfter.setPreferredSize(new Dimension(UIScale.scale(200), sortAfter.getPreferredSize().height)); + Spinners.compact(talkPower); + + add(typeBox(), BorderLayout.WEST); + add(rightColumn(), BorderLayout.CENTER); + } + + /** Notified whenever the channel type changes, so the delete delay can follow it. */ + void onTypeChanged(Consumer listener) { + this.typeListener = listener; + } + + @Override + public void read(ChannelSettings settings) { + switch (settings.type) { + case TEMPORARY: + temporary.setSelected(true); + break; + case SEMI_PERMANENT: + semiPermanent.setSelected(true); + break; + default: + permanent.setSelected(true); + break; + } + defaultChannel.setSelected(settings.defaultChannel); + // The default channel cannot simply stop being one; another has to take over. + defaultChannel.setEnabled(!settings.defaultChannel); + select(settings.order); + talkPower.setValue(settings.neededTalkPower); + fireTypeChanged(); + } + + @Override + public void write(ChannelSettings settings) { + settings.type = selectedType(); + settings.defaultChannel = defaultChannel.isSelected(); + SortEntry entry = (SortEntry) sortAfter.getSelectedItem(); + settings.order = entry == null ? 0 : entry.channelId; + settings.neededTalkPower = (Integer) talkPower.getValue(); + } + + private ChannelSettings.Type selectedType() { + if (temporary.isSelected()) return ChannelSettings.Type.TEMPORARY; + if (semiPermanent.isSelected()) return ChannelSettings.Type.SEMI_PERMANENT; + return ChannelSettings.Type.PERMANENT; + } + + private void fireTypeChanged() { + if (typeListener != null) typeListener.accept(selectedType()); + } + + private void select(int channelId) { + for (int i = 0; i < sortAfter.getItemCount(); i++) { + if (sortAfter.getItemAt(i).channelId == channelId) { + sortAfter.setSelectedIndex(i); + return; + } + } + sortAfter.setSelectedIndex(0); + } + + private JPanel typeBox() { + JPanel box = new JPanel(); + box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS)); + box.setBorder(BorderFactory.createTitledBorder("Channel Type")); + for (JRadioButton radio : new JRadioButton[]{temporary, semiPermanent, permanent}) { + radio.setAlignmentX(0f); + box.add(radio); + } + JSeparator line = new JSeparator(); + line.setAlignmentX(0f); + line.setMaximumSize(new Dimension(Integer.MAX_VALUE, UIScale.scale(8))); + box.add(Box.createVerticalStrut(UIScale.scale(4))); + box.add(line); + box.add(Box.createVerticalStrut(UIScale.scale(4))); + defaultChannel.setAlignmentX(0f); + box.add(defaultChannel); + box.add(Box.createVerticalGlue()); + return box; + } + + private JPanel rightColumn() { + JPanel sort = new JPanel(new BorderLayout()); + sort.setBorder(BorderFactory.createTitledBorder("Sort This Channel After:")); + sort.add(sortAfter, BorderLayout.CENTER); + + JPanel moderation = new JPanel(new FlowLayout(FlowLayout.LEFT, UIScale.scale(6), UIScale.scale(2))); + moderation.setBorder(BorderFactory.createTitledBorder("Moderation")); + JLabel label = new JLabel("Needed Talk Power:"); + label.setToolTipText("Talk Power required to speak in this channel."); + moderation.add(label); + moderation.add(talkPower); + + // Both groups keep their natural height; the filler below soaks up the rest, so + // they sit at the top instead of stretching over the whole tab. + JPanel column = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + c.gridx = 0; + c.fill = GridBagConstraints.HORIZONTAL; + c.weightx = 1; + c.insets = UIScale.scale(new Insets(0, 0, 6, 0)); + column.add(sort, c); + column.add(moderation, c); + c.weighty = 1; + c.fill = GridBagConstraints.BOTH; + column.add(Box.createGlue(), c); + return column; + } + + /** One entry of the "sort after" list: a sibling channel, or the top of the list. */ + private static final class SortEntry { + final int channelId; + final String label; + + SortEntry(int channelId, String label) { + this.channelId = channelId; + this.label = label; + } + + @Override + public String toString() { + return label; + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatAttachmentActions.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatAttachmentActions.java new file mode 100644 index 0000000..fe69ed7 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatAttachmentActions.java @@ -0,0 +1,145 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.myts.ChatAttachment; +import eu.lixko.ts3j.client.myts.ChatAttachments; +import eu.lixko.ts3j.client.myts.MyTsException; +import eu.lixko.ts3j.client.net.ConnectionListener.ChatScope; +import eu.lixko.ts3j.client.net.PictureDownloads; +import eu.lixko.ts3j.client.session.ServerSession; + +import javax.imageio.ImageIO; +import javax.swing.JFileChooser; +import javax.swing.SwingUtilities; +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.util.List; +import java.util.function.Function; + +/** + * Shares files in one server's chats through myTeamSpeak, and shows and saves the files + * shared there. Failures land in the chat as system lines. + */ +final class ChatAttachmentActions implements ChatPanel.AttachmentHandler { + + private static final String SIGN_IN = "Sign in to myTeamSpeak to share files"; + private static final String PASTED_NAME = "image.png"; + + /** Where files were last shared from or saved to, for every server alike. */ + private static File lastDirectory; + + private final MainFrame host; + private final ServerSession session; + private final ChatPanel chat; + private final PictureDownloads pictures; + private final Function scopes; + + ChatAttachmentActions(MainFrame host, ServerSession session, ChatPanel chat, PictureDownloads pictures, + Function scopes) { + this.host = host; + this.session = session; + this.chat = chat; + this.pictures = pictures; + this.scopes = scopes; + } + + @Override + public void choose(ChatPanel.Target target, int clientId) { + if (!signedIn()) return; + JFileChooser chooser = new JFileChooser(lastDirectory); + chooser.setMultiSelectionEnabled(true); + chooser.setDialogTitle("Share files"); + if (chooser.showOpenDialog(host) != JFileChooser.APPROVE_OPTION) return; + File[] files = chooser.getSelectedFiles(); + if (files.length > 0) lastDirectory = files[0].getParentFile(); + share(target, clientId, List.of(files)); + } + + @Override + public void share(ChatPanel.Target target, int clientId, List files) { + if (!signedIn()) return; + for (File file : files) { + if (!file.isFile()) continue; + if (file.length() > ChatAttachments.MAX_UPLOAD_BYTES) { + chat.appendSystem(file.getName() + " is over " + (ChatAttachments.MAX_UPLOAD_BYTES >> 20) + " MB."); + continue; + } + try { + session.sendAttachment(scopes.apply(target), clientId, host.attachments(), + new FileInputStream(file), file.length(), file.getName()); + } catch (IOException e) { + chat.appendSystem("Could not share " + file.getName() + ": " + e.getMessage()); + } + } + } + + @Override + public void share(ChatPanel.Target target, int clientId, BufferedImage image) { + if (!signedIn()) return; + ByteArrayOutputStream png = new ByteArrayOutputStream(); + try { + ImageIO.write(image, "png", png); + } catch (IOException e) { + chat.appendSystem("Could not share the picture: " + e.getMessage()); + return; + } + session.sendAttachment(scopes.apply(target), clientId, host.attachments(), + new ByteArrayInputStream(png.toByteArray()), png.size(), PASTED_NAME); + } + + @Override + public void open(String href, boolean picture) { + ChatAttachment.Ref ref = ChatAttachment.Ref.parse(href); + if (ref == null) return; + File shown = picture ? pictures.get(href) : null; + BufferedImage image = shown == null ? null : read(shown); + if (image != null) { + new PictureViewer(host, ref.fileName(), image, () -> save(ref, shown)).setVisible(true); + } else { + save(ref, null); + } + } + + /** Asks where to save the file, then copies it there: from {@code have} when given, else fetched. */ + private void save(ChatAttachment.Ref ref, File have) { + if (have == null && !signedIn()) return; + JFileChooser chooser = new JFileChooser(lastDirectory); + chooser.setDialogTitle("Save " + ref.fileName()); + chooser.setSelectedFile(new File(lastDirectory, ref.fileName())); + if (chooser.showSaveDialog(host) != JFileChooser.APPROVE_OPTION) return; + File target = chooser.getSelectedFile(); + lastDirectory = target.getParentFile(); + ChatAttachments attachments = host.attachments(); + Thread.ofVirtual().name("chat-attachment-save").start(() -> { + try { + if (have != null) { + Files.copy(have.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING); + } else { + Files.write(target.toPath(), attachments.download(ref, ChatAttachments.MAX_UPLOAD_BYTES)); + } + } catch (IOException | MyTsException e) { + SwingUtilities.invokeLater(() -> + chat.appendSystem("Could not save " + ref.fileName() + ": " + e.getMessage())); + } + }); + } + + private boolean signedIn() { + if (host.canShareFiles()) return true; + chat.appendSystem(SIGN_IN + "."); + return false; + } + + private static BufferedImage read(File file) { + try { + return ImageIO.read(file); + } catch (IOException e) { + return null; + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatLogsPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatLogsPanel.java new file mode 100644 index 0000000..125f29a --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatLogsPanel.java @@ -0,0 +1,88 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.config.AppDirs; +import eu.lixko.ts3j.client.config.Settings; + +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JFileChooser; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; +import java.awt.BorderLayout; +import java.awt.GridBagConstraints; +import java.io.File; + +/** + * Options page for chat logs: whether they are kept, and where. By default they go into the + * TeamSpeak 3 client's own folder, so both clients show the same history. + */ +final class ChatLogsPanel extends FormPanel { + + private final Settings settings; + private final JCheckBox enabled = new JCheckBox("Keep chat logs"); + private final JTextField folder = new JTextField(18); + private final JButton browse = new JButton("Browse…"); + private final JCheckBox pictures = new JCheckBox("Show pictures in descriptions and chat"); + + ChatLogsPanel(Settings settings) { + this.settings = settings; + GridBagConstraints c = gbc(); + + enabled.setSelected(settings.chatLogs); + enabled.setToolTipText("Write every chat to disk and show its history when it opens again"); + enabled.addActionListener(e -> updateEnabled()); + + folder.setText(settings.chatLogDir); + folder.putClientProperty("JTextField.placeholderText", "The TeamSpeak 3 client's folder"); + folder.setToolTipText("Leave empty to share the TeamSpeak 3 client's logs:
    " + + AppDirs.chatLogs() + ""); + limitWidth(folder, FIELD_WIDTH); + browse.addActionListener(e -> browseForFolder()); + JPanel folderRow = new JPanel(new BorderLayout(UIScale.scale(6), 0)); + folderRow.add(folder, BorderLayout.CENTER); + folderRow.add(browse, BorderLayout.EAST); + + JLabel nextConnect = new JLabel("Takes effect on the next connect."); + nextConnect.setEnabled(false); + + pictures.setSelected(settings.descriptionPictures); + pictures.setToolTipText("Off: only links to them, nothing fetched"); + + int row = 0; + addSection(this, c, row++, "Logging"); + addWide(this, c, row++, enabled); + addRow(this, c, row++, new JLabel("Folder:"), folderRow); + c.gridx = 1; + c.gridy = row++; + add(nextConnect, c); + addSection(this, c, row++, "Descriptions"); + addWide(this, c, row++, pictures); + addFiller(this, c, row); + updateEnabled(); + } + + private void updateEnabled() { + folder.setEnabled(enabled.isSelected()); + browse.setEnabled(enabled.isSelected()); + } + + private void browseForFolder() { + JFileChooser chooser = new JFileChooser(); + chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + chooser.setDialogTitle("Folder for chat logs"); + String current = folder.getText().trim(); + chooser.setCurrentDirectory(current.isEmpty() ? AppDirs.chatLogs().toFile() : new File(current)); + if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { + folder.setText(chooser.getSelectedFile().getAbsolutePath()); + } + } + + /** Copies the page into the settings; the caller saves them. */ + void apply() { + settings.chatLogs = enabled.isSelected(); + settings.chatLogDir = folder.getText().trim(); + settings.descriptionPictures = pictures.isSelected(); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatPanel.java new file mode 100644 index 0000000..c6b2229 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatPanel.java @@ -0,0 +1,761 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.myts.ChatAttachment; +import eu.lixko.ts3j.client.net.PictureDownloads; +import eu.lixko.ts3j.client.text.BBCode; +import eu.lixko.ts3j.client.text.ChatHtml; +import eu.lixko.ts3j.client.text.HtmlText; +import eu.lixko.ts3j.client.text.TextQuery; +import eu.lixko.ts3j.client.text.TsLink; + +import javax.swing.AbstractAction; +import javax.swing.BorderFactory; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JEditorPane; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollBar; +import javax.swing.JScrollPane; +import javax.swing.JTabbedPane; +import javax.swing.JTextField; +import javax.swing.KeyStroke; +import javax.swing.SwingUtilities; +import javax.swing.event.HyperlinkEvent; +import javax.swing.text.BadLocationException; +import javax.swing.text.Element; +import javax.swing.text.StyleConstants; +import javax.swing.text.html.HTML; +import javax.swing.text.html.HTMLDocument; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Insets; +import java.awt.Point; +import java.awt.event.ActionEvent; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseWheelEvent; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.function.Supplier; + +/** + * Chat area with one tab per conversation (server, current channel and one per + * private chat). The tab strip sits between the log and the input line. Logs are + * rendered as HTML: sender names are links that open the client context menu, + * and message bodies go through the {@link BBCode} renderer. + */ +public final class ChatPanel extends JPanel { + + /** Where an outgoing message should go. */ + public enum Target {CHANNEL, SERVER, PRIVATE} + + public interface SendHandler { + /** {@code clientId} is only meaningful for {@link Target#PRIVATE}. */ + void send(Target target, int clientId, String text); + } + + /** Invoked when a client or channel link in the log is clicked. */ + public interface LinkHandler { + void onClientLink(TsLink.Ref ref, Component source, int x, int y); + + void onChannelLink(TsLink.Ref ref, Component source, int x, int y); + + /** The "unread offline messages" log line was clicked. */ + void onOfflineMessagesLink(); + } + + /** Files shared in the chats, which the host sends, fetches and shows. */ + public interface AttachmentHandler { + /** Asks which files to share in the conversation. */ + void choose(Target target, int clientId); + + void share(Target target, int clientId, List files); + + void share(Target target, int clientId, BufferedImage image); + + /** + * A shared file was clicked. + * + * @param picture whether the picture shown for it was, rather than its name + */ + void open(String href, boolean picture); + } + + private final JTabbedPane tabs = new JTabbedPane(JTabbedPane.BOTTOM); + private final JTextField input = new JTextField(); + + /** Tab strip height, so a tab with no icon still lines up with the others. */ + private static final int HEADER_HEIGHT = 20; + /** The largest a shared picture is drawn in the log. */ + private static final int PICTURE_WIDTH = 320; + private static final int PICTURE_HEIGHT = 240; + private static final int PICTURE_WIDTH_STEP = 40; + + private static final String NO_SERVER = "Server"; + private static final String NO_CHANNEL = "Channel"; + + private final Tab serverTab = new Tab(Target.SERVER, 0, NO_SERVER, Icons.server()); + private final Tab channelTab = new Tab(Target.CHANNEL, 0, NO_CHANNEL, Icons.channelChat()); + /** Private chats keyed by the peer's client id. */ + private final Map privateTabs = new LinkedHashMap<>(); + /** Static-content tabs (e.g. a moved-out description), keyed by caller-chosen id. */ + private final Map noteTabs = new LinkedHashMap<>(); + + private final TabDragReorder dragReorder = new TabDragReorder(tabs, this::moveTab); + + private final ChatSearch search = new ChatSearch(new ChatSearch.Host() { + @Override + public JEditorPane selectedLog() { + Tab t = selectedTab(); + return t == null ? null : t.log; + } + + @Override + public void showMatching(TextQuery filter) { + Tab t = selectedTab(); + if (t != null) t.showMatching(filter); + } + }); + + private SendHandler sendHandler; + private LinkHandler linkHandler; + private AttachmentHandler attachmentHandler; + private final TextZoom zoom; + private final PictureDownloads downloads; + private final DescriptionPictures pictures; + /** The server's unique identifier, which shared files are kept under; null while unknown. */ + private final Supplier room; + private final JButton attach = new JButton(Icons.of("UPLOAD")); + private boolean inputEnabled; + private boolean sharingAvailable; + private final Runnable onPicture = () -> SwingUtilities.invokeLater(() -> { + for (Tab t : allTabs()) t.picturesChanged(); + }); + + public ChatPanel(TextZoom zoom, Settings settings, PictureDownloads downloads, Supplier room) { + super(new BorderLayout()); + this.zoom = zoom; + this.downloads = downloads; + this.pictures = new DescriptionPictures(downloads, settings); + this.room = room; + + tabs.setFont(Theme.uiFont()); + tabs.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); + // Half the look and feel's leading padding: these tabs carry a name that is worth + // the width, and their headers bring their own spacing. + tabs.putClientProperty("JTabbedPane.tabInsets", new Insets(4, 6, 4, 12)); + addTab(serverTab, false); + addTab(channelTab, false); + tabs.setSelectedIndex(0); + tabs.addChangeListener(e -> { + Tab t = selectedTab(); + if (t != null) t.setUnread(false); + // A search filters only the tab it is in; the one left behind shows everything again. + for (Tab other : allTabs()) { + if (other != t) other.showMatching(null); + } + search.retarget(); + }); + tabs.addMouseWheelListener(this::onWheel); + dragReorder.attach(tabs); + add(tabs, BorderLayout.CENTER); + add(search.bar(), BorderLayout.NORTH); + String find = "ts3-chat-find"; + getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("control F"), find); + getActionMap().put(find, new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + openFind(); + } + }); + + JPanel bottom = new JPanel(new BorderLayout(UIScale.scale(4), 0)); + bottom.setBorder(new ScaledEmptyBorder(4, 0, 0, 0)); + bottom.add(input, BorderLayout.CENTER); + bottom.add(attach, BorderLayout.EAST); + add(bottom, BorderLayout.SOUTH); + + input.addActionListener(e -> fireSend()); + input.setTransferHandler(attachmentTransfer(input)); + attach.putClientProperty("JButton.buttonType", "toolBarButton"); + attach.setFocusable(false); + attach.addActionListener(e -> { + Tab tab = selectedTab(); + if (attachmentHandler != null && tab != null && tab.target != null) { + attachmentHandler.choose(tab.target, tab.clientId); + } + }); + + setInputEnabled(false); + } + + public void setSendHandler(SendHandler h) { + this.sendHandler = h; + } + + public void setLinkHandler(LinkHandler h) { + this.linkHandler = h; + } + + public void setAttachmentHandler(AttachmentHandler h) { + this.attachmentHandler = h; + } + + /** Whether files can be shared at all, i.e. signed in to myTeamSpeak. */ + public void setSharingAvailable(boolean available) { + edt(() -> { + sharingAvailable = available; + updateAttach(); + }); + } + + @Override + public void addNotify() { + super.addNotify(); + downloads.addListener(onPicture); + } + + @Override + public void removeNotify() { + downloads.removeListener(onPicture); + super.removeNotify(); + } + + /** Opens the find bar on the selected conversation. */ + public void openFind() { + edt(search::open); + } + + /** Appends text to the input line, e.g. a client link dropped onto the chat. */ + public void appendToInput(String text) { + edt(() -> { + String cur = input.getText(); + input.setText(cur.isEmpty() || cur.endsWith(" ") ? cur + text : cur + " " + text); + input.requestFocusInWindow(); + }); + } + + /** Names the server tab after the server we are on; blank falls back to "Server". */ + public void setServerName(String name) { + edt(() -> serverTab.setTitle(name == null || name.isBlank() ? NO_SERVER : name)); + } + + /** Names the channel tab after the channel we are in; blank falls back to "Channel". */ + public void setChannelName(String name) { + edt(() -> channelTab.setTitle(name == null || name.isBlank() ? NO_CHANNEL : name)); + } + + public void setInputEnabled(boolean enabled) { + input.setEnabled(enabled); + inputEnabled = enabled; + updateAttach(); + } + + private void updateAttach() { + attach.setEnabled(inputEnabled && sharingAvailable); + attach.setToolTipText(sharingAvailable ? "Share file" : "Sign in to myTeamSpeak to share files"); + } + + /** Takes dropped and pasted files and pictures as files to share, leaving the rest to {@code c}'s own handling. */ + private AttachmentTransferHandler attachmentTransfer(JComponent c) { + return new AttachmentTransferHandler(c.getTransferHandler(), new AttachmentTransferHandler.Sink() { + @Override + public boolean files(List files) { + Tab tab = selectedTab(); + if (attachmentHandler == null || tab == null || tab.target == null) return false; + attachmentHandler.share(tab.target, tab.clientId, files); + return true; + } + + @Override + public boolean image(BufferedImage image) { + Tab tab = selectedTab(); + if (attachmentHandler == null || tab == null || tab.target == null) return false; + attachmentHandler.share(tab.target, tab.clientId, image); + return true; + } + }); + } + + /** Opens (or focuses) the private chat with {@code clientId}. */ + public void openPrivateChat(int clientId, String nickname) { + openPrivateChat(clientId, "", nickname); + } + + /** Opens (or focuses) the private chat with {@code clientId}. */ + public void openPrivateChat(int clientId, String uniqueId, String nickname) { + edt(() -> { + Tab tab = privateTab(clientId, uniqueId, nickname); + tabs.setSelectedComponent(tab.scroll); + input.requestFocusInWindow(); + }); + } + + public void setServerHistory(List htmlEntries) { + edt(() -> serverTab.setHistory(htmlEntries)); + } + + public void setChannelHistory(List htmlEntries) { + edt(() -> channelTab.setHistory(htmlEntries)); + } + + public void setPrivateHistory(int clientId, String nickname, List htmlEntries) { + edt(() -> privateTab(clientId, "", nickname).setHistory(htmlEntries)); + } + + /** Drops every private chat tab, e.g. after disconnecting. */ + public void closePrivateChats() { + edt(() -> { + for (Tab t : privateTabs.values()) tabs.remove(t.scroll); + privateTabs.clear(); + }); + } + + /** Drops every static-content tab (moved-out descriptions), e.g. after disconnecting. */ + public void closeNoteTabs() { + edt(() -> { + for (Tab t : noteTabs.values()) tabs.remove(t.scroll); + noteTabs.clear(); + }); + } + + /** Closes a single static-content tab by its key, if open; does not run its {@code onClose}. */ + public void closeNoteTab(String key) { + edt(() -> { + Tab tab = noteTabs.remove(key); + if (tab != null) tabs.remove(tab.scroll); + }); + } + + /** + * Opens (or replaces the content of, and focuses) a static-content tab, e.g. a + * channel/client description moved out of the info panel. {@code onClose} runs + * when the tab is closed, so the caller can un-hide the description again. + */ + public void openDescriptionTab(String key, Icon icon, String title, String htmlBody, Runnable onClose) { + edt(() -> { + Tab tab = noteTabs.get(key); + if (tab == null) { + tab = new Tab(key, icon, title, onClose); + noteTabs.put(key, tab); + addTab(tab, true); + } + tab.setStaticContent(htmlBody); + tabs.setSelectedComponent(tab.scroll); + }); + } + + private void fireSend() { + String text = input.getText().trim(); + if (text.isEmpty() || sendHandler == null) return; + Tab tab = selectedTab(); + if (tab == null || tab.target == null) return; + sendHandler.send(tab.target, tab.clientId, text); + input.setText(""); + } + + // ---- append helpers (safe from any thread) ---- + + /** System notices always land in the server tab. */ + public void appendSystem(String text) { + edt(() -> serverTab.append(ChatHtml.system(text))); + } + + /** + * Server-side events (client joins/leaves/moves, group changes, channel edits, …). + * These lines name clients and channels with TeamSpeak's own links, which stay + * clickable here — everything else in them is literal text. + */ + public void appendServerLog(String text) { + edt(() -> serverTab.append(ChatHtml.serverLog(text))); + } + + public void appendServerLogHtml(String html) { + edt(() -> serverTab.append(ChatHtml.logEntry(html))); + } + + public void appendServerMessage(int fromId, String from, String text) { + appendServerMessage(fromId, "", from, text); + } + + public void appendServerMessage(int fromId, String uniqueId, String from, String text) { + edt(() -> serverTab.appendMessage(fromId, uniqueId, from, text)); + } + + public void appendChannelMessage(int fromId, String from, String text) { + appendChannelMessage(fromId, "", from, text); + } + + public void appendChannelMessage(int fromId, String uniqueId, String from, String text) { + edt(() -> channelTab.appendMessage(fromId, uniqueId, from, text)); + } + + /** Appends to the private chat with {@code peerId}, creating the tab if needed. */ + public void appendPrivateMessage(int peerId, String peerName, int fromId, String from, String text) { + appendPrivateMessage(peerId, "", peerName, fromId, "", from, text); + } + + /** Appends to the private chat with {@code peerId}, creating the tab if needed. */ + public void appendPrivateMessage(int peerId, String peerUniqueId, String peerName, + int fromId, String fromUniqueId, String from, String text) { + edt(() -> privateTab(peerId, peerUniqueId, peerName).appendMessage(fromId, fromUniqueId, from, text)); + } + + private Tab privateTab(int clientId, String nickname) { + return privateTab(clientId, "", nickname); + } + + private Tab privateTab(int clientId, String uniqueId, String nickname) { + Tab tab = privateTabs.get(clientId); + if (tab == null) { + tab = new Tab(Target.PRIVATE, clientId, uniqueId, nickname, Icons.privateChat()); + privateTabs.put(clientId, tab); + addTab(tab, true); + } else { + tab.setClientUniqueId(uniqueId); + } + return tab; + } + + private void addTab(Tab tab, boolean closable) { + tabs.addTab(tab.title, tab.scroll); + zoom.attach(tab.log); + tabs.setTabComponentAt(tabs.indexOfComponent(tab.scroll), tab.header(closable)); + } + + private void closeTab(Tab tab) { + if (tab.noteKey != null) { + noteTabs.remove(tab.noteKey); + if (tab.onClose != null) tab.onClose.run(); + } else { + privateTabs.remove(tab.clientId); + } + tabs.remove(tab.scroll); + } + + /** Drags a tab from one position to another, keeping the current selection on screen. */ + private void moveTab(int from, int to) { + if (from < 0 || to < 0 || from >= tabs.getTabCount() || to >= tabs.getTabCount() || from == to) return; + Component content = tabs.getComponentAt(from); + String title = tabs.getTitleAt(from); + Icon icon = tabs.getIconAt(from); + String tip = tabs.getToolTipTextAt(from); + Component header = tabs.getTabComponentAt(from); + boolean wasSelected = tabs.getSelectedIndex() == from; + tabs.removeTabAt(from); + tabs.insertTab(title, icon, content, tip, to); + tabs.setTabComponentAt(to, header); + if (wasSelected) tabs.setSelectedIndex(to); + } + + private void onWheel(MouseWheelEvent e) { + Component content = tabs.getSelectedComponent(); + if (content != null && content.getBounds().contains(e.getPoint())) return; + int steps = e.getWheelRotation(); + if (steps == 0) return; + int target = Math.max(0, Math.min(tabs.getTabCount() - 1, tabs.getSelectedIndex() + steps)); + if (target != tabs.getSelectedIndex()) tabs.setSelectedIndex(target); + e.consume(); + } + + private Tab selectedTab() { + Component c = tabs.getSelectedComponent(); + if (c == serverTab.scroll) return serverTab; + if (c == channelTab.scroll) return channelTab; + for (Tab t : privateTabs.values()) { + if (t.scroll == c) return t; + } + for (Tab t : noteTabs.values()) { + if (t.scroll == c) return t; + } + return null; + } + + private List allTabs() { + List all = new ArrayList<>(); + all.add(serverTab); + all.add(channelTab); + all.addAll(privateTabs.values()); + all.addAll(noteTabs.values()); + return all; + } + + private String room() { + String id = room.get(); + return id == null ? "" : id; + } + + private void edt(Runnable r) { + if (SwingUtilities.isEventDispatchThread()) r.run(); + else SwingUtilities.invokeLater(r); + } + + /** One conversation: its HTML log, its scroll pane and the tab-strip header. */ + private final class Tab { + + final Target target; + final int clientId; + private String clientUniqueId; + private String title; + final JEditorPane log = HtmlStyles.pane("font-family:sans-serif; font-size:11px; margin:" + + HtmlStyles.px(4) + " " + HtmlStyles.px(6) + ";"); + final JScrollPane scroll; + /** Set for a static-content tab (e.g. a moved-out description); null for a conversation. */ + final String noteKey; + final Runnable onClose; + private final Icon icon; + private JLabel titleLabel; + /** Everything this conversation has shown, whether or not a search currently hides it. */ + private final List entries = new ArrayList<>(); + /** Only messages matching this are on screen; {@code null} shows all. */ + private TextQuery filter; + /** The shared pictures the entries show, and how they stood when last drawn. */ + private final List pictureUrls = new ArrayList<>(); + private String pictureState = ""; + private int renderedPictureWidth; + + Tab(Target target, int clientId, String title, Icon icon) { + this(target, clientId, "", title, icon, null, null); + } + + Tab(Target target, int clientId, String clientUniqueId, String title, Icon icon) { + this(target, clientId, clientUniqueId, title, icon, null, null); + } + + /** A static-content tab: no send target, closing it runs {@code onClose}. */ + Tab(String noteKey, Icon icon, String title, Runnable onClose) { + this(null, 0, "", title, icon, noteKey, onClose); + } + + private Tab(Target target, int clientId, String clientUniqueId, String title, + Icon icon, String noteKey, Runnable onClose) { + this.target = target; + this.clientId = clientId; + this.clientUniqueId = clientUniqueId == null ? "" : clientUniqueId; + this.title = title; + this.icon = icon; + this.noteKey = noteKey; + this.onClose = onClose; + + log.setText("

    "); + log.addHyperlinkListener(e -> { + if (e.getEventType() != HyperlinkEvent.EventType.ACTIVATED) return; + onLink(e.getDescription(), isPicture(e.getSourceElement())); + }); + log.setTransferHandler(attachmentTransfer(log)); + + scroll = new JScrollPane(log); + HtmlStyles.fillViewport(log); + scroll.setBorder(BorderFactory.createEmptyBorder()); + scroll.getViewport().addComponentListener(new ComponentAdapter() { + @Override + public void componentResized(ComponentEvent e) { + if (!pictureUrls.isEmpty() && pictureWidth() != renderedPictureWidth) keepingScroll(); + } + }); + } + + private static boolean isPicture(Element element) { + return element != null && element.getAttributes().getAttribute(StyleConstants.NameAttribute) == HTML.Tag.IMG; + } + + void setClientUniqueId(String uniqueId) { + if (uniqueId != null && !uniqueId.isBlank()) clientUniqueId = uniqueId; + } + + private void onLink(String href, boolean picture) { + if (href == null) return; + if (ChatAttachment.isHref(href)) { + if (attachmentHandler != null) attachmentHandler.open(href, picture); + return; + } + if (TsLink.isOfflineMessages(href)) { + if (linkHandler != null) linkHandler.onOfflineMessagesLink(); + return; + } + TsLink.Ref ref = TsLink.parse(href); + if (ref == null) { + Links.open(href, ChatPanel.this); + return; + } + if (linkHandler == null) return; + Point p = log.getMousePosition(); + if (p == null) p = new Point(0, 0); + if (ref.client) linkHandler.onClientLink(ref, log, p.x, p.y); + else linkHandler.onChannelLink(ref, log, p.x, p.y); + } + + Component header(boolean closable) { + // Only the height is pinned: a fixed width would freeze the tab at the width of + // whatever name it was built with, clipping longer ones (and the bold unread font). + JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT, UIScale.scale(2), 0)) { + @Override + public Dimension getPreferredSize() { + Dimension d = super.getPreferredSize(); + return new Dimension(d.width, Math.max(d.height, UIScale.scale(HEADER_HEIGHT))); + } + }; + p.setOpaque(false); + titleLabel = new JLabel(title, icon, JLabel.LEADING); + titleLabel.setFont(Theme.uiFont()); + titleLabel.setIconTextGap(UIScale.scale(3)); + p.add(titleLabel); + dragReorder.attach(p); + dragReorder.attach(titleLabel); + if (closable) { + JLabel close = new JLabel("×"); + close.setFont(Theme.uiBold()); + close.setForeground(Theme.chatSystem()); + close.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + close.setToolTipText("Close chat"); + close.addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + closeTab(Tab.this); + } + }); + p.add(close); + } + return p; + } + + /** Renames the tab in place — the server and channel tabs follow where we are. */ + void setTitle(String title) { + if (title.equals(this.title)) return; + this.title = title; + int index = tabs.indexOfComponent(scroll); + if (index >= 0) tabs.setTitleAt(index, title); + if (titleLabel == null) return; + titleLabel.setText(title); + // The strip lays its tabs out itself; it has to re-measure this one. + tabs.revalidate(); + tabs.repaint(); + } + + void setUnread(boolean unread) { + if (titleLabel == null) return; + titleLabel.setFont(unread ? Theme.uiBold() : Theme.uiFont()); + titleLabel.setForeground(unread ? Theme.accent() : null); + } + + void appendMessage(int fromId, String fromUniqueId, String from, String text) { + append(ChatHtml.message(fromId, + fromUniqueId == null || fromUniqueId.isBlank() ? clientUniqueId : fromUniqueId, from, text, + room())); + } + + void setHistory(List htmlEntries) { + entries.clear(); + pictureUrls.clear(); + if (htmlEntries != null) { + String room = room(); + for (String entry : htmlEntries) add(ChatHtml.logEntry(entry, room)); + } + render(); + } + + /** Replaces the whole log with fixed content; used by static-content tabs. */ + void setStaticContent(String html) { + entries.clear(); + pictureUrls.clear(); + entries.add(html); + render(); + } + + private void add(String entry) { + entries.add(entry); + // Static content comes with its pictures already in place. + if (noteKey == null && DescriptionPictures.hasPictures(entry)) { + pictureUrls.addAll(DescriptionPictures.urls(entry)); + } + } + + /** The entry as drawn: its shared pictures as they stand now. */ + private String drawn(String entry) { + if (noteKey != null || !DescriptionPictures.hasPictures(entry)) return entry; + return pictures.html(entry, renderedPictureWidth, UIScale.scale(PICTURE_HEIGHT)); + } + + /** + * How wide a shared picture may be: the log's width inside its margins, in steps so that + * dragging a divider does not rebuild the log on every pixel. + */ + private int pictureWidth() { + int step = UIScale.scale(PICTURE_WIDTH_STEP); + int width = scroll.getViewport().getWidth() - UIScale.scale(24); + return Math.min(UIScale.scale(PICTURE_WIDTH), Math.max(step, width / step * step)); + } + + /** A picture came or failed: redrawn if it is one of this log's. */ + void picturesChanged() { + if (!pictureUrls.isEmpty() && !pictures.state(pictureUrls).equals(pictureState)) keepingScroll(); + } + + /** Redraws the log, staying where the reader is unless that is at the end. */ + private void keepingScroll() { + JScrollBar bar = scroll.getVerticalScrollBar(); + boolean atEnd = bar.getValue() + bar.getVisibleAmount() >= bar.getMaximum() - UIScale.scale(8); + Point at = scroll.getViewport().getViewPosition(); + render(); + if (!atEnd || search.isOpen()) SwingUtilities.invokeLater(() -> scroll.getViewport().setViewPosition(at)); + } + + void showMatching(TextQuery filter) { + if (Objects.equals(this.filter, filter)) return; + this.filter = filter; + render(); + } + + private boolean shows(String entry) { + return filter == null || filter.matches(HtmlText.plain(entry)); + } + + private void render() { + // Read before drawing, so a picture coming meanwhile still counts as a change. + pictureState = pictures.state(pictureUrls); + renderedPictureWidth = pictureWidth(); + StringBuilder html = new StringBuilder(); + for (String entry : entries) { + if (shows(entry)) html.append(drawn(entry)); + } + log.setText("
    " + html + "
    "); + log.setCaretPosition(noteKey != null ? 0 : log.getDocument().getLength()); + } + + void append(String entry) { + boolean stale = !pictures.state(pictureUrls).equals(pictureState); + add(entry); + if (stale) { + // A picture already shown changed and is about to be redrawn; this joins it. + render(); + } else if (shows(entry)) { + pictureState = pictures.state(pictureUrls); + if (renderedPictureWidth == 0) renderedPictureWidth = pictureWidth(); + try { + HTMLDocument doc = (HTMLDocument) log.getDocument(); + doc.insertBeforeEnd(doc.getElement("chatlog"), drawn(entry)); + // Following new lines would pull the view away from the match being read. + if (!search.isOpen()) log.setCaretPosition(doc.getLength()); + } catch (BadLocationException | IOException ignored) { + } + } + if (tabs.getSelectedComponent() != scroll) setUnread(true); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatSearch.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatSearch.java new file mode 100644 index 0000000..4e49371 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatSearch.java @@ -0,0 +1,270 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.text.TextQuery; + +import javax.swing.JEditorPane; +import javax.swing.JToggleButton; +import javax.swing.JViewport; +import javax.swing.SwingUtilities; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultHighlighter; +import javax.swing.text.Document; +import javax.swing.text.Highlighter; +import java.awt.Color; +import java.awt.Point; +import java.awt.Rectangle; +import java.beans.PropertyChangeListener; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; + +/** + * Find in a log pane — the chat's selected conversation, or the server log: highlights the + * query's matches and steps through them, newest first. Optionally shows only the + * messages that match. + */ +final class ChatSearch implements FindBar.Listener { + + /** The conversation being searched: whichever chat tab is selected. */ + interface Host { + /** The selected tab's log, or {@code null} when there is none. */ + JEditorPane selectedLog(); + + /** Shows only the selected tab's messages matching {@code filter}; {@code null} shows all again. */ + void showMatching(TextQuery filter); + } + + /** More highlights than this slow painting down, and nobody steps through them one by one. */ + private static final int MAX_HIGHLIGHTS = 5000; + + private final Host host; + private final FindBar bar = new FindBar(this); + private final JToggleButton onlyMatching; + + private final Highlighter.HighlightPainter matchPainter = new ThemedPainter(false); + private final Highlighter.HighlightPainter currentPainter = new ThemedPainter(true); + private final List highlightTags = new ArrayList<>(); + /** Start and end offsets of each match in the log document, oldest first. */ + private final List matches = new ArrayList<>(); + private int current = -1; + /** The next re-highlight follows a new query, so it starts again from the newest match. */ + private boolean freshQuery; + private boolean rehighlightQueued; + + private JEditorPane log; + private final DocumentListener docListener = new DocumentListener() { + @Override + public void insertUpdate(DocumentEvent e) { + queueRehighlight(); + } + + @Override + public void removeUpdate(DocumentEvent e) { + queueRehighlight(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + } + }; + /** A theme change re-installs the log's document. */ + private final PropertyChangeListener docSwap = e -> { + if (e.getOldValue() instanceof Document old) old.removeDocumentListener(docListener); + if (e.getNewValue() instanceof Document now) now.addDocumentListener(docListener); + queueRehighlight(); + }; + + ChatSearch(Host host) { + this(host, "Show only matching messages"); + } + + ChatSearch(Host host, String filterTooltip) { + this.host = host; + onlyMatching = bar.addFilterToggle(filterTooltip); + } + + FindBar bar() { + return bar; + } + + boolean isOpen() { + return bar.isOpen(); + } + + void open() { + retarget(); + bar.open(); + } + + /** The selected tab changed: carry the search over to it. */ + void retarget() { + JEditorPane now = host.selectedLog(); + if (now != log) { + detach(); + log = now; + if (log != null) { + log.getDocument().addDocumentListener(docListener); + log.addPropertyChangeListener("document", docSwap); + } + } + if (bar.isOpen()) queryChanged(bar.query()); + } + + @Override + public void queryChanged(TextQuery query) { + freshQuery = true; + boolean usable = !query.isEmpty() && !query.isInvalid(); + host.showMatching(onlyMatching.isSelected() && usable ? query : null); + rehighlight(); + } + + @Override + public void next() { + step(1); + } + + @Override + public void previous() { + step(-1); + } + + @Override + public void closed() { + clearHighlights(); + matches.clear(); + host.showMatching(null); + if (log != null) { + log.setCaretPosition(log.getDocument().getLength()); + log.requestFocusInWindow(); + } + } + + private void step(int delta) { + if (matches.isEmpty()) return; + current = Math.floorMod(current + delta, matches.size()); + paintHighlights(); + scrollToCurrent(); + updateStatus(); + } + + private void queueRehighlight() { + if (!bar.isOpen() || rehighlightQueued) return; + rehighlightQueued = true; + SwingUtilities.invokeLater(() -> { + rehighlightQueued = false; + if (bar.isOpen()) rehighlight(); + }); + } + + /** Finds the matches in the log as it now reads, keeping the current one where it can. */ + private void rehighlight() { + int keepStart = !freshQuery && current >= 0 && current < matches.size() ? matches.get(current)[0] : -1; + matches.clear(); + current = -1; + TextQuery query = bar.query(); + Matcher m = null; + if (log != null) { + try { + Document doc = log.getDocument(); + m = query.matcher(doc.getText(0, doc.getLength())); + } catch (BadLocationException ignored) { + } + } + if (m != null) { + while (m.find()) { + if (m.end() > m.start()) matches.add(new int[]{m.start(), m.end()}); + } + } + if (matches.size() > MAX_HIGHLIGHTS) matches.subList(0, matches.size() - MAX_HIGHLIGHTS).clear(); + + if (!matches.isEmpty()) { + current = matches.size() - 1; + if (keepStart >= 0) { + for (int i = 0; i < matches.size(); i++) { + if (matches.get(i)[0] >= keepStart) { + current = i; + break; + } + } + } + } + paintHighlights(); + if (freshQuery) scrollToCurrent(); + freshQuery = false; + updateStatus(); + } + + private void updateStatus() { + TextQuery query = bar.query(); + if (query.isInvalid()) return; + bar.setNavigable(matches.size() > 1); + if (query.isEmpty()) bar.clearCount(); + else bar.setCount(current + 1, matches.size(), matches.size() == MAX_HIGHLIGHTS); + } + + private void paintHighlights() { + clearHighlights(); + if (log == null) return; + Highlighter h = log.getHighlighter(); + for (int i = 0; i < matches.size(); i++) { + int[] r = matches.get(i); + try { + highlightTags.add(h.addHighlight(r[0], r[1], i == current ? currentPainter : matchPainter)); + } catch (BadLocationException ignored) { + } + } + } + + private void clearHighlights() { + if (log != null) { + Highlighter h = log.getHighlighter(); + for (Object tag : highlightTags) h.removeHighlight(tag); + } + highlightTags.clear(); + } + + /** Brings the current match to the middle of the view, once the log has been laid out. */ + private void scrollToCurrent() { + if (current < 0 || log == null) return; + int start = matches.get(current)[0]; + JEditorPane pane = log; + SwingUtilities.invokeLater(() -> { + if (pane != log || !(pane.getParent() instanceof JViewport viewport)) return; + try { + Rectangle r = pane.modelToView2D(start).getBounds(); + Rectangle view = viewport.getViewRect(); + if (view.contains(r)) return; + int maxY = Math.max(0, pane.getHeight() - view.height); + int y = Math.max(0, Math.min(maxY, r.y - (view.height - r.height) / 2)); + viewport.setViewPosition(new Point(view.x, y)); + } catch (BadLocationException ignored) { + } + }); + } + + private void detach() { + clearHighlights(); + matches.clear(); + current = -1; + if (log == null) return; + log.getDocument().removeDocumentListener(docListener); + log.removePropertyChangeListener("document", docSwap); + } + + /** Reads the theme when painting, so highlights follow a light/dark switch. */ + private static final class ThemedPainter extends DefaultHighlighter.DefaultHighlightPainter { + private final boolean current; + + ThemedPainter(boolean current) { + super(null); + this.current = current; + } + + @Override + public Color getColor() { + return current ? Theme.searchCurrent() : Theme.searchMatch(); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ClientMenu.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ClientMenu.java new file mode 100644 index 0000000..f455c77 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ClientMenu.java @@ -0,0 +1,161 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.contacts.ContactType; +import eu.lixko.ts3j.client.net.ChannelNode; +import eu.lixko.ts3j.client.net.ClientEntry; +import eu.lixko.ts3j.client.net.Group; +import eu.lixko.ts3j.client.net.GroupChoice; +import eu.lixko.ts3j.client.net.ServerModel; + +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JMenu; +import javax.swing.JMenuItem; +import javax.swing.JPopupMenu; +import java.util.List; + +/** + * The context menu for a client, shared by the server tree and the clickable + * names in the chat log. + */ +final class ClientMenu { + + private ClientMenu() { + } + + /** + * @param fromTree whether this menu was opened from the server tree itself, as + * opposed to a client link elsewhere (chat log, etc.) — "Find + * Client in Channel Tree" is redundant in the former case. + */ + static JPopupMenu build(ClientEntry client, boolean self, boolean fromTree, ServerModel model, + GroupIcons groupIcons, ServerTreePanel.Actions actions) { + JPopupMenu menu = new JPopupMenu(); + if (!self) { + JMenuItem pm = new JMenuItem("Open text chat", Icons.of("PLAYER_CHAT")); + pm.addActionListener(a -> actions.openPrivateChat(client)); + menu.add(pm); + JMenuItem poke = new JMenuItem("Poke", Icons.of("POKE")); + poke.addActionListener(a -> actions.pokeClient(client)); + menu.add(poke); + JMenuItem complain = new JMenuItem("Make a Complaint", Icons.of("SEND_COMPLAINT")); + complain.addActionListener(a -> actions.complainAboutClient(client)); + menu.add(complain); + menu.addSeparator(); + JMenuItem kickChannel = new JMenuItem("Kick Client from Channel", Icons.of("KICK_FROM_CHANNEL")); + kickChannel.addActionListener(a -> actions.kickClientFromChannel(client)); + menu.add(kickChannel); + JMenuItem kickServer = new JMenuItem("Kick Client from Server", Icons.of("KICK_FROM_SERVER")); + kickServer.addActionListener(a -> actions.kickClientFromServer(client)); + menu.add(kickServer); + JMenuItem ban = new JMenuItem("Ban Client", Icons.of("BAN_CLIENT")); + ban.addActionListener(a -> actions.banClient(client)); + menu.add(ban); + boolean muted = actions.isClientLocallyMuted(client.id); + JMenuItem mute = new JMenuItem(muted ? "Unmute client" : "Mute client", + Icons.of(muted ? "PLAYER_ON" : "INPUT_MUTED")); + mute.addActionListener(a -> actions.toggleClientMute(client)); + menu.add(mute); + JMenuItem volume = new JMenuItem("Change Volume…", Icons.of("VOLUME")); + volume.addActionListener(a -> actions.changeClientVolume(client)); + menu.add(volume); + menu.addSeparator(); + addContactItems(menu, client, actions); + } else { + JMenuItem me = new JMenuItem("This is you", Icons.of("PLAYER_OFF")); + me.setEnabled(false); + menu.add(me); + } + menu.addSeparator(); + menu.add(buildServerGroupMenu(client, model, groupIcons, actions)); + menu.add(buildChannelGroupMenu(client, model, groupIcons, actions)); + menu.addSeparator(); + if (!fromTree) { + JMenuItem findInTree = new JMenuItem("Find Client in Channel Tree", Icons.of("CHANNEL_SWITCH")); + findInTree.setEnabled(model.isChannelVisible(client.channelId)); + findInTree.addActionListener(a -> actions.findClientInTree(client)); + menu.add(findInTree); + } + JMenuItem description = new JMenuItem("Change Description", Icons.of("EDIT")); + description.addActionListener(a -> actions.changeClientDescription(client)); + menu.add(description); + if (!self && !client.avatarFlag.isEmpty() && actions.canDeleteOtherAvatars()) { + JMenuItem avatar = new JMenuItem("Delete Avatar", Icons.of("DELETE_AVATAR_OTHER")); + avatar.addActionListener(a -> actions.deleteClientAvatar(client)); + menu.add(avatar); + } + JMenuItem info = new JMenuItem("Connection Info", Icons.of("INFO")); + info.addActionListener(a -> actions.showConnectionInfo(client)); + menu.add(info); + if (!self) { + menu.addSeparator(); + JMenuItem joinChannel = new JMenuItem("Join Channel of Client", Icons.of("CHANNEL_SWITCH")); + joinChannel.setEnabled(model.canJoinChannel(client.channelId)); + joinChannel.addActionListener(a -> actions.joinChannel(client.channelId)); + menu.add(joinChannel); + JMenuItem moveHere = new JMenuItem("Move Client to own Channel", Icons.of("MOVE_CLIENT_TO_OWN_CHANNEL")); + moveHere.addActionListener(a -> actions.moveClientToOwnChannel(client)); + menu.add(moveHere); + } + return menu; + } + + /** + * The contact entries, as TeamSpeak offers them: a client not on the list can be + * added as a friend or blocked; one on it can be edited or removed. + */ + private static void addContactItems(JPopupMenu menu, ClientEntry client, ServerTreePanel.Actions actions) { + ContactType type = actions.contactTypeOf(client); + if (type == null) { + JMenuItem friend = new JMenuItem("Add as Friend", Icons.of("ADD_FRIEND")); + friend.addActionListener(a -> actions.addContact(client, ContactType.FRIEND)); + menu.add(friend); + JMenuItem blocked = new JMenuItem("Add as Blocked", Icons.of("ADD_FOE")); + blocked.addActionListener(a -> actions.addContact(client, ContactType.BLOCKED)); + menu.add(blocked); + return; + } + JMenuItem edit = new JMenuItem("Edit in Contacts", Icons.of("EDIT_FRIEND_FOE_STATUS")); + edit.addActionListener(a -> actions.editContact(client)); + menu.add(edit); + JMenuItem remove = new JMenuItem("Remove from Contacts", + Icons.of(type == ContactType.BLOCKED ? "REMOVE_FOE" : "REMOVE_FRIEND")); + remove.addActionListener(a -> actions.removeContact(client)); + menu.add(remove); + } + + private static JMenu buildServerGroupMenu(ClientEntry client, ServerModel model, GroupIcons groupIcons, + ServerTreePanel.Actions actions) { + JMenu menu = new JMenu("Set Server Groups"); + menu.setIcon(Icons.of("PERMISSIONS_SERVER_GROUPS")); + JMenuItem dialog = new JMenuItem("Server Groups Dialog..."); + dialog.addActionListener(a -> actions.showServerGroupsDialog(client)); + menu.add(dialog); + menu.addSeparator(); + + for (GroupChoice choice : model.serverGroupChoices(client)) { + if (!choice.allowed()) continue; + Group g = choice.group(); + JCheckBoxMenuItem item = new JCheckBoxMenuItem(g.name, groupIcons.iconOf(g)); + item.setSelected(choice.assigned()); + item.addActionListener(a -> actions.setClientServerGroup(client, g, !choice.assigned())); + menu.add(item); + } + return menu; + } + + private static JMenu buildChannelGroupMenu(ClientEntry client, ServerModel model, GroupIcons groupIcons, + ServerTreePanel.Actions actions) { + JMenu menu = new JMenu("Set Channel Group"); + menu.setIcon(Icons.of("PERMISSIONS_CHANNEL_GROUPS")); + int defaultGroupId = model.defaultChannelGroupId(); + for (GroupChoice choice : model.channelGroupChoices(client)) { + Group g = choice.group(); + if (g.id == defaultGroupId || !choice.allowed()) continue; + JCheckBoxMenuItem item = new JCheckBoxMenuItem(g.name, groupIcons.iconOf(g)); + item.setSelected(choice.assigned()); + item.addActionListener(a -> actions.setClientChannelGroup(client, g)); + menu.add(item); + } + return menu; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ClientVersionPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ClientVersionPanel.java new file mode 100644 index 0000000..d84f74f --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ClientVersionPanel.java @@ -0,0 +1,187 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.config.ClientVersion; +import eu.lixko.ts3j.client.config.Settings; + +import javax.swing.DefaultListCellRenderer; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JTextField; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; + +/** + * The Application page's section for the version and operating system reported to the server, which + * is what other clients see next to the nickname ("3.6.2 on Windows"). + * + *

    Servers verify TeamSpeak's signature over the version and platform and refuse + * the connection ("client is modified") when it does not match, so the page is + * built around the signed versions in {@link ClientVersion#PRESETS}. The fields + * behind them can still be edited by hand for a version whose signature is known + * from somewhere else. Changes take effect on the next connect. + */ +final class ClientVersionPanel extends JPanel { + + /** Combo entry that leaves the three fields to the user. */ + private static final String CUSTOM = "Custom…"; + + private final Settings settings; + + private final JCheckBox enabled = new JCheckBox("Report a custom version and operating system"); + private final JComboBox presetCombo = new JComboBox<>(); + private final JTextField versionField = new JTextField(24); + private final JComboBox platformCombo = new JComboBox<>(); + private final JTextField signField = new JTextField(24); + + /** Set while a preset is being copied into the fields, so that does not count as an edit. */ + private boolean filling; + + ClientVersionPanel(Settings settings) { + super(new BorderLayout(0, UIScale.scale(8))); + this.settings = settings; + + add(buildForm(), BorderLayout.NORTH); + + load(); + enabled.addActionListener(e -> updateEnabled()); + updateEnabled(); + } + + /** Copies the edited version into the settings; the caller saves them. */ + void apply() { + settings.customVersion = enabled.isSelected(); + settings.clientVersion = versionField.getText().trim(); + settings.clientPlatform = String.valueOf(platformCombo.getEditor().getItem()).trim(); + settings.clientVersionSign = signField.getText().trim(); + } + + private JComponent buildForm() { + JPanel p = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + c.insets = UIScale.scale(new Insets(2, 2, 2, 2)); + c.anchor = GridBagConstraints.WEST; + c.fill = GridBagConstraints.HORIZONTAL; + + presetCombo.addItem(CUSTOM); + for (ClientVersion preset : ClientVersion.PRESETS) presetCombo.addItem(preset); + presetCombo.setRenderer(new DefaultListCellRenderer() { + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, + boolean selected, boolean focus) { + super.getListCellRendererComponent(list, value, index, selected, focus); + setText(value instanceof ClientVersion v ? v.label() : String.valueOf(value)); + return this; + } + }); + presetCombo.setToolTipText("Versions with a signature TeamSpeak issued for them"); + presetCombo.addActionListener(e -> onPresetSelected()); + + platformCombo.setEditable(true); + for (String platform : ClientVersion.PLATFORMS) platformCombo.addItem(platform); + + versionField.setToolTipText("Version string, e.g. 3.6.2 [Build: 1695203293]"); + platformCombo.setToolTipText("Operating system shown to other clients"); + signField.setToolTipText("TeamSpeak's signature for this version and platform"); + versionField.getDocument().addDocumentListener(new EditListener()); + signField.getDocument().addDocumentListener(new EditListener()); + platformCombo.addActionListener(e -> onFieldEdited()); + + int row = 0; + c.gridx = 0; + c.gridy = row++; + c.gridwidth = 2; + p.add(enabled, c); + c.gridwidth = 1; + + addRow(p, c, row++, new JLabel("Version:"), presetCombo); + addRow(p, c, row++, new JLabel("Version string:"), versionField); + addRow(p, c, row++, new JLabel("Operating system:"), platformCombo); + addRow(p, c, row++, new JLabel("Signature:"), signField); + + c.gridx = 0; + c.gridy = row; + c.gridwidth = 2; + JLabel note = new JLabel("Servers refuse made-up or outdated versions (\"client is modified\")." + + "
    Takes effect on the next connect."); + note.setEnabled(false); + p.add(note, c); + return p; + } + + private void load() { + enabled.setSelected(settings.customVersion); + ClientVersion preset = ClientVersion.match( + settings.clientVersion, settings.clientPlatform, settings.clientVersionSign); + fill(preset != null ? preset + : new ClientVersion("", settings.clientVersion, settings.clientPlatform, settings.clientVersionSign)); + presetCombo.setSelectedItem(preset != null ? preset : CUSTOM); + } + + private void onPresetSelected() { + if (presetCombo.getSelectedItem() instanceof ClientVersion preset) fill(preset); + } + + /** A hand-edited field no longer describes the selected preset. */ + private void onFieldEdited() { + if (filling) return; + ClientVersion preset = ClientVersion.match(versionField.getText().trim(), + String.valueOf(platformCombo.getEditor().getItem()).trim(), signField.getText().trim()); + presetCombo.setSelectedItem(preset != null ? preset : CUSTOM); + } + + private void fill(ClientVersion version) { + filling = true; + try { + versionField.setText(version.version()); + platformCombo.setSelectedItem(version.platform()); + platformCombo.getEditor().setItem(version.platform()); + signField.setText(version.sign()); + } finally { + filling = false; + } + } + + private void updateEnabled() { + boolean on = enabled.isSelected(); + presetCombo.setEnabled(on); + versionField.setEnabled(on); + platformCombo.setEnabled(on); + signField.setEnabled(on); + } + + /** Notices any typing in the version or signature field. */ + private final class EditListener implements javax.swing.event.DocumentListener { + @Override + public void insertUpdate(javax.swing.event.DocumentEvent e) { + onFieldEdited(); + } + + @Override + public void removeUpdate(javax.swing.event.DocumentEvent e) { + onFieldEdited(); + } + + @Override + public void changedUpdate(javax.swing.event.DocumentEvent e) { + onFieldEdited(); + } + } + + private static void addRow(JPanel p, GridBagConstraints c, int row, JLabel label, Component field) { + c.gridx = 0; + c.gridy = row; + c.weightx = 0; + p.add(label, c); + c.gridx = 1; + c.weightx = 1; + p.add(field, c); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ClientVolumeDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ClientVolumeDialog.java new file mode 100644 index 0000000..3b6fec7 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ClientVolumeDialog.java @@ -0,0 +1,80 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.net.ClientEntry; +import eu.lixko.ts3j.client.net.TeamspeakConnection; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JSlider; +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Frame; + +/** + * TeamSpeak's "Change Volume" for one client: a gain in decibels on top of the + * master volume, applied as the slider moves. It is remembered in the client's + * contact entry, when it has one; otherwise it lasts for the session. + */ +final class ClientVolumeDialog extends JDialog { + + private static final int RANGE_DB = 40; + + private final TeamspeakConnection conn; + private final ClientEntry client; + private final JSlider slider = new JSlider(-RANGE_DB, RANGE_DB, 0); + private final JLabel value = new JLabel(); + + ClientVolumeDialog(Frame owner, TeamspeakConnection conn, ClientEntry client) { + super(owner, "Change Volume: " + conn.displayName(client), false); + this.conn = conn; + this.client = client; + + slider.setValue((int) Math.round(conn.getClientVolumeModifier(client))); + slider.setMajorTickSpacing(20); + slider.setMinorTickSpacing(5); + slider.setPaintTicks(true); + slider.setPaintLabels(true); + slider.addChangeListener(e -> onChanged()); + FormPanel.limitWidth(value, 60); + + JPanel content = new JPanel(new BorderLayout(UIScale.scale(8), UIScale.scale(8))); + content.setBorder(new ScaledEmptyBorder(12, 12, 8, 12)); + content.add(new JLabel("Volume Modifier"), BorderLayout.NORTH); + content.add(FormPanel.sliderWithLabel(slider, value), BorderLayout.CENTER); + JLabel hint = new JLabel("Values greater than +6 dB will cause clipping " + + "and distortion that will negatively affect your audio quality. It is advised to choose " + + "lower values."); + hint.setForeground(Theme.chatSystem()); + content.add(hint, BorderLayout.SOUTH); + + JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT)); + JButton reset = new JButton("Reset"); + reset.addActionListener(e -> slider.setValue(0)); + JButton close = new JButton("Close"); + close.addActionListener(e -> dispose()); + buttons.add(reset); + buttons.add(close); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(content, BorderLayout.CENTER); + getContentPane().add(buttons, BorderLayout.SOUTH); + + onChanged(); + Dialogs.closeOnEscape(this); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + pack(); + setMinimumSize(new Dimension(UIScale.scale(360), getHeight())); + setLocationRelativeTo(owner); + } + + private void onChanged() { + int db = slider.getValue(); + value.setText((db > 0 ? "+" : "") + db + " dB"); + if (!slider.getValueIsAdjusting()) conn.setClientVolumeModifier(client, db); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ComplaintsDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ComplaintsDialog.java new file mode 100644 index 0000000..9eb4904 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ComplaintsDialog.java @@ -0,0 +1,511 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.net.ClientEntry; +import eu.lixko.ts3j.client.net.Complaint; +import eu.lixko.ts3j.client.net.ServerModel; +import eu.lixko.ts3j.client.net.TeamspeakConnection; + +import javax.swing.AbstractAction; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.KeyStroke; +import javax.swing.ListSelectionModel; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.event.PopupMenuEvent; +import javax.swing.event.PopupMenuListener; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.DefaultTableCellRenderer; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.Point; +import java.awt.event.ActionEvent; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; + +/** + * The server's complaints, as the official client's Tools > Complaints List window: one + * collapsible row per client complained about, with each complaint's date, author and + * reason beneath it. + * + *

    One per server tab and modeless, like the ban list; the tab closes it when the + * connection goes away. + */ +final class ComplaintsDialog extends JDialog { + + private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + private enum Column { + TARGET("Target Nickname", 200), + FROM("From Nickname", 160), + REASON("Reason", 280); + + final String title; + final int width; + + Column(String title, int width) { + this.title = title; + this.width = width; + } + } + + /** A client complained about, with the complaints against them. */ + private record Target(int dbId, String name, List complaints) { + } + + /** A row of the table: a target, or one complaint under its expanded target. */ + private record Row(Target target, Complaint complaint) { + boolean isTarget() { + return complaint == null; + } + } + + private final TeamspeakConnection conn; + private final Consumer banClient; + + private final ComplaintTableModel tableModel = new ComplaintTableModel(); + private final JTable table = new JTable(tableModel) { + /** The popup acts on what was clicked, as a tree's would; Swing asks here before showing it. */ + @Override + public Point getPopupLocation(MouseEvent e) { + int row = e == null ? -1 : rowAtPoint(e.getPoint()); + if (row >= 0 && !isRowSelected(row)) setRowSelectionInterval(row, row); + return super.getPopupLocation(e); + } + }; + private final JButton removeButton = new JButton("Remove", Icons.of("DELETE")); + private final JLabel status = new JLabel(" "); + private final JMenuItem removeItem = item("Remove", "DELETE", this::removeSelected); + private final JMenuItem banItem = item("Ban Client", "BAN_CLIENT", this::banSelected); + + private List targets = List.of(); + /** Targets shown expanded, by database id; kept across reloads. */ + private final Set expanded = new HashSet<>(); + private boolean loading; + + /** @param banClient opens the ban dialog for an online client */ + ComplaintsDialog(Frame owner, TeamspeakConnection conn, Consumer banClient) { + super(owner, "Complaints List", false); + this.conn = conn; + this.banClient = banClient; + + JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(6))); + content.setBackground(Theme.windowBg()); + content.setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); + content.add(buildToolbar(), BorderLayout.NORTH); + content.add(buildTable(), BorderLayout.CENTER); + content.add(buildBottom(), BorderLayout.SOUTH); + setContentPane(content); + bindKeys(); + + serverNameChanged(); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + setPreferredSize(UIScale.scale(new Dimension(680, 420))); + pack(); + setLocationRelativeTo(owner); + reload(); + } + + // ---- construction ---- + + private JPanel buildToolbar() { + removeButton.setToolTipText("Remove selected complaints
    (Delete)"); + removeButton.addActionListener(e -> removeSelected()); + + JPanel bar = new JPanel(); + bar.setLayout(new BoxLayout(bar, BoxLayout.X_AXIS)); + bar.setOpaque(false); + bar.add(removeButton); + bar.add(Box.createHorizontalGlue()); + return bar; + } + + private JScrollPane buildTable() { + table.setFont(Theme.uiFont()); + table.setRowHeight(UIScale.scale(20)); + table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); + table.setFillsViewportHeight(true); + table.setShowGrid(false); + table.getTableHeader().setReorderingAllowed(false); + table.getSelectionModel().addListSelectionListener(e -> updateButtons()); + table.setComponentPopupMenu(tablePopup()); + table.addMouseListener(new ToggleOnClick()); + ComplaintCellRenderer renderer = new ComplaintCellRenderer(); + for (Column c : Column.values()) { + table.getColumnModel().getColumn(c.ordinal()).setPreferredWidth(UIScale.scale(c.width)); + table.getColumnModel().getColumn(c.ordinal()).setCellRenderer(renderer); + } + + JScrollPane scroll = new JScrollPane(table); + scroll.getViewport().setBackground(Theme.treeBg()); + return scroll; + } + + private JPanel buildBottom() { + JButton reload = new JButton("Reload", Icons.of("REFRESH")); + reload.setToolTipText("Reload complaints
    (F5)"); + reload.addActionListener(e -> reload()); + JButton close = new JButton("Close"); + close.addActionListener(e -> dispose()); + + JPanel row = new JPanel(new BorderLayout()); + row.setOpaque(false); + row.add(reload, BorderLayout.WEST); + row.add(close, BorderLayout.EAST); + + JPanel bottom = new JPanel(new BorderLayout(0, UIScale.scale(8))); + bottom.setOpaque(false); + bottom.add(status, BorderLayout.NORTH); + bottom.add(row, BorderLayout.SOUTH); + status.setForeground(Theme.chatEvent()); + return bottom; + } + + private JPopupMenu tablePopup() { + JPopupMenu menu = new JPopupMenu(); + menu.add(item("Reload", "REFRESH", this::reload)); + menu.addSeparator(); + menu.add(removeItem); + menu.add(banItem); + menu.addPopupMenuListener(new PopupMenuListener() { + @Override + public void popupMenuWillBecomeVisible(PopupMenuEvent e) { + removeItem.setEnabled(removeButton.isEnabled()); + banItem.setEnabled(banTarget() != null); + } + + @Override + public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { + } + + @Override + public void popupMenuCanceled(PopupMenuEvent e) { + } + }); + return menu; + } + + private static JMenuItem item(String text, String icon, Runnable action) { + JMenuItem item = new JMenuItem(text, Icons.of(icon)); + item.addActionListener(e -> action.run()); + return item; + } + + private void bindKeys() { + bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("F5"), this::reload); + bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control W"), this::dispose); + bind(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), + this::removeSelected); + bind(table, JComponent.WHEN_FOCUSED, KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), () -> setLeadExpanded(true)); + bind(table, JComponent.WHEN_FOCUSED, KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), () -> setLeadExpanded(false)); + Dialogs.closeOnEscape(this); + } + + private static void bind(JComponent target, int condition, KeyStroke key, Runnable action) { + String name = "ts3-complaints-" + key; + target.getInputMap(condition).put(key, name); + target.getActionMap().put(name, new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + action.run(); + } + }); + } + + // ---- data ---- + + /** Follows the server's name, as the ban list's title does. */ + void serverNameChanged() { + String name = conn.getModel().getServerName(); + setTitle(name == null || name.isBlank() ? "Complaints List" : "Complaints List - " + name); + } + + void connectionLost() { + dispose(); + } + + private void reload() { + if (loading) return; + loading = true; + status.setText("Loading…"); + conn.requestComplaints((complaints, error) -> SwingUtilities.invokeLater(() -> { + loading = false; + if (!isDisplayable()) return; + if (error != null) { + setTargets(List.of()); + status.setText("Failed to request complaint list: " + error); + } else { + setTargets(groupByTarget(complaints)); + status.setText(complaints.size() == 1 ? "1 complaint" : complaints.size() + " complaints"); + } + })); + } + + private static List groupByTarget(List complaints) { + Map byId = new LinkedHashMap<>(); + for (Complaint c : complaints) { + byId.computeIfAbsent(c.targetDbId(), id -> new Target(id, c.targetName(), new ArrayList<>())) + .complaints().add(c); + } + List out = new ArrayList<>(byId.values()); + out.sort(Comparator.comparing(Target::name, String.CASE_INSENSITIVE_ORDER)); + for (Target t : out) t.complaints().sort(Comparator.comparingLong(Complaint::timestampEpochSeconds)); + return out; + } + + private void setTargets(List targets) { + this.targets = targets; + rebuildRows(); + } + + /** Lays the rows out again after a reload or a target opening or closing, keeping the selection. */ + private void rebuildRows() { + Set selected = new HashSet<>(selectedRows()); + List rows = new ArrayList<>(); + for (Target t : targets) { + rows.add(new Row(t, null)); + if (expanded.contains(t.dbId())) { + for (Complaint c : t.complaints()) rows.add(new Row(t, c)); + } + } + tableModel.setRows(rows); + for (int i = 0; i < rows.size(); i++) { + if (selected.contains(rows.get(i))) table.addRowSelectionInterval(i, i); + } + updateButtons(); + } + + private void setExpanded(Target target, boolean open) { + if (open ? expanded.add(target.dbId()) : expanded.remove(target.dbId())) rebuildRows(); + } + + private void setLeadExpanded(boolean open) { + int lead = table.getSelectionModel().getLeadSelectionIndex(); + if (lead < 0 || lead >= tableModel.getRowCount()) return; + Row row = tableModel.get(lead); + if (row.isTarget()) { + setExpanded(row.target(), open); + } else if (!open) { + int parent = tableModel.indexOf(new Row(row.target(), null)); + setExpanded(row.target(), false); + table.setRowSelectionInterval(parent, parent); + } + } + + private List selectedRows() { + List rows = new ArrayList<>(); + for (int i : table.getSelectedRows()) rows.add(tableModel.get(i)); + return rows; + } + + /** Whole targets selected, and complaints selected on their own (not under a selected target). */ + private Selection selection() { + Set whole = new LinkedHashSet<>(); + List single = new ArrayList<>(); + List rows = selectedRows(); + for (Row r : rows) if (r.isTarget()) whole.add(r.target()); + for (Row r : rows) if (!r.isTarget() && !whole.contains(r.target())) single.add(r.complaint()); + return new Selection(whole, single); + } + + private record Selection(Set whole, List single) { + boolean isEmpty() { + return whole.isEmpty() && single.isEmpty(); + } + + List affected() { + List all = new ArrayList<>(single); + for (Target t : whole) all.addAll(t.complaints()); + return all; + } + } + + private int selfDbId() { + ClientEntry self = conn.getModel().getClient(conn.getSelfClientId()); + return self == null ? 0 : self.databaseId; + } + + private void updateButtons() { + Selection sel = selection(); + removeButton.setEnabled(!sel.isEmpty() && conn.getModel().canDeleteComplaints(sel.affected(), selfDbId())); + } + + /** + * Who Ban Client acts on: the target on a target row, the author on a complaint row, + * as in the official client. Only an online client can be banned this way. + */ + private ClientEntry banTarget() { + int[] rows = table.getSelectedRows(); + if (rows.length != 1) return null; + ServerModel model = conn.getModel(); + if (model.selfPower("i_client_ban_power") == 0) return null; + Row row = tableModel.get(rows[0]); + ClientEntry client = model.findClientByDatabaseId(row.isTarget() ? row.target().dbId() : row.complaint().fromDbId()); + return client == null || client.id == conn.getSelfClientId() ? null : client; + } + + // ---- actions ---- + + private void removeSelected() { + if (!removeButton.isEnabled()) return; + Selection sel = selection(); + String question = sel.single().isEmpty() && sel.whole().size() == 1 + ? "Do you really want to remove all complaints of this user?" + : "Do you really want to remove the selected complaint(s)?"; + int answer = JOptionPane.showConfirmDialog(this, question, "Remove Complaints", + JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); + if (answer != JOptionPane.YES_OPTION) return; + List whole = sel.whole().stream().map(Target::dbId).toList(); + conn.deleteComplaints(whole, sel.single(), error -> SwingUtilities.invokeLater(() -> { + if (!isDisplayable()) return; + if (error != null) { + JOptionPane.showMessageDialog(this, "Failed to delete complaints: " + error, getTitle(), + JOptionPane.ERROR_MESSAGE); + } + reload(); + })); + } + + private void banSelected() { + ClientEntry client = banTarget(); + if (client != null) banClient.accept(client); + } + + // ---- table ---- + + private final class ToggleOnClick extends MouseAdapter { + @Override + public void mousePressed(MouseEvent e) { + int row = table.rowAtPoint(e.getPoint()); + if (row < 0 || !SwingUtilities.isLeftMouseButton(e)) return; + Row clicked = tableModel.get(row); + if (!clicked.isTarget()) return; + boolean onHandle = table.columnAtPoint(e.getPoint()) == Column.TARGET.ordinal() + && e.getX() - table.getCellRect(row, 0, false).x < handleWidth(); + if (onHandle || e.getClickCount() == 2) { + setExpanded(clicked.target(), !expanded.contains(clicked.target().dbId())); + } + } + } + + private static Icon handleIcon(boolean open) { + return UIManager.getIcon(open ? "Tree.expandedIcon" : "Tree.collapsedIcon"); + } + + private static int handleWidth() { + Icon icon = handleIcon(false); + return (icon == null ? UIScale.scale(12) : icon.getIconWidth()) + UIScale.scale(6); + } + + private final class ComplaintTableModel extends AbstractTableModel { + + private List rows = List.of(); + + void setRows(List rows) { + this.rows = rows; + fireTableDataChanged(); + } + + Row get(int row) { + return rows.get(row); + } + + int indexOf(Row row) { + return rows.indexOf(row); + } + + @Override + public int getRowCount() { + return rows.size(); + } + + @Override + public int getColumnCount() { + return Column.values().length; + } + + @Override + public String getColumnName(int column) { + return Column.values()[column].title; + } + + @Override + public Object getValueAt(int row, int column) { + return text(rows.get(row), Column.values()[column]); + } + + String text(Row row, Column column) { + if (row.isTarget()) { + int n = row.target().complaints().size(); + return switch (column) { + case TARGET -> row.target().name(); + case FROM -> ""; + case REASON -> n == 1 ? "has 1 complaint" : "has " + n + " complaints"; + }; + } + Complaint c = row.complaint(); + return switch (column) { + case TARGET -> c.timestampEpochSeconds() <= 0 ? "" : DATE.format( + Instant.ofEpochSecond(c.timestampEpochSeconds()).atZone(ZoneId.systemDefault())); + case FROM -> c.fromName(); + case REASON -> c.message(); + }; + } + } + + /** Draws the tree handle and indent in the first column, and a target's count greyed out. */ + private final class ComplaintCellRenderer extends DefaultTableCellRenderer { + @Override + public Component getTableCellRendererComponent(JTable t, Object value, boolean selected, + boolean focused, int row, int column) { + // setForeground sticks as the renderer's unselected colour; clear it so the + // table's own colour applies again after a greyed cell. + setForeground(null); + super.getTableCellRendererComponent(t, value, selected, focused, row, column); + Row r = tableModel.get(row); + Column c = Column.values()[column]; + setIcon(null); + setBorder(new ScaledEmptyBorder(0, 2, 0, 2)); + if (c == Column.TARGET) { + if (r.isTarget()) { + setIcon(handleIcon(expanded.contains(r.target().dbId()))); + setIconTextGap(UIScale.scale(6)); + } else { + setBorder(new ScaledEmptyBorder(0, 2 + UIScale.unscale(handleWidth()) + 6, 0, 2)); + } + } + setToolTipText(c == Column.REASON && !r.isTarget() && !r.complaint().message().isEmpty() + ? r.complaint().message() : null); + if (c == Column.REASON && r.isTarget() && !selected) setForeground(UIManager.getColor("Label.disabledForeground")); + return this; + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ConnectDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ConnectDialog.java new file mode 100644 index 0000000..82f1d42 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ConnectDialog.java @@ -0,0 +1,130 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.config.IdentityStore; +import eu.lixko.ts3j.client.config.Settings; + +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JPasswordField; +import javax.swing.JTextField; +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; + +/** Modal "Connect to Server" dialog. */ +public final class ConnectDialog extends JDialog { + + private final JTextField addressField; + private final JTextField portField; + private final JTextField nickField; + private final JPasswordField passwordField; + private final IdentityChooser identityChooser; + + private boolean confirmed; + + public ConnectDialog(Frame owner, Settings settings, IdentityStore identities) { + super(owner, "Connect to Server", true); + + String addr = settings.lastAddress; + int port = 9987; + int colon = addr.lastIndexOf(':'); + if (colon > 0) { + try { + port = Integer.parseInt(addr.substring(colon + 1)); + addr = addr.substring(0, colon); + } catch (NumberFormatException ignored) { + } + } + + addressField = new JTextField(addr, 18); + portField = new JTextField(Integer.toString(port), 6); + nickField = new JTextField(settings.nickname, 18); + passwordField = new JPasswordField(settings.serverPassword, 18); + identityChooser = new IdentityChooser(identities, false, settings.defaultIdentityId); + + JPanel form = new JPanel(new GridBagLayout()); + form.setBorder(new ScaledEmptyBorder(12, 12, 8, 12)); + GridBagConstraints c = new GridBagConstraints(); + c.insets = UIScale.scale(new Insets(4, 4, 4, 4)); + c.anchor = GridBagConstraints.WEST; + c.fill = GridBagConstraints.HORIZONTAL; + + int row = 0; + add(form, c, row++, "Server address:", addressField); + add(form, c, row++, "Port:", portField); + add(form, c, row++, "Nickname:", nickField); + add(form, c, row++, "Password (optional):", passwordField); + add(form, c, row++, "Identity:", identityChooser); + + JPanel buttons = new JPanel(new BorderLayout()); + JPanel right = new JPanel(); + JButton connect = new JButton("Connect"); + JButton cancel = new JButton("Cancel"); + connect.addActionListener(e -> { + confirmed = true; + dispose(); + }); + cancel.addActionListener(e -> dispose()); + right.add(connect); + right.add(cancel); + buttons.add(right, BorderLayout.EAST); + getRootPane().setDefaultButton(connect); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(form, BorderLayout.CENTER); + getContentPane().add(buttons, BorderLayout.SOUTH); + + Dialogs.closeOnEscape(this); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + pack(); + setMinimumSize(new Dimension(UIScale.scale(340), getHeight())); + setLocationRelativeTo(owner); + } + + private void add(JPanel form, GridBagConstraints c, int row, String label, java.awt.Component field) { + c.gridx = 0; + c.gridy = row; + c.weightx = 0; + form.add(new JLabel(label), c); + c.gridx = 1; + c.weightx = 1; + form.add(field, c); + } + + public boolean isConfirmed() { + return confirmed; + } + + public String getAddress() { + return addressField.getText().trim(); + } + + public int getPort() { + try { + return Integer.parseInt(portField.getText().trim()); + } catch (NumberFormatException e) { + return 9987; + } + } + + public String getNickname() { + String n = nickField.getText().trim(); + return n.isEmpty() ? "TS3j User" : n; + } + + public String getPassword() { + return new String(passwordField.getPassword()); + } + + /** Chosen identity id, or an empty string to fall back to the default identity. */ + public String getIdentityId() { + return identityChooser.getSelectedIdentityId(); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ConnectionInfoDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ConnectionInfoDialog.java new file mode 100644 index 0000000..c5a30f1 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ConnectionInfoDialog.java @@ -0,0 +1,337 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.net.ClientEntry; +import eu.lixko.ts3j.client.net.ConnectionStats; +import eu.lixko.ts3j.client.net.ConnectionStatsFormat; +import eu.lixko.ts3j.client.net.ConnectionStatsFormat.Row; +import eu.lixko.ts3j.client.net.ConnectionStatsFormat.TrafficRow; +import eu.lixko.ts3j.client.net.TeamspeakConnection; +import eu.lixko.ts3j.client.net.avatar.Avatar; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JSeparator; +import javax.swing.JTabbedPane; +import javax.swing.SwingConstants; +import javax.swing.SwingUtilities; +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Image; +import java.awt.Insets; +import java.awt.Toolkit; +import java.awt.datatransfer.StringSelection; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Live "Client Connection Info" window, laid out as TeamSpeak 3's: name, times, ping and + * address beside the avatar, above a tab per traffic category whose table has Total / In / + * Out columns, and a Quota tab. A Voice received tab adds what our own playback + * made of the client's voice (everyone's, for ourselves). Polls once a second while open. + */ +public final class ConnectionInfoDialog extends JDialog { + + private static final int REFRESH_MS = 1000; + /** Avatar box, about the official window's. */ + private static final int AVATAR_SIZE = 80; + /** Sample texts sizing the columns, as the official window does, so they don't jitter. */ + private static final String TOTAL_SAMPLE = "100.00 %"; + private static final String VALUE_SAMPLE = "1023.00 KiB/s"; + + private final TeamspeakConnection conn; + private final int clientId; + private final String nickname; + private final javax.swing.Timer timer; + private final AtomicBoolean inFlight = new AtomicBoolean(); + + private final Figures summary; + private final JButton copyAddress = new JButton(Icons.of("COPY")); + private final JLabel avatar = new JLabel(); + private Avatar shownAvatar; + private ConnectionStats latest; + + private final List traffic = new ArrayList<>(); + private Figures quota; + private final Figures voice = new Figures(List.of(ConnectionStatsFormat.voiceRows(null)), false); + + public ConnectionInfoDialog(Frame owner, TeamspeakConnection conn, int clientId, String nickname) { + super(owner, "Connection Info - " + nickname, false); + this.conn = conn; + this.clientId = clientId; + this.nickname = nickname; + this.summary = new Figures(List.of(ConnectionStatsFormat.summaryRows(null, nickname)), true); + + JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(12))); + content.setBackground(Theme.windowBg()); + content.setBorder(new ScaledEmptyBorder(10, 10, 10, 10)); + content.add(buildHeader(), BorderLayout.NORTH); + content.add(buildTabs(), BorderLayout.CENTER); + content.add(buildButtons(), BorderLayout.SOUTH); + setContentPane(content); + + Dialogs.closeOnEscape(this); + // Disposing is what stops the refresh timer, so the window button must not merely hide. + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + pack(); + setLocationRelativeTo(owner); + + addWindowListener(new WindowAdapter() { + @Override + public void windowClosed(WindowEvent e) { + timer.stop(); + } + }); + + timer = new javax.swing.Timer(REFRESH_MS, e -> refresh()); + timer.setInitialDelay(0); + timer.start(); + } + + // ---- construction ---- + + private JPanel buildHeader() { + copyAddress.setToolTipText("Copy client address to clipboard"); + copyAddress.setMargin(UIScale.scale(new Insets(1, 1, 1, 1))); + copyAddress.setEnabled(false); + copyAddress.addActionListener(e -> { + String address = ConnectionStatsFormat.copyableAddress(latest); + if (address != null) { + Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(address), null); + } + }); + summary.addTrailing(copyAddress); + + avatar.setVerticalAlignment(SwingConstants.TOP); + avatar.setBorder(new ScaledEmptyBorder(0, 16, 0, 0)); + + JPanel header = new JPanel(new BorderLayout()); + header.setOpaque(false); + header.add(summary, BorderLayout.CENTER); + header.add(avatar, BorderLayout.EAST); + return header; + } + + private JTabbedPane buildTabs() { + JTabbedPane tabs = new JTabbedPane(); + tabs.setFont(Theme.uiFont()); + for (ConnectionStatsFormat.Tab tab : ConnectionStatsFormat.TRAFFIC_TABS) { + TrafficTable table = new TrafficTable(tab.kind()); + traffic.add(table); + tabs.addTab(tab.title(), table); + } + tabs.addTab(ConnectionStatsFormat.QUOTA_TAB, buildQuota()); + tabs.addTab(ConnectionStatsFormat.VOICE_TAB, page(voice)); + return tabs; + } + + private JComponent buildQuota() { + // Laid out for ourselves, the longer form; another client's extra rows hide on the first update. + ConnectionStats self = new ConnectionStats(); + self.self = true; + quota = new Figures(ConnectionStatsFormat.quotaGroups(self), false); + return page(quota); + } + + private static JComponent page(JComponent body) { + JPanel page = new JPanel(new BorderLayout()); + page.setOpaque(false); + page.setBorder(new ScaledEmptyBorder(8, 10, 8, 10)); + page.add(body, BorderLayout.NORTH); + return page; + } + + private JPanel buildButtons() { + JPanel bar = new JPanel(); + bar.setLayout(new BoxLayout(bar, BoxLayout.X_AXIS)); + bar.setOpaque(false); + bar.add(Box.createHorizontalGlue()); + JButton close = new JButton("Close", Icons.of("CLOSE")); + close.addActionListener(e -> dispose()); + bar.add(close); + return bar; + } + + // ---- live update ---- + + private void refresh() { + if (!conn.isConnected()) { + timer.stop(); + return; + } + if (!inFlight.compareAndSet(false, true)) return; // a previous poll is still running + conn.requestConnectionInfo(clientId, stats -> SwingUtilities.invokeLater(() -> { + inFlight.set(false); + apply(stats); + })); + } + + private void apply(ConnectionStats s) { + if (!isDisplayable()) return; + latest = s; + summary.update(List.of(ConnectionStatsFormat.summaryRows(s, nickname))); + copyAddress.setEnabled(ConnectionStatsFormat.copyableAddress(s) != null); + for (TrafficTable table : traffic) table.update(s); + quota.update(ConnectionStatsFormat.quotaGroups(s)); + voice.update(List.of(ConnectionStatsFormat.voiceRows(s.voiceReceived))); + showAvatar(); + } + + private void showAvatar() { + ClientEntry client = conn.getModel().getClient(clientId); + Avatar current = conn.avatarOf(client); + if (current == shownAvatar) return; + shownAvatar = current; + avatar.setIcon(current == null ? null : avatarIcon(current)); + pack(); + } + + private static ImageIcon avatarIcon(Avatar avatar) { + if (avatar.file() == null) return null; + Dimension size = AvatarHtml.fit(AvatarHtml.dimensions(avatar.data()), UIScale.scale(AVATAR_SIZE)); + ImageIcon icon = new ImageIcon(avatar.data()); + if (size == null) return icon; + return new ImageIcon(icon.getImage().getScaledInstance(size.width, size.height, Image.SCALE_SMOOTH)); + } + + // ---- figures ---- + + private static JLabel label(String text) { + JLabel l = new JLabel(text); + l.setFont(Theme.uiFont()); + return l; + } + + /** Pins a label's width to that of {@code sample}, so a growing figure doesn't resize the window. */ + private static JLabel sized(JLabel l, String sample) { + Dimension pref = l.getPreferredSize(); + int width = l.getFontMetrics(l.getFont()).stringWidth(sample); + l.setPreferredSize(new Dimension(Math.max(pref.width, width), pref.height)); + return l; + } + + private static GridBagConstraints cell(int x, int y, int anchor, Insets insets) { + GridBagConstraints c = new GridBagConstraints(); + c.gridx = x; + c.gridy = y; + c.anchor = anchor; + c.insets = UIScale.scale(insets); + return c; + } + + /** + * Labelled figures, one per row, in groups set apart by a rule; refreshed in place, and + * rows an update leaves out hide. + */ + private static final class Figures extends JPanel { + private final List> groups = new ArrayList<>(); + private int lastRow; + + Figures(List> rows, boolean valuesRight) { + super(new GridBagLayout()); + setOpaque(false); + int y = 0; + for (List group : rows) { + if (y > 0) { + GridBagConstraints rule = cell(0, y++, GridBagConstraints.WEST, new Insets(6, 0, 6, 0)); + rule.gridwidth = 2; + rule.fill = GridBagConstraints.HORIZONTAL; + add(new JSeparator(), rule); + } + List labels = new ArrayList<>(); + for (Row row : group) { + JLabel key = label(row.label()); + JLabel value = label(row.value()); + labels.add(new JLabel[]{key, value}); + add(key, cell(0, y, GridBagConstraints.WEST, new Insets(3, 0, 3, 16))); + GridBagConstraints vc = cell(1, y, valuesRight ? GridBagConstraints.EAST : GridBagConstraints.WEST, + new Insets(3, 0, 3, 0)); + vc.weightx = 1; + add(value, vc); + lastRow = y++; + } + groups.add(labels); + } + } + + /** Puts {@code c} after the last row's value. */ + void addTrailing(JComponent c) { + add(c, cell(2, lastRow, GridBagConstraints.EAST, new Insets(0, 6, 0, 0))); + } + + void update(List> rows) { + for (int g = 0; g < groups.size(); g++) { + List labels = groups.get(g); + List group = rows.get(g); + for (int i = 0; i < labels.size(); i++) { + boolean shown = i < group.size(); + labels.get(i)[0].setVisible(shown); + labels.get(i)[1].setVisible(shown); + if (shown) labels.get(i)[1].setText(group.get(i).value()); + } + } + } + } + + /** One traffic category: a row per figure under Total / In / Out headings. */ + private static final class TrafficTable extends JPanel { + private final ConnectionStats.Kind kind; + private final JLabel[][] cells; + + TrafficTable(ConnectionStats.Kind kind) { + super(new GridBagLayout()); + this.kind = kind; + setOpaque(false); + setBorder(new ScaledEmptyBorder(8, 10, 8, 10)); + + List columns = ConnectionStatsFormat.COLUMNS; + for (int c = 0; c < columns.size(); c++) { + JLabel heading = label(columns.get(c)); + heading.setFont(heading.getFont().deriveFont(Font.ITALIC)); + add(heading, column(c + 1, 0)); + } + List rows = ConnectionStatsFormat.trafficRows(null, kind); + cells = new JLabel[rows.size()][]; + for (int r = 0; r < rows.size(); r++) { + TrafficRow row = rows.get(r); + add(label(row.label()), cell(0, r + 1, GridBagConstraints.WEST, new Insets(3, 0, 3, 8))); + cells[r] = new JLabel[]{ + sized(label(row.total()), TOTAL_SAMPLE), sized(label(row.in()), VALUE_SAMPLE), + sized(label(row.out()), VALUE_SAMPLE)}; + for (int c = 0; c < cells[r].length; c++) add(cells[r][c], column(c + 1, r + 1)); + } + GridBagConstraints filler = cell(0, rows.size() + 1, GridBagConstraints.WEST, new Insets(0, 0, 0, 0)); + filler.weighty = 1; + add(Box.createGlue(), filler); + } + + private static GridBagConstraints column(int x, int y) { + GridBagConstraints c = cell(x, y, GridBagConstraints.WEST, new Insets(3, 8, 3, 8)); + c.weightx = 1; + return c; + } + + void update(ConnectionStats s) { + List rows = ConnectionStatsFormat.trafficRows(s, kind); + for (int r = 0; r < rows.size(); r++) { + cells[r][0].setText(rows.get(r).total()); + cells[r][1].setText(rows.get(r).in()); + cells[r][2].setText(rows.get(r).out()); + } + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ContactDefaultsDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ContactDefaultsDialog.java new file mode 100644 index 0000000..f72bead --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ContactDefaultsDialog.java @@ -0,0 +1,201 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.contacts.ContactDefaults; +import eu.lixko.ts3j.client.contacts.ContactType; +import eu.lixko.ts3j.client.contacts.NicknameDisplay; + +import javax.swing.BorderFactory; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JSeparator; +import javax.swing.SwingConstants; +import java.awt.BorderLayout; +import java.awt.Dialog; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.util.EnumMap; +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.Function; + +/** + * TeamSpeak's "Contact Manager Default Settings": what a client starts out with + * when added as a friend, blocked or neutral — the ignore/hide flags and how its + * nickname is displayed — in a grid with one column per contact type. + */ +final class ContactDefaultsDialog extends JDialog { + + private static final ContactType[] COLUMNS = {ContactType.FRIEND, ContactType.BLOCKED, ContactType.NEUTRAL}; + + private final Settings settings; + private final Map> flags = new EnumMap<>(ContactType.class); + private final Map> displays = new EnumMap<>(ContactType.class); + + ContactDefaultsDialog(Dialog owner, Settings settings) { + super(owner, "Contact Manager Default Settings", true); + this.settings = settings; + for (ContactType t : COLUMNS) { + flags.put(t, new java.util.LinkedHashMap<>()); + displays.put(t, new EnumMap<>(NicknameDisplay.class)); + } + + JPanel content = new JPanel(); + content.setLayout(new javax.swing.BoxLayout(content, javax.swing.BoxLayout.Y_AXIS)); + content.setBorder(new ScaledEmptyBorder(12, 12, 8, 12)); + JLabel intro = new JLabel("Configure default settings when adding a client to the Contact Manager"); + intro.setAlignmentX(LEFT_ALIGNMENT); + content.add(intro); + content.add(javax.swing.Box.createVerticalStrut(UIScale.scale(10))); + content.add(buildFlags()); + content.add(javax.swing.Box.createVerticalStrut(UIScale.scale(10))); + content.add(buildDisplays()); + + JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT)); + JButton ok = new JButton("OK"); + ok.addActionListener(e -> { + apply(); + dispose(); + }); + JButton cancel = new JButton("Cancel"); + cancel.addActionListener(e -> dispose()); + buttons.add(ok); + buttons.add(cancel); + getRootPane().setDefaultButton(ok); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(content, BorderLayout.CENTER); + getContentPane().add(buttons, BorderLayout.SOUTH); + + load(); + Dialogs.closeOnEscape(this); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + pack(); + setMinimumSize(new Dimension(getWidth(), getHeight())); + setLocationRelativeTo(owner); + } + + private JPanel buildFlags() { + JPanel grid = titledGrid("Ignore and Hide Defaults"); + int row = 1; + row = flagRow(grid, row, "Mute", "automute", "Automatically mute this person"); + row = flagRow(grid, row, "Ignore server/channel chat", "ignorePublicMessages", + "Ignore messages this person sends to the server or in channels"); + row = flagRow(grid, row, "Ignore private chat", "ignorePrivateMessages", "Ignore private chat by this person"); + row = flagRow(grid, row, "Ignore Pokes", "ignorePokes", "Ignore pokes this person sends you"); + row = flagRow(grid, row, "Hide avatar", "ignoreAvatar", "Do not download this person's avatar"); + row = flagRow(grid, row, "Hide away message", "ignoreAwayMessage", "Ignore this person's away messages"); + flagRow(grid, row, "Deny whisper", "ignoreWhisper", "This contact is always denied to whisper to you."); + return grid; + } + + private JPanel buildDisplays() { + JPanel grid = titledGrid("Nickname Display Defaults"); + Map groups = new EnumMap<>(ContactType.class); + for (ContactType t : COLUMNS) groups.put(t, new ButtonGroup()); + int row = 1; + for (NicknameDisplay display : NicknameDisplay.values()) { + GridBagConstraints c = cell(0, row); + c.anchor = GridBagConstraints.WEST; + grid.add(new JLabel(display.label()), c); + for (int i = 0; i < COLUMNS.length; i++) { + JRadioButton radio = new JRadioButton(); + radio.setToolTipText(display == NicknameDisplay.BOTH ? "Show both custom name and the nickname" + : display == NicknameDisplay.ONLY_CUSTOM ? "Show only custom name" : "Show only the nickname"); + groups.get(COLUMNS[i]).add(radio); + displays.get(COLUMNS[i]).put(display, radio); + grid.add(radio, cell(i + 1, row)); + } + row++; + } + return grid; + } + + /** A grid with the three contact types as column headings. */ + private JPanel titledGrid(String title) { + JPanel grid = new JPanel(new GridBagLayout()); + grid.setBorder(BorderFactory.createTitledBorder(title)); + grid.setAlignmentX(LEFT_ALIGNMENT); + String[] headings = {"Friends", "Blocked", "Neutral"}; + for (int i = 0; i < headings.length; i++) { + JLabel heading = new JLabel(headings[i], SwingConstants.CENTER); + heading.setFont(Theme.uiBold()); + GridBagConstraints c = cell(i + 1, 0); + c.ipadx = 12; + grid.add(heading, c); + } + GridBagConstraints line = cell(0, 100); + line.gridwidth = 4; + line.fill = GridBagConstraints.HORIZONTAL; + grid.add(new JSeparator(), line); + return grid; + } + + private int flagRow(JPanel grid, int row, String label, String key, String tooltip) { + GridBagConstraints c = cell(0, row); + c.anchor = GridBagConstraints.WEST; + c.weightx = 1; + grid.add(new JLabel(label), c); + for (int i = 0; i < COLUMNS.length; i++) { + JCheckBox box = new JCheckBox(); + box.setToolTipText(tooltip); + flags.get(COLUMNS[i]).put(key, box); + grid.add(box, cell(i + 1, row)); + } + return row + 1; + } + + private static GridBagConstraints cell(int x, int y) { + GridBagConstraints c = new GridBagConstraints(); + c.gridx = x; + c.gridy = y; + c.insets = UIScale.scale(new Insets(1, 6, 1, 6)); + c.anchor = GridBagConstraints.CENTER; + return c; + } + + // ---- model <-> fields ---- + + private void load() { + for (ContactType t : COLUMNS) { + ContactDefaults.Entry e = settings.contactDefaults.of(t); + Map boxes = flags.get(t); + boxes.get("automute").setSelected(e.automute); + boxes.get("ignorePublicMessages").setSelected(e.ignorePublicMessages); + boxes.get("ignorePrivateMessages").setSelected(e.ignorePrivateMessages); + boxes.get("ignorePokes").setSelected(e.ignorePokes); + boxes.get("ignoreAvatar").setSelected(e.ignoreAvatar); + boxes.get("ignoreAwayMessage").setSelected(e.ignoreAwayMessage); + boxes.get("ignoreWhisper").setSelected(e.ignoreWhisper); + displays.get(t).get(e.nicknameDisplay).setSelected(true); + } + } + + private void apply() { + for (ContactType t : COLUMNS) { + ContactDefaults.Entry e = settings.contactDefaults.of(t); + Map boxes = flags.get(t); + e.automute = boxes.get("automute").isSelected(); + e.ignorePublicMessages = boxes.get("ignorePublicMessages").isSelected(); + e.ignorePrivateMessages = boxes.get("ignorePrivateMessages").isSelected(); + e.ignorePokes = boxes.get("ignorePokes").isSelected(); + e.ignoreAvatar = boxes.get("ignoreAvatar").isSelected(); + e.ignoreAwayMessage = boxes.get("ignoreAwayMessage").isSelected(); + e.ignoreWhisper = boxes.get("ignoreWhisper").isSelected(); + for (Map.Entry radio : displays.get(t).entrySet()) { + if (radio.getValue().isSelected()) e.nicknameDisplay = radio.getKey(); + } + } + settings.save(); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ContactsDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ContactsDialog.java new file mode 100644 index 0000000..5920965 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ContactsDialog.java @@ -0,0 +1,569 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.contacts.Contact; +import eu.lixko.ts3j.client.contacts.ContactStore; +import eu.lixko.ts3j.client.contacts.ContactType; +import eu.lixko.ts3j.client.contacts.NicknameDisplay; +import eu.lixko.ts3j.client.teamspeak.TeamSpeakSettingsDb; +import eu.lixko.ts3j.client.text.TsLink; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.JRadioButton; +import javax.swing.JScrollPane; +import javax.swing.JTextField; +import javax.swing.JTree; +import javax.swing.KeyStroke; +import javax.swing.SwingUtilities; +import javax.swing.TransferHandler; +import javax.swing.border.Border; +import javax.swing.plaf.basic.BasicTreeUI; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeCellRenderer; +import javax.swing.tree.DefaultTreeModel; +import javax.swing.tree.TreePath; +import javax.swing.tree.TreeSelectionModel; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.Toolkit; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.StringSelection; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.io.File; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.function.Consumer; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * The contact list window: the contacts grouped as friends, blocked and neutral on + * the left, and on the right all of the selected one's settings — TeamSpeak's + * General / Display / Ignore / Whisper pages, in one column rather than as tabs + * since each holds only a few options. Every edit is stored as it is made. + * + *

    Clients can be dragged in from the server tree — the drag carries the + * client's TS3 link, which names its unique id. + */ +final class ContactsDialog extends JDialog { + + private static final DateTimeFormatter SEEN = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); + private static final DateTimeFormatter SEEN_DAY = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + private static final Pattern CLIENT_LINK = Pattern.compile("client://[^\\]\\s]+"); + + private final ContactStore contacts; + private final Settings settings; + private final ContactStore.Listener storeListener = () -> SwingUtilities.invokeLater(this::reload); + + private final DefaultMutableTreeNode root = new DefaultMutableTreeNode(); + private final DefaultTreeModel treeModel = new DefaultTreeModel(root); + private final JTree tree = new JTree(treeModel); + private final DefaultMutableTreeNode friends = new DefaultMutableTreeNode("Friends"); + private final DefaultMutableTreeNode blocked = new DefaultMutableTreeNode("Blocked"); + private final DefaultMutableTreeNode neutral = new DefaultMutableTreeNode("Neutral"); + + private final JTextField nicknameField = new JTextField(18); + private final JButton nicknameApply = new JButton("Apply"); + private final JRadioButton neutralRadio = new JRadioButton("Neutral"); + private final JRadioButton blockedRadio = new JRadioButton("Blocked"); + private final JRadioButton friendRadio = new JRadioButton("Friend"); + private final JTextField phoneticField = new JTextField(18); + private final JLabel lastSeenLabel = new JLabel(" "); + private final JRadioButton bothRadio = new JRadioButton(NicknameDisplay.BOTH.label()); + private final JRadioButton onlyCustomRadio = new JRadioButton(NicknameDisplay.ONLY_CUSTOM.label()); + private final JRadioButton onlyNicknameRadio = new JRadioButton(NicknameDisplay.ONLY_NICKNAME.label()); + private final JCheckBox automute = new JCheckBox("Mute"); + private final JCheckBox ignorePublic = new JCheckBox("Ignore server/channel chat"); + private final JCheckBox ignorePrivate = new JCheckBox("Ignore private chat"); + private final JCheckBox ignorePokes = new JCheckBox("Ignore Pokes"); + private final JCheckBox ignoreAvatar = new JCheckBox("Hide avatar"); + private final JCheckBox ignoreAway = new JCheckBox("Hide away message"); + private final JCheckBox denyWhisper = new JCheckBox("Deny whisper"); + private final JPanel details = new JPanel(new BorderLayout(0, UIScale.scale(8))); + + /** Set while the fields are being filled from a contact, so that does not count as an edit. */ + private boolean filling; + + ContactsDialog(Frame owner, ContactStore contacts, Settings settings) { + super(owner, "Contacts", false); + this.contacts = contacts; + this.settings = settings; + + buildTree(); + JPanel left = new JPanel(new BorderLayout(0, UIScale.scale(4))); + left.setBorder(new ScaledEmptyBorder(8, 8, 8, 4)); + JLabel hint = new JLabel("Drag & Drop users here"); + hint.setForeground(Theme.chatSystem()); + left.add(hint, BorderLayout.NORTH); + JScrollPane scroll = new JScrollPane(tree); + scroll.setPreferredSize(UIScale.scale(new Dimension(300, 340))); + left.add(scroll, BorderLayout.CENTER); + + details.setBorder(new ScaledEmptyBorder(8, 4, 8, 8)); + details.add(buildNicknameRow(), BorderLayout.NORTH); + details.add(buildOptions(), BorderLayout.CENTER); + + JPanel buttons = new JPanel(new BorderLayout()); + buttons.setBorder(new ScaledEmptyBorder(0, 8, 8, 8)); + JPanel leftButtons = new JPanel(new FlowLayout(FlowLayout.LEFT, UIScale.scale(6), 0)); + JButton defaults = new JButton("Set Defaults"); + defaults.setToolTipText("Set default display, ignore and hide options"); + defaults.addActionListener(e -> new ContactDefaultsDialog(this, settings).setVisible(true)); + leftButtons.add(defaults); + if (TeamSpeakSettingsDb.locate() != null) { + JButton importButton = new JButton("Import from TeamSpeak 3…"); + importButton.setToolTipText("Add the contacts of the TeamSpeak 3 client installed on this computer"); + importButton.addActionListener(e -> importFromTeamSpeak()); + leftButtons.add(importButton); + } + buttons.add(leftButtons, BorderLayout.WEST); + JButton close = new JButton("Close"); + close.addActionListener(e -> dispose()); + JPanel rightButtons = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0)); + rightButtons.add(close); + buttons.add(rightButtons, BorderLayout.EAST); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(left, BorderLayout.WEST); + getContentPane().add(details, BorderLayout.CENTER); + getContentPane().add(buttons, BorderLayout.SOUTH); + + contacts.addListener(storeListener); + addWindowListener(new java.awt.event.WindowAdapter() { + @Override + public void windowClosed(java.awt.event.WindowEvent e) { + contacts.removeListener(storeListener); + } + }); + + reload(); + Dialogs.closeOnEscape(this); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + pack(); + // Only the list scrolls, so the window never gets shorter than the options column. + setMinimumSize(new Dimension(UIScale.scale(620), getHeight())); + setLocationRelativeTo(owner); + } + + // ---- tree ---- + + private void buildTree() { + root.add(friends); + root.add(blocked); + root.add(neutral); + tree.setRootVisible(false); + tree.setShowsRootHandles(true); + // Half the usual nesting, so long names and their dates fit in the narrow list. + if (tree.getUI() instanceof BasicTreeUI) { + BasicTreeUI ui = (BasicTreeUI) tree.getUI(); + ui.setLeftChildIndent(UIScale.scale(4)); + ui.setRightChildIndent(UIScale.scale(5)); + } + tree.setRowHeight(UIScale.scale(20)); + tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); + tree.setCellRenderer(new ContactRenderer()); + tree.addTreeSelectionListener(e -> showSelected()); + tree.addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + maybePopup(e); + } + + @Override + public void mouseReleased(MouseEvent e) { + maybePopup(e); + } + }); + tree.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "remove"); + tree.getActionMap().put("remove", new javax.swing.AbstractAction() { + @Override + public void actionPerformed(java.awt.event.ActionEvent e) { + removeSelected(); + } + }); + tree.setTransferHandler(new DropHandler()); + } + + /** Re-lists the contacts, keeping the selection on the same unique id. */ + private void reload() { + String selectedUid = selectedContact() == null ? null : selectedContact().uniqueId; + for (DefaultMutableTreeNode group : List.of(friends, blocked, neutral)) group.removeAllChildren(); + List sorted = new ArrayList<>(contacts.all()); + sorted.sort(Comparator.comparing((Contact c) -> c.nickname, String.CASE_INSENSITIVE_ORDER) + .thenComparing(c -> c.uniqueId)); + for (Contact c : sorted) groupOf(c.type).add(new DefaultMutableTreeNode(c)); + treeModel.reload(); + for (int i = 0; i < tree.getRowCount(); i++) tree.expandRow(i); + if (selectedUid != null) select(selectedUid); + else showSelected(); + } + + private DefaultMutableTreeNode groupOf(ContactType type) { + switch (type) { + case FRIEND: + return friends; + case BLOCKED: + return blocked; + default: + return neutral; + } + } + + /** Selects the contact with a unique id, if it is on the list. */ + void select(String uniqueId) { + java.util.Enumeration nodes = root.depthFirstEnumeration(); + while (nodes.hasMoreElements()) { + DefaultMutableTreeNode n = (DefaultMutableTreeNode) nodes.nextElement(); + if (n.getUserObject() instanceof Contact && ((Contact) n.getUserObject()).uniqueId.equals(uniqueId)) { + TreePath path = new TreePath(n.getPath()); + tree.setSelectionPath(path); + tree.scrollPathToVisible(path); + return; + } + } + } + + private Contact selectedContact() { + TreePath path = tree.getSelectionPath(); + if (path == null) return null; + Object obj = ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); + return obj instanceof Contact ? (Contact) obj : null; + } + + private void maybePopup(MouseEvent e) { + if (!e.isPopupTrigger()) return; + TreePath path = tree.getPathForLocation(e.getX(), e.getY()); + if (path == null) return; + tree.setSelectionPath(path); + Contact contact = selectedContact(); + if (contact == null) return; + + JPopupMenu menu = new JPopupMenu(); + for (ContactType type : new ContactType[]{ContactType.FRIEND, ContactType.BLOCKED, ContactType.NEUTRAL}) { + JMenuItem item = new javax.swing.JRadioButtonMenuItem(type.label(), type == contact.type); + item.addActionListener(a -> edit(c -> c.type = type)); + menu.add(item); + } + menu.addSeparator(); + JMenuItem remove = new JMenuItem("Remove", Icons.of("DELETE")); + remove.addActionListener(a -> removeSelected()); + menu.add(remove); + JMenuItem applyDefaults = new JMenuItem("Apply Defaults"); + applyDefaults.addActionListener(a -> edit(c -> c.applyDefaults(settings.contactDefaults.of(c.type)))); + menu.add(applyDefaults); + menu.addSeparator(); + JMenuItem copyUid = new JMenuItem("Copy Unique ID to Clipboard", Icons.of("COPY")); + copyUid.addActionListener(a -> Toolkit.getDefaultToolkit().getSystemClipboard() + .setContents(new StringSelection(contact.uniqueId), null)); + menu.add(copyUid); + menu.show(tree, e.getX(), e.getY()); + } + + private void removeSelected() { + Contact contact = selectedContact(); + if (contact == null) return; + int answer = JOptionPane.showConfirmDialog(this, + "Do you really want to delete contact " + contact.nickname + "?", "Remove Contact", + JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); + if (answer == JOptionPane.YES_OPTION) contacts.remove(contact.uniqueId); + } + + private void importFromTeamSpeak() { + File db = TeamSpeakSettingsDb.locate(); + if (db == null) return; + try { + List imported = TeamSpeakSettingsDb.readContacts(db); + int added = contacts.merge(imported); + JOptionPane.showMessageDialog(this, imported.size() + " contact(s) read from " + db + + "\n" + added + " new, " + (imported.size() - added) + " updated.", + "Import from TeamSpeak 3", JOptionPane.INFORMATION_MESSAGE); + } catch (Exception e) { + JOptionPane.showMessageDialog(this, "Could not read " + db + ":\n" + e.getMessage(), + "Import from TeamSpeak 3", JOptionPane.ERROR_MESSAGE); + } + } + + // ---- details ---- + + /** The names, each label on its own line above its field. */ + private JComponent buildNicknameRow() { + JPanel row = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + c.insets = UIScale.scale(new Insets(2, 2, 2, 2)); + c.anchor = GridBagConstraints.WEST; + c.gridx = 0; + c.gridy = 0; + c.gridwidth = 2; + row.add(new JLabel("Custom Nickname:"), c); + + c.gridy = 1; + c.gridwidth = 1; + c.weightx = 1; + c.fill = GridBagConstraints.HORIZONTAL; + nicknameField.setToolTipText("Enter custom nickname"); + nicknameField.addActionListener(e -> applyNickname()); + row.add(nicknameField, c); + c.gridx = 1; + c.weightx = 0; + c.fill = GridBagConstraints.NONE; + nicknameApply.setToolTipText("Apply nickname change"); + nicknameApply.addActionListener(e -> applyNickname()); + row.add(nicknameApply, c); + + c.gridx = 0; + c.gridy = 2; + c.gridwidth = 2; + row.add(new JLabel("Phonetic Nickname:"), c); + c.gridy = 3; + c.weightx = 1; + c.fill = GridBagConstraints.HORIZONTAL; + row.add(phoneticField, c); + c.gridy = 4; + row.add(lastSeenLabel, c); + return row; + } + + /** Every option at once, one short group under the other. */ + private JComponent buildOptions() { + JComponent contact = group("Contact", radioGroup(neutralRadio, blockedRadio, friendRadio)); + neutralRadio.setToolTipText("Mark as neutral"); + blockedRadio.setToolTipText("Mark as blocked"); + friendRadio.setToolTipText("Mark as friend"); + phoneticField.setToolTipText("Client nickname written as phonemes (optional)"); + neutralRadio.addActionListener(e -> edit(c -> c.type = ContactType.NEUTRAL)); + blockedRadio.addActionListener(e -> edit(c -> c.type = ContactType.BLOCKED)); + friendRadio.addActionListener(e -> edit(c -> c.type = ContactType.FRIEND)); + phoneticField.addActionListener(e -> applyPhonetic()); + phoneticField.addFocusListener(new java.awt.event.FocusAdapter() { + @Override + public void focusLost(java.awt.event.FocusEvent e) { + applyPhonetic(); + } + }); + + JComponent display = group("Display", radioGroup(bothRadio, onlyCustomRadio, onlyNicknameRadio)); + bothRadio.setToolTipText("Show custom name and nickname"); + onlyCustomRadio.setToolTipText("Show only custom name"); + onlyNicknameRadio.setToolTipText("Show nickname only"); + bothRadio.addActionListener(e -> edit(c -> c.nicknameDisplay = NicknameDisplay.BOTH)); + onlyCustomRadio.addActionListener(e -> edit(c -> c.nicknameDisplay = NicknameDisplay.ONLY_CUSTOM)); + onlyNicknameRadio.addActionListener(e -> edit(c -> c.nicknameDisplay = NicknameDisplay.ONLY_NICKNAME)); + + JComponent ignore = group("Ignore", automute, ignorePublic, ignorePrivate, ignorePokes, ignoreAvatar, ignoreAway, + denyWhisper); + automute.setToolTipText("Automatically mute this person"); + ignorePublic.setToolTipText("Ignore messages this person sends to the server or in channels"); + ignorePrivate.setToolTipText("Ignore private chat by this person"); + ignorePokes.setToolTipText("Ignore pokes this person sends you"); + ignoreAvatar.setToolTipText("Do not download this person's avatar"); + ignoreAway.setToolTipText("Ignore this person's away messages"); + automute.addActionListener(e -> edit(c -> c.automute = automute.isSelected())); + ignorePublic.addActionListener(e -> edit(c -> c.ignorePublicMessages = ignorePublic.isSelected())); + ignorePrivate.addActionListener(e -> edit(c -> c.ignorePrivateMessages = ignorePrivate.isSelected())); + ignorePokes.addActionListener(e -> edit(c -> c.ignorePokes = ignorePokes.isSelected())); + ignoreAvatar.addActionListener(e -> edit(c -> c.ignoreAvatar = ignoreAvatar.isSelected())); + ignoreAway.addActionListener(e -> edit(c -> c.ignoreAwayMessage = ignoreAway.isSelected())); + + denyWhisper.setToolTipText("This contact is always denied to whisper to you"); + denyWhisper.addActionListener(e -> edit(c -> c.whisperAllowed = !denyWhisper.isSelected())); + return column(contact, display, ignore); + } + + private static JPanel column(JComponent... groups) { + JPanel p = new JPanel(); + p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); + for (JComponent g : groups) { + g.setAlignmentX(Component.LEFT_ALIGNMENT); + g.setMaximumSize(new Dimension(Integer.MAX_VALUE, g.getPreferredSize().height)); + p.add(g); + p.add(Box.createVerticalStrut(UIScale.scale(6))); + } + p.add(Box.createVerticalGlue()); + return p; + } + + private static JPanel group(String title, JComponent... rows) { + JPanel p = new JPanel(); + p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); + p.setBorder(BorderFactory.createTitledBorder(title)); + for (JComponent row : rows) { + row.setAlignmentX(Component.LEFT_ALIGNMENT); + p.add(row); + } + return p; + } + + private static JPanel radioGroup(JRadioButton... buttons) { + ButtonGroup group = new ButtonGroup(); + JPanel p = new JPanel(); + p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); + for (JRadioButton b : buttons) { + group.add(b); + b.setAlignmentX(Component.LEFT_ALIGNMENT); + p.add(b); + } + return p; + } + + /** Fills the right-hand side from the selected contact, or greys it out. */ + private void showSelected() { + Contact c = selectedContact(); + filling = true; + try { + setDetailsEnabled(details, c != null); + if (c == null) { + nicknameField.setText(""); + phoneticField.setText(""); + lastSeenLabel.setText(" "); + return; + } + nicknameField.setText(c.nickname); + phoneticField.setText(c.phoneticNickname); + lastSeenLabel.setText(lastSeen(c)); + (c.type == ContactType.FRIEND ? friendRadio : c.type == ContactType.BLOCKED ? blockedRadio : neutralRadio) + .setSelected(true); + (c.nicknameDisplay == NicknameDisplay.ONLY_CUSTOM ? onlyCustomRadio + : c.nicknameDisplay == NicknameDisplay.ONLY_NICKNAME ? onlyNicknameRadio : bothRadio) + .setSelected(true); + automute.setSelected(c.automute); + ignorePublic.setSelected(c.ignorePublicMessages); + ignorePrivate.setSelected(c.ignorePrivateMessages); + ignorePokes.setSelected(c.ignorePokes); + ignoreAvatar.setSelected(c.ignoreAvatar); + ignoreAway.setSelected(c.ignoreAwayMessage); + denyWhisper.setSelected(!c.whisperAllowed); + } finally { + filling = false; + } + } + + private static String lastSeen(Contact c) { + if (c.lastSeen == null) return "Never seen"; + String where = c.lastSeenServerName.isEmpty() ? c.lastSeenServerAddress : c.lastSeenServerName; + return "Last seen " + SEEN.format(c.lastSeen) + (where.isEmpty() ? "" : " on " + where); + } + + private static void setDetailsEnabled(Component component, boolean enabled) { + component.setEnabled(enabled); + if (component instanceof java.awt.Container) { + for (Component child : ((java.awt.Container) component).getComponents()) { + setDetailsEnabled(child, enabled); + } + } + } + + /** Changes the selected contact and stores it; the store's change notice re-lists the tree. */ + private void edit(Consumer change) { + if (filling) return; + Contact c = selectedContact(); + if (c == null) return; + change.accept(c); + contacts.put(c); + } + + private void applyNickname() { + String name = nicknameField.getText().trim(); + Contact c = selectedContact(); + if (c == null || name.isEmpty() || name.equals(c.nickname)) return; + edit(contact -> contact.nickname = name); + } + + private void applyPhonetic() { + String name = phoneticField.getText().trim(); + Contact c = selectedContact(); + if (c == null || name.equals(c.phoneticNickname)) return; + edit(contact -> contact.phoneticNickname = name); + } + + // ---- drop target ---- + + /** Accepts clients dragged out of a server tree, whose transfer text is their TS3 link. */ + private final class DropHandler extends TransferHandler { + @Override + public boolean canImport(TransferSupport support) { + return support.isDataFlavorSupported(DataFlavor.stringFlavor); + } + + @Override + public boolean importData(TransferSupport support) { + String text; + try { + text = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor); + } catch (Exception e) { + return false; + } + boolean added = false; + Matcher m = CLIENT_LINK.matcher(text); + while (m.find()) { + TsLink.Ref ref = TsLink.parse(m.group()); + if (ref == null || !ref.client || ref.uniqueId.isEmpty()) continue; + if (contacts.find(ref.uniqueId) == null) { + contacts.add(ref.uniqueId, ref.name, ContactType.NEUTRAL, settings.contactDefaults); + } + select(ref.uniqueId); + added = true; + } + return added; + } + } + + // ---- rendering ---- + + private static final class ContactRenderer extends DefaultTreeCellRenderer { + private final Border margin = getBorder(); + /** Keeps a group's name clear of its expand arrow, which the tight nesting brings close. */ + private final Border groupMargin = BorderFactory.createCompoundBorder(margin, new ScaledEmptyBorder(0, 4, 0, 0)); + + @Override + public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, + boolean leaf, int row, boolean hasFocus) { + super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); + Object obj = ((DefaultMutableTreeNode) value).getUserObject(); + if (obj instanceof Contact) { + Contact c = (Contact) obj; + setText("" + esc(c.nickname) + "  " + (c.lastSeen == null ? "Never" : SEEN_DAY.format(c.lastSeen)) + ""); + setFont(Theme.uiFont()); + setBorder(margin); + } else { + setText(String.valueOf(obj)); + setFont(Theme.uiBold()); + setBorder(groupMargin); + } + setIcon(null); + return this; + } + + private static String esc(String s) { + return s.replace("&", "&").replace("<", "<").replace(">", ">"); + } + + private static String hex(java.awt.Color c) { + return String.format("#%02x%02x%02x", c.getRed(), c.getGreen(), c.getBlue()); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ContactsPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ContactsPanel.java new file mode 100644 index 0000000..ea88ca6 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ContactsPanel.java @@ -0,0 +1,74 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.config.Settings; + +import javax.swing.DefaultListCellRenderer; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import java.awt.Component; +import java.awt.FlowLayout; +import java.awt.GridBagConstraints; + +/** + * Options page for the contact list: whether friends and blocked clients are + * coloured in the server tree, whose whispers get through (TeamSpeak's whisper + * options), and the defaults a new contact starts with. + */ +final class ContactsPanel extends FormPanel { + + private final Settings settings; + private final JCheckBox colorContacts = new JCheckBox("Colour friends and blocked clients in the server tree"); + private final JComboBox whisperPolicy = new JComboBox<>(Settings.WhisperPolicy.values()); + + ContactsPanel(Settings settings) { + this.settings = settings; + GridBagConstraints c = gbc(); + + colorContacts.setSelected(settings.colorContacts); + colorContacts.setToolTipText("Friends in green and blocked clients in red, as the TeamSpeak client shows them"); + + whisperPolicy.setSelectedItem(settings.whisperPolicy); + whisperPolicy.setRenderer(new DefaultListCellRenderer() { + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, + boolean selected, boolean focus) { + super.getListCellRendererComponent(list, value, index, selected, focus); + if (value instanceof Settings.WhisperPolicy) setText(((Settings.WhisperPolicy) value).label()); + return this; + } + }); + whisperPolicy.setToolTipText("Use individual settings in contacts, else allow: a client not on your " + + "contact list may whisper to you.
    Use individual settings in contacts, else deny: only " + + "contacts marked \"Allow whisper\" may.
    Nobody: individual contact settings are ignored."); + + JButton defaults = new JButton("Contact defaults…"); + defaults.setToolTipText("Configure default settings when adding a client to the Contact Manager"); + defaults.addActionListener(e -> { + java.awt.Window owner = SwingUtilities.getWindowAncestor(this); + new ContactDefaultsDialog(owner instanceof JDialog ? (JDialog) owner : null, settings).setVisible(true); + }); + JPanel defaultsRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); + defaultsRow.add(defaults); + + int row = 0; + addSection(this, c, row++, "Server Tree"); + addWide(this, c, row++, colorContacts); + addSection(this, c, row++, "Whispers"); + addRow(this, c, row++, new JLabel("Allow whispers from:"), whisperPolicy); + addSection(this, c, row++, "New Contacts"); + addWide(this, c, row++, defaultsRow); + addFiller(this, c, row); + } + + /** Copies the page into the settings; the caller saves them. */ + void apply() { + settings.colorContacts = colorContacts.isSelected(); + settings.whisperPolicy = (Settings.WhisperPolicy) whisperPolicy.getSelectedItem(); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/CountryFlagIcons.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/CountryFlagIcons.java new file mode 100644 index 0000000..a6f73f2 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/CountryFlagIcons.java @@ -0,0 +1,40 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.gfx.CountryFlags; + +import javax.swing.ImageIcon; +import java.awt.Image; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +/** TeamSpeak's country flags as Swing icons, at their own 16×11 scaled with the interface. */ +final class CountryFlagIcons { + + private static final int WIDTH = 16; + private static final int HEIGHT = 11; + private static final Map> ICONS = new ConcurrentHashMap<>(); + + private CountryFlagIcons() { + } + + /** @return the flag, or {@code null} for an unknown or empty code */ + static ImageIcon of(String code) { + if (code == null || code.isEmpty()) return null; + return ICONS.computeIfAbsent(code, CountryFlagIcons::load).orElse(null); + } + + private static Optional load(String code) { + byte[] png = CountryFlags.png(code); + if (png == null) return Optional.empty(); + ImageIcon icon = new ImageIcon(png); + if (icon.getIconWidth() <= 0) return Optional.empty(); + int width = UIScale.scale(WIDTH); + int height = UIScale.scale(HEIGHT); + if (icon.getIconWidth() != width || icon.getIconHeight() != height) { + icon = new ImageIcon(icon.getImage().getScaledInstance(width, height, Image.SCALE_SMOOTH)); + } + return Optional.of(icon); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DescriptionEditorDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DescriptionEditorDialog.java new file mode 100644 index 0000000..0fc5757 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DescriptionEditorDialog.java @@ -0,0 +1,172 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.text.BBCode; + +import javax.swing.Box; +import javax.swing.JButton; +import javax.swing.JColorChooser; +import javax.swing.JDialog; +import javax.swing.JEditorPane; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JToggleButton; +import javax.swing.JToolBar; +import java.awt.BorderLayout; +import java.awt.CardLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Window; + +/** + * The description editor TeamSpeak tears off the channel dialog: the raw BBCode plus + * the handful of formatting buttons it offers (bold, italic, underline, colour) and a + * preview that renders the text the way the info panel will. + * + *

    Formatting works on the selection, wrapping it in the tag pair; with nothing + * selected the pair is inserted and the caret placed between the two halves, so typing + * continues inside it. + */ +final class DescriptionEditorDialog extends JDialog { + + private static final String EDIT_CARD = "edit"; + private static final String PREVIEW_CARD = "preview"; + + private final JTextArea area = new JTextArea(); + private final JEditorPane preview = new JEditorPane("text/html", ""); + private final CardLayout cards = new CardLayout(); + private final JPanel body = new JPanel(cards); + private final JToggleButton previewButton = new JToggleButton("Preview"); + private boolean accepted; + + DescriptionEditorDialog(Window owner, String description) { + super(owner, "Channel Description", ModalityType.APPLICATION_MODAL); + area.setText(description); + area.setLineWrap(true); + area.setWrapStyleWord(true); + area.setFont(new Font(Font.MONOSPACED, Font.PLAIN, UIScale.scale(12))); + area.setCaretPosition(0); + + preview.setEditable(false); + preview.setBackground(Theme.chatBg()); + preview.setBorder(new ScaledEmptyBorder(6, 8, 6, 8)); + + body.add(new JScrollPane(area), EDIT_CARD); + body.add(new JScrollPane(preview), PREVIEW_CARD); + + JLabel hint = new JLabel("Press Button to \"Preview\" the changes in channel info."); + hint.setForeground(Theme.chatSystem()); + hint.setBorder(new ScaledEmptyBorder(4, 6, 0, 6)); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(buildToolbar(), BorderLayout.NORTH); + getContentPane().add(body, BorderLayout.CENTER); + JPanel south = new JPanel(new BorderLayout()); + south.add(hint, BorderLayout.NORTH); + south.add(buildButtons(), BorderLayout.SOUTH); + getContentPane().add(south, BorderLayout.SOUTH); + + Dialogs.closeOnEscape(this); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + setSize(UIScale.scale(new Dimension(520, 380))); + setMinimumSize(UIScale.scale(new Dimension(360, 260))); + setLocationRelativeTo(owner); + } + + /** @return whether the user confirmed; {@link #getDescription()} then holds the new text */ + boolean isAccepted() { + return accepted; + } + + String getDescription() { + return area.getText(); + } + + private JToolBar buildToolbar() { + JToolBar bar = new JToolBar(); + bar.setFloatable(false); + bar.add(tagButton("B", "Bold", Font.BOLD, "[b]", "[/b]")); + bar.add(tagButton("I", "Italic", Font.ITALIC, "[i]", "[/i]")); + JButton underline = tagButton("U", "Underline", Font.PLAIN, "[u]", "[/u]"); + bar.add(underline); + JButton color = new JButton("Color"); + color.setToolTipText("Color"); + color.addActionListener(a -> chooseColor()); + bar.add(square(color)); + bar.add(Box.createHorizontalGlue()); + previewButton.setToolTipText("Show the description as the info panel renders it"); + previewButton.addActionListener(a -> showPreview(previewButton.isSelected())); + previewButton.setMaximumSize(previewButton.getPreferredSize()); + bar.add(previewButton); + return bar; + } + + private JPanel buildButtons() { + JButton ok = new JButton("OK"); + JButton cancel = new JButton("Cancel"); + ok.addActionListener(a -> { + accepted = true; + dispose(); + }); + cancel.addActionListener(a -> dispose()); + JPanel panel = new JPanel(new BorderLayout()); + JPanel right = new JPanel(); + right.add(ok); + right.add(cancel); + panel.add(right, BorderLayout.EAST); + getRootPane().setDefaultButton(ok); + return panel; + } + + private JButton tagButton(String text, String tip, int style, String open, String close) { + JButton button = new JButton(text); + button.setToolTipText(tip); + button.setFont(button.getFont().deriveFont(style)); + button.addActionListener(a -> wrapSelection(open, close)); + return square(button); + } + + /** + * Pins a toolbar button to its natural size: the tool bar lays its children out along a + * box, which would otherwise let one of them soak up all the free width. + */ + private static JButton square(JButton button) { + Dimension size = new Dimension(Math.max(UIScale.scale(28), button.getPreferredSize().width), + button.getPreferredSize().height); + button.setPreferredSize(size); + button.setMaximumSize(size); + return button; + } + + private void chooseColor() { + Color chosen = JColorChooser.showDialog(this, "Color", Color.BLACK); + if (chosen == null) return; + wrapSelection(String.format("[color=#%02x%02x%02x]", + chosen.getRed(), chosen.getGreen(), chosen.getBlue()), "[/color]"); + } + + /** Wraps the selection (or the caret) in a BBCode tag pair and returns focus to the text. */ + private void wrapSelection(String open, String close) { + if (previewButton.isSelected()) showPreview(false); + int start = area.getSelectionStart(); + int end = area.getSelectionEnd(); + String selected = area.getSelectedText(); + area.replaceRange(open + (selected == null ? "" : selected) + close, start, end); + area.setCaretPosition(start + open.length() + (selected == null ? 0 : selected.length())); + area.requestFocusInWindow(); + } + + private void showPreview(boolean on) { + previewButton.setSelected(on); + if (on) { + preview.setText("" + + BBCode.toHtml(area.getText()) + ""); + preview.setCaretPosition(0); + } + cards.show(body, on ? PREVIEW_CARD : EDIT_CARD); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DescriptionPictures.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DescriptionPictures.java new file mode 100644 index 0000000..bea7f26 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DescriptionPictures.java @@ -0,0 +1,166 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.myts.ChatAttachment; +import eu.lixko.ts3j.client.net.PictureDownloads; +import eu.lixko.ts3j.client.text.BBCode; +import eu.lixko.ts3j.client.text.ChatHtml; + +import javax.imageio.ImageIO; +import javax.imageio.ImageReader; +import javax.imageio.stream.ImageInputStream; +import java.awt.Dimension; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Shows the pictures of description HTML as the info views can: from the downloads' files, + * narrowed to fit, with a loading icon while one comes. With pictures turned off, or when one + * cannot be had, it is a link to the picture behind a picture icon instead. + */ +final class DescriptionPictures { + + /** A picture, and the links it may sit in. */ + private static final Pattern TAG = Pattern.compile( + "|]*href=\"([^\"]*)\"[^>]*>|", Pattern.CASE_INSENSITIVE); + private static final int ICON = 16; + + private final PictureDownloads downloads; + private final Settings settings; + private final Map sizes = new ConcurrentHashMap<>(); + + DescriptionPictures(PictureDownloads downloads, Settings settings) { + this.downloads = downloads; + this.settings = settings; + } + + static boolean hasPictures(String html) { + return html.contains(" urls(String html) { + List urls = new ArrayList<>(); + Matcher m = TAG.matcher(html); + while (m.find()) { + if (m.group(1) != null) urls.add(unescape(m.group(1))); + } + return urls; + } + + /** + * How the pictures stand, one letter each: it changes when one of them comes or fails, + * and asks for those not on their way yet. + */ + String state(List urls) { + if (!settings.descriptionPictures) return ""; + StringBuilder state = new StringBuilder(urls.size()); + for (String url : urls) { + state.append(downloads.get(url) != null ? 'y' : downloads.failed(url) ? 'n' : '-'); + } + return state.toString(); + } + + private String picture(String url, String anchor, String href, int maxWidth, int maxHeight) { + if (!settings.descriptionPictures) return link("ICONVIEWER", url, anchor, href); + File file = downloads.get(url); + if (file == null) { + return downloads.failed(url) ? link("BROKEN_IMAGE", url, anchor, href) : icon("LOADING_IMAGE"); + } + Dimension size = sizes.computeIfAbsent(file, DescriptionPictures::read); + if (size.width <= 0 || size.height <= 0) return link("BROKEN_IMAGE", url, anchor, href); + int width = Math.min(UIScale.scale(size.width), Math.max(1, maxWidth)); + int height = (int) ((long) size.height * width / size.width); + if (height > maxHeight) { + height = Math.max(1, maxHeight); + width = Math.max(1, (int) ((long) size.width * height / size.height)); + } + // Swing frames a picture inside a link unless told not to. + return ""; + } + + /** + * The picture's address as a link behind {@code iconKey}, shortened: Swing never breaks a + * long one, so it would widen the view past its edge; a file shared in chat goes by its + * name. Inside another link, that link is closed around it and shown after it, so it is + * not lost with the picture that carried it. + */ + private static String link(String iconKey, String url, String anchor, String href) { + ChatAttachment.Ref attachment = ChatAttachment.Ref.parse(url); + String label = attachment != null ? attachment.fileName() : BBCode.shortAddress(url); + String linkClass = attachment != null ? ChatHtml.ATTACHMENT_CLASS : BBCode.linkClass(url); + // A link to the picture itself already is the link this would be. + if (anchor != null && href.equals(url)) return icon(iconKey) + BBCode.escape(label); + String own = icon(iconKey) + "" + + BBCode.escape(label) + ""; + if (anchor == null) return own; + return "" + own + " " + anchor + BBCode.escape(href) + "" + anchor; + } + + private static String icon(String key) { + int size = UIScale.scale(ICON); + File file = IconFiles.of(key, size); + if (file == null) return ""; + return " "; + } + + /** The picture's size in pixels, read from its header; zero when it is no picture Swing can show. */ + private static Dimension read(File file) { + try (ImageInputStream in = ImageIO.createImageInputStream(file)) { + Iterator readers = in == null ? null : ImageIO.getImageReaders(in); + if (readers == null || !readers.hasNext()) return new Dimension(); + ImageReader reader = readers.next(); + try { + reader.setInput(in); + return new Dimension(reader.getWidth(0), reader.getHeight(0)); + } finally { + reader.dispose(); + } + } catch (IOException e) { + return new Dimension(); + } + } + + private static String unescape(String s) { + return s.replace("<", "<").replace(">", ">").replace(""", "\"").replace("&", "&"); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesignPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesignPanel.java new file mode 100644 index 0000000..677d80a --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesignPanel.java @@ -0,0 +1,282 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.gfx.IconPack; + +import javax.swing.DefaultListCellRenderer; +import javax.swing.DefaultListModel; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JFileChooser; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextField; +import javax.swing.SwingConstants; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.io.File; +import java.util.Arrays; + +/** + * Options page for how the client looks: the light or dark look-and-feel, the interface + * scale, the channel tree's flags and row colours, and the icon pack the user interface is drawn with — where to look for more of + * them, and a viewer showing everything the active pack contains. + * + *

    Theme and pack apply right away so the change can be seen in the window behind the + * dialog; cancelling puts the previous ones back. The scale is only read at startup. + */ +final class DesignPanel extends JPanel { + + /** Size of the tiles in the icon viewer. */ + private static final int PREVIEW_SIZE = 32; + private static final int TILE = 44; + + /** Stands for "no pack": the icons the client draws itself. */ + private static final String BUILT_IN = "Plain (drawn by the client)"; + + /** The scale factors offered besides following the desktop (0). */ + private static final double[] SCALES = {0, 1, 1.25, 1.5, 1.75, 2, 2.5, 3}; + + private final Settings settings; + /** What {@link #revert()} goes back to: as the dialog opened, or as last applied. */ + private String originalPackId; + private String originalPackDir; + private Settings.Appearance originalAppearance; + + private final JComboBox appearanceCombo = + new JComboBox<>(Settings.Appearance.values()); + private final JComboBox scaleCombo = new JComboBox<>(); + private final JComboBox packCombo = new JComboBox<>(); + private final JLabel packInfo = new JLabel(); + private final JTextField packDirField; + private final JCheckBox countryFlags = new JCheckBox("Show country flags in the channel tree"); + private final RowColorCombo anyColor; + private final RowColorCombo talkingColor; + private final RowColorCombo mutedAwayColor; + private final DefaultListModel previewModel = new DefaultListModel<>(); + private final JList preview = new JList<>(previewModel); + + DesignPanel(Settings settings) { + super(new BorderLayout(0, UIScale.scale(8))); + this.settings = settings; + this.originalPackId = settings.iconPack; + this.originalPackDir = settings.iconPackDir; + this.originalAppearance = settings.appearance; + this.packDirField = new JTextField(settings.iconPackDir, 18); + this.anyColor = new RowColorCombo(settings.clientRowColors.any); + this.talkingColor = new RowColorCombo(settings.clientRowColors.talking); + this.mutedAwayColor = new RowColorCombo(settings.clientRowColors.mutedAway); + + setBorder(new ScaledEmptyBorder(12, 12, 12, 12)); + add(buildHeader(), BorderLayout.NORTH); + add(buildPreview(), BorderLayout.CENTER); + + reloadPacks(); + } + + /** Copies the chosen appearance and pack into the settings; the caller saves them. */ + void apply() { + settings.appearance = selectedAppearance(); + if (scaleCombo.getSelectedItem() instanceof Double scale) settings.uiScale = scale; + settings.iconPackDir = packDirField.getText().trim(); + Object selected = packCombo.getSelectedItem(); + settings.iconPack = selected instanceof IconPack pack ? pack.id() : ""; + settings.countryFlags = countryFlags.isSelected(); + settings.clientRowColors.any = anyColor.value(); + settings.clientRowColors.talking = talkingColor.value(); + settings.clientRowColors.mutedAway = mutedAwayColor.value(); + originalPackId = settings.iconPack; + originalPackDir = settings.iconPackDir; + originalAppearance = settings.appearance; + } + + /** Puts back the appearance and pack last applied, for a cancelled edit. */ + void revert() { + settings.iconPack = originalPackId; + settings.iconPackDir = originalPackDir; + IconTheme.get().reload(settings); + if (settings.appearance != originalAppearance) { + settings.appearance = originalAppearance; + LookAndFeelManager.switchTo(originalAppearance); + } + } + + // ---- layout ---- + + private JComponent buildHeader() { + JPanel p = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + c.insets = UIScale.scale(new Insets(4, 4, 4, 4)); + c.anchor = GridBagConstraints.WEST; + c.fill = GridBagConstraints.HORIZONTAL; + + packCombo.setToolTipText("Icon packs installed here or in a TeamSpeak 3 client"); + packCombo.addActionListener(e -> onPackSelected()); + packCombo.setRenderer(new DefaultListCellRenderer() { + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, + boolean selected, boolean focus) { + super.getListCellRendererComponent(list, value, index, selected, focus); + setText(value instanceof IconPack pack ? pack.name() : String.valueOf(value)); + return this; + } + }); + + appearanceCombo.setToolTipText("Light or dark window colours"); + appearanceCombo.setSelectedItem(settings.appearance); + appearanceCombo.setRenderer(new DefaultListCellRenderer() { + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, + boolean selected, boolean focus) { + super.getListCellRendererComponent(list, value, index, selected, focus); + setText(value == Settings.Appearance.DARK ? "Dark" : "Light"); + return this; + } + }); + appearanceCombo.addActionListener(e -> onAppearanceSelected()); + + JPanel dirRow = new JPanel(new BorderLayout(UIScale.scale(6), 0)); + JButton browse = new JButton("Browse…"); + browse.addActionListener(e -> browseForPackFolder()); + dirRow.add(packDirField, BorderLayout.CENTER); + dirRow.add(browse, BorderLayout.EAST); + packDirField.setToolTipText("Extra folder to look for icon packs in"); + packInfo.setEnabled(false); + countryFlags.setSelected(settings.countryFlags); + + int row = 0; + FormPanel.addSection(p, c, row++, "Appearance"); + FormPanel.addRow(p, c, row++, new JLabel("Theme:"), appearanceCombo); + if (DisplayScale.isManaged()) { + buildScaleCombo(); + FormPanel.addRow(p, c, row++, new JLabel("Interface scale:"), scaleCombo); + } + FormPanel.addSection(p, c, row++, "Channel Tree"); + FormPanel.addWide(p, c, row++, countryFlags); + FormPanel.addRow(p, c, row++, new JLabel("Client background:"), anyColor); + FormPanel.addRow(p, c, row++, new JLabel("While talking:"), talkingColor); + FormPanel.addRow(p, c, row++, new JLabel("Muted / away:"), mutedAwayColor); + FormPanel.addSection(p, c, row++, "Icon Pack"); + FormPanel.addRow(p, c, row++, new JLabel("Icon pack:"), packCombo); + c.gridx = 1; + c.gridy = row++; + p.add(packInfo, c); + FormPanel.addRow(p, c, row, new JLabel("Extra pack folder:"), dirRow); + return p; + } + + private void buildScaleCombo() { + for (double scale : SCALES) scaleCombo.addItem(scale); + if (settings.uiScale > 0 && Arrays.stream(SCALES).noneMatch(s -> s == settings.uiScale)) { + scaleCombo.addItem(settings.uiScale); + } + scaleCombo.setSelectedItem(Math.max(0, settings.uiScale)); + scaleCombo.setToolTipText("Size of text, icons and controls; takes effect after a restart"); + scaleCombo.setRenderer(new DefaultListCellRenderer() { + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, + boolean selected, boolean focus) { + super.getListCellRendererComponent(list, value, index, selected, focus); + double scale = value instanceof Double d ? d : 0; + setText(scale > 0 ? percent(scale) + : "Automatic (" + percent(DisplayScale.detected()) + ")"); + return this; + } + }); + } + + private static String percent(double scale) { + return Math.round(scale * 100) + "%"; + } + + private JComponent buildPreview() { + preview.setLayoutOrientation(JList.HORIZONTAL_WRAP); + preview.setVisibleRowCount(-1); + preview.setFixedCellWidth(UIScale.scale(TILE)); + preview.setFixedCellHeight(UIScale.scale(TILE)); + preview.setCellRenderer(new DefaultListCellRenderer() { + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, + boolean selected, boolean focus) { + super.getListCellRendererComponent(list, value, index, selected, focus); + String key = String.valueOf(value); + ImageIcon icon = Icons.of(key, UIScale.scale(PREVIEW_SIZE)); + setText(""); + setIcon(icon); + setToolTipText(key); + setHorizontalAlignment(SwingConstants.CENTER); + return this; + } + }); + + JScrollPane scroll = new JScrollPane(preview); + scroll.setPreferredSize(UIScale.scale(new Dimension(360, 200))); + return scroll; + } + + // ---- behaviour ---- + + private void reloadPacks() { + IconTheme theme = IconTheme.get(); + theme.reload(settings); + // Filling the combo box changes its selection, and with it the active pack, + // so remember the one the settings asked for before touching it. + IconPack selected = theme.activePack(); + + packCombo.removeAllItems(); + packCombo.addItem(BUILT_IN); + for (IconPack pack : theme.packs()) packCombo.addItem(pack); + packCombo.setSelectedItem(selected == null ? BUILT_IN : selected); + onPackSelected(); + } + + private Settings.Appearance selectedAppearance() { + Object selected = appearanceCombo.getSelectedItem(); + return selected instanceof Settings.Appearance a ? a : Settings.Appearance.LIGHT; + } + + private void onAppearanceSelected() { + Settings.Appearance chosen = selectedAppearance(); + if (chosen == settings.appearance) return; + settings.appearance = chosen; + LookAndFeelManager.switchTo(chosen); + } + + private void onPackSelected() { + Object selected = packCombo.getSelectedItem(); + IconPack pack = selected instanceof IconPack p ? p : null; + IconTheme.get().setPack(pack); + + previewModel.clear(); + if (pack == null) { + packInfo.setText("Drawn by the client itself"); + } else { + for (String key : pack.keys()) previewModel.addElement(key); + packInfo.setText(pack.keys().size() + " icons" + + (pack.fallsBack() ? ", missing ones from the default pack" : "")); + } + } + + private void browseForPackFolder() { + JFileChooser chooser = new JFileChooser(); + chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + chooser.setDialogTitle("Folder containing icon packs"); + String current = packDirField.getText().trim(); + if (!current.isEmpty()) chooser.setCurrentDirectory(new File(current)); + if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return; + packDirField.setText(chooser.getSelectedFile().getAbsolutePath()); + settings.iconPackDir = packDirField.getText(); + reloadPacks(); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesktopEntry.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesktopEntry.java new file mode 100644 index 0000000..0dea2cc --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesktopEntry.java @@ -0,0 +1,140 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.Main; +import eu.lixko.ts3j.client.session.ServerLink; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.Arrays; +import java.util.Locale; + +/** + * Installs a freedesktop launcher for the client in the user's applications folder. + * + *

    Task bars find the launcher belonging to a window through its {@code WM_CLASS} + * ({@link WindowClass}), matched against {@code StartupWMClass}. When no launcher + * claims the class, Plasma falls back to the process's command line — {@code java} — + * and files the window under whatever launcher runs Java, with its name and icon. + * + *

    A launcher run from a jar also takes {@code ts3server://} links. + * + *

    The files are only rewritten when their content changes, e.g. after the jar moved. + * {@code -Dts3j.desktopEntry=false} turns this off. + */ +public final class DesktopEntry { + + private static final int ICON_SIZE = 256; + + private DesktopEntry() { + } + + /** Call on the event thread. */ + public static void install() { + if (!System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("linux") + || !Boolean.parseBoolean(System.getProperty("ts3j.desktopEntry", "true"))) { + return; + } + try { + Path data = dataHome(); + Path icon = icon(); + writeIfChanged(icon, iconPng()); + Path applications = data.resolve("applications"); + if (writeIfChanged(applications.resolve(WindowClass.NAME + ".desktop"), + entry(icon).getBytes(StandardCharsets.UTF_8))) { + updateSchemeHandlers(applications); + } + } catch (IOException | RuntimeException e) { + System.err.println("Cannot install the desktop entry: " + e); + } + } + + /** The application icon the entry names, which desktop notifications show too. */ + static Path icon() { + return dataHome().resolve("icons").resolve(WindowClass.NAME + ".png"); + } + + private static Path dataHome() { + String xdg = System.getenv("XDG_DATA_HOME"); + if (xdg != null && !xdg.isBlank()) return Path.of(xdg); + return Path.of(System.getProperty("user.home"), ".local", "share"); + } + + private static String entry(Path icon) { + String exec = launchCommand(); + StringBuilder s = new StringBuilder() + .append("[Desktop Entry]\n") + .append("Type=Application\n") + .append("Name=TeamSpook TS3j\n") + .append("GenericName=TeamSpeak 3 Client\n") + .append("Comment=Voice chat on TeamSpeak 3 servers\n") + .append("Icon=").append(icon).append('\n') + .append("Exec=").append(exec == null ? "java" : exec + " %u").append('\n') + .append("StartupWMClass=").append(WindowClass.NAME).append('\n') + .append("Categories=Network;InstantMessaging;AudioVideo;\n") + .append("Terminal=false\n"); + // Run from classes (an IDE, mvn exec:java) there is nothing sensible to launch; + // the entry is still needed to name the window, but stays out of the menu. + if (exec == null) s.append("NoDisplay=true\n"); + else s.append("MimeType=x-scheme-handler/").append(ServerLink.SCHEME).append(";\n"); + return s.toString(); + } + + /** {@code java -jar }, or {@code null} when not running from a jar. */ + private static String launchCommand() { + try { + Path jar = Path.of(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI()); + if (!jar.toString().endsWith(".jar")) return null; + String java = ProcessHandle.current().info().command().orElse("java"); + return quote(java) + " -jar " + quote(jar.toAbsolutePath().toString()); + } catch (URISyntaxException | RuntimeException e) { + return null; + } + } + + /** Quotes an Exec argument as the Desktop Entry spec asks. */ + private static String quote(String arg) { + arg = arg.replace("%", "%%"); + if (arg.chars().noneMatch(c -> " \t\"'\\`$;&|<>()*?#~".indexOf(c) >= 0)) return arg; + String escaped = arg.replaceAll("([\"`$\\\\])", "\\\\$1"); + // The whole value is also a desktop-file string, where a backslash is escaped again. + return ("\"" + escaped + "\"").replace("\\", "\\\\"); + } + + private static byte[] iconPng() throws IOException { + BufferedImage img = new BufferedImage(ICON_SIZE, ICON_SIZE, BufferedImage.TYPE_INT_ARGB); + Icons.app(ICON_SIZE).paintIcon(null, img.getGraphics(), 0, 0); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ImageIO.write(img, "png", out); + return out.toByteArray(); + } + + /** + * Browsers find the handler of a {@code ts3server://} link in the folder's MIME cache, which + * only this tool rebuilds; without it the entry still names the window. + */ + private static void updateSchemeHandlers(Path applications) { + try { + new ProcessBuilder("update-desktop-database", applications.toString()) + .redirectErrorStream(true).redirectOutput(ProcessBuilder.Redirect.DISCARD).start(); + } catch (IOException ignored) { + } + } + + /** @return whether the file changed */ + private static boolean writeIfChanged(Path file, byte[] content) throws IOException { + if (Files.exists(file) && Arrays.equals(Files.readAllBytes(file), content)) return false; + Files.createDirectories(file.getParent()); + Path tmp = file.resolveSibling(file.getFileName() + ".tmp"); + Files.write(tmp, content); + Files.move(tmp, file, StandardCopyOption.REPLACE_EXISTING, + StandardCopyOption.ATOMIC_MOVE); + return true; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesktopNotifier.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesktopNotifier.java new file mode 100644 index 0000000..559976e --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesktopNotifier.java @@ -0,0 +1,159 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.net.ConnectionListener.ChatScope; +import eu.lixko.ts3j.client.notify.desktop.DesktopNotifications; +import eu.lixko.ts3j.client.notify.desktop.DesktopNotifications.Notice; +import eu.lixko.ts3j.client.notify.desktop.FreedesktopNotifications; +import eu.lixko.ts3j.client.text.BBCode; +import eu.lixko.ts3j.client.text.ChatHtml; +import eu.lixko.ts3j.client.ui.tray.AwtTray; + +import javax.swing.SwingUtilities; +import java.awt.KeyboardFocusManager; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * Tells the user about pokes and private messages through the desktop's notifications + * while none of the client's windows has the focus. A private conversation keeps one + * notification, updated as messages come; all of them go once the window is back in + * front, as they have then been seen. + * + *

    Called on the event thread. Talking to the desktop may block, so that happens on a + * thread of its own, which also keeps the notifications in order. + */ +final class DesktopNotifier { + + private static final int MAX_LINES = 5; + + private final MainFrame frame; + private final Settings settings; + private final ExecutorService worker = Executors.newSingleThreadExecutor(r -> { + Thread t = new Thread(r, "notifications"); + t.setDaemon(true); + return t; + }); + + /** Found on first use, on the worker; {@code null} where the desktop offers none. */ + private DesktopNotifications backend; + private boolean resolved; + + /** One notification per private conversation; touched on the worker only. */ + private final Map conversations = new HashMap<>(); + private final List pokes = new ArrayList<>(); + + private record Conversation(ServerTab tab, int clientId) { + } + + private static final class Shown { + final List lines = new ArrayList<>(); + int id; + } + + DesktopNotifier(MainFrame frame, Settings settings) { + this.frame = frame; + this.settings = settings; + } + + void poke(ServerTab tab, String from, String message) { + if (!wanted()) return; + String body = BBCode.toPlain(message); + Notice notice = new Notice(from + " poked you", body, () -> open(tab, null), null); + worker.execute(() -> { + DesktopNotifications out = backend(); + if (out == null) return; + int id = out.show(notice, 0); + if (id != 0) pokes.add(id); + }); + } + + void privateMessage(ServerTab tab, int clientId, String from, String message) { + if (!wanted()) return; + String text = ChatHtml.plainMessage(message); + Conversation key = new Conversation(tab, clientId); + worker.execute(() -> { + DesktopNotifications out = backend(); + if (out == null) return; + Shown shown = conversations.computeIfAbsent(key, k -> new Shown()); + shown.lines.add(text); + if (shown.lines.size() > MAX_LINES) shown.lines.removeFirst(); + Notice notice = new Notice(from, String.join("\n", shown.lines), + () -> open(tab, clientId), reply -> reply(tab, clientId, reply)); + shown.id = out.show(notice, shown.id); + }); + } + + /** The window is in front again: what was notified of is in plain sight. */ + void windowActivated() { + worker.execute(() -> { + if (backend == null) return; + conversations.values().forEach(shown -> backend.close(shown.id)); + conversations.clear(); + pokes.forEach(backend::close); + pokes.clear(); + }); + } + + /** A private chat on a server that went away can neither be opened nor answered. */ + void forget(ServerTab tab) { + worker.execute(() -> conversations.entrySet().removeIf(e -> { + if (e.getKey().tab() != tab) return false; + if (backend != null) backend.close(e.getValue().id); + return true; + })); + } + + void shutdown() { + worker.execute(() -> { + if (backend != null) backend.shutdown(); + }); + worker.shutdown(); + } + + private boolean wanted() { + // Some window of ours has the focus exactly when there is an active window. + return settings.desktopNotifications + && KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow() == null; + } + + private DesktopNotifications backend() { + if (!resolved) { + resolved = true; + backend = create(); + } + return backend; + } + + /** The desktop's notification service on Linux; elsewhere the tray icon's messages. */ + private DesktopNotifications create() { + if (System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("linux")) { + DesktopNotifications service = FreedesktopNotifications.connect( + "TeamSpook TS3j", WindowClass.NAME, DesktopEntry.icon().toString()); + if (service != null) return service; + } + return frame.awtTray() instanceof AwtTray tray ? new TrayNotifications(tray) : null; + } + + private void open(ServerTab tab, Integer clientId) { + SwingUtilities.invokeLater(() -> { + frame.bringToFront(); + frame.selectTab(tab); + if (clientId != null) { + var client = tab.connection().getModel().getClient(clientId); + if (client != null) tab.chat().openPrivateChat(clientId, client.uniqueId, client.nickname); + } + }); + } + + private void reply(ServerTab tab, int clientId, String text) { + SwingUtilities.invokeLater(() -> { + if (tab.session().isConnected()) tab.session().sendChat(ChatScope.PRIVATE, clientId, text); + }); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/Dialogs.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/Dialogs.java new file mode 100644 index 0000000..48d2d68 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/Dialogs.java @@ -0,0 +1,44 @@ +package eu.lixko.ts3j.client.ui; + +import javax.swing.AbstractAction; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JRootPane; +import javax.swing.KeyStroke; +import java.awt.event.ActionEvent; +import java.awt.event.KeyEvent; + +/** Behaviour shared by the client's dialogs. */ +final class Dialogs { + + private Dialogs() { + } + + /** + * Makes Escape close a dialog, the way Swing's own option panes do. + * + *

    The binding lives on the root pane's window-wide input map, so it fires + * wherever the focus sits — but only where nothing nearer to the focused + * component claims Escape first, which is what leaves a table's or combo + * box's own "cancel the edit" behaviour intact. + */ + static void closeOnEscape(JDialog dialog) { + closeOnEscape(dialog, dialog::dispose); + } + + /** + * Binds Escape to the dialog's own way of closing, for dialogs that have to + * tidy up (or discard edits) on the way out. + */ + static void closeOnEscape(JDialog dialog, Runnable close) { + JRootPane root = dialog.getRootPane(); + root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) + .put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "ts3-close"); + root.getActionMap().put("ts3-close", new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + close.run(); + } + }); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DisplayScale.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DisplayScale.java new file mode 100644 index 0000000..69916ef --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DisplayScale.java @@ -0,0 +1,134 @@ +package eu.lixko.ts3j.client.ui; + +import java.awt.Toolkit; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Locale; + +/** + * Decides how large the user interface is drawn on Linux, where Java2D only knows + * whole-number scale factors: asked for 150 %, it draws at 100 % — or, told + * 2 by the desktop, at 200 %, while FlatLaf's own scaling goes on top of that. + * + *

    So on Linux Java2D is pinned to 1 and the whole factor, fractional or not, is + * handed to FlatLaf, which scales fonts and its own metrics; the client scales its own + * sizes through FlatLaf's {@link com.formdev.flatlaf.util.UIScale} to match. + * + *

    The desktop's factor is read the way an X11 toolkit would learn it: + *

      + *
    1. {@code Xft/DPI} from XSETTINGS — GNOME and Plasma (through xsettingsd) publish + * the device-pixel DPI there, fractional scale and text scaling included;
    2. + *
    3. KWin's {@code [Xwayland] Scale}, which Plasma sets when X11 apps are left to + * scale themselves — for sessions with no XSETTINGS daemon running;
    4. + *
    5. {@code GDK_SCALE}, which Java2D would otherwise have honoured itself.
    6. + *
    + * With the compositor scaling X11 apps (GNOME's default, and Plasma's "Scaled by the + * system") the client sees 96 DPI and is drawn at 100 %, which is what those + * modes expect; they then upscale the window, blurry but the right size. + * + *

    A {@code sun.java2d.uiScale} or {@code flatlaf.uiScale} given on the command line + * turns all of this off. + */ +public final class DisplayScale { + + private static final String JAVA2D_SCALE = "sun.java2d.uiScale"; + private static final String FLATLAF_SCALE = "flatlaf.uiScale"; + private static final double BASE_DPI = 96; + private static final double MAX_SCALE = 4; + + private static boolean managed; + private static double detected = 1; + + private DisplayScale() { + } + + /** + * Sets the scale up; call before anything touches AWT. + * + * @param override the user's chosen factor, or 0 to follow the desktop + */ + public static void configure(double override) { + if (!isLinux() || System.getProperty(JAVA2D_SCALE) != null + || System.getProperty(FLATLAF_SCALE) != null) { + return; + } + System.setProperty(JAVA2D_SCALE, "1"); + managed = true; + detected = detect(); + double factor = override > 0 ? override : detected; + System.setProperty(FLATLAF_SCALE, Double.toString(factor)); + } + + /** Whether the client sets the scale itself, so that the user may choose one. */ + public static boolean isManaged() { + return managed; + } + + /** The desktop's factor, as found at startup. */ + public static double detected() { + return detected; + } + + private static double detect() { + double scale = xftScale(); + if (scale <= 0) scale = kwinXwaylandScale(); + scale = Math.max(scale, gdkScale()); + return Math.max(1, Math.min(MAX_SCALE, scale)); + } + + private static double xftScale() { + // The XSETTINGS value is in 1024ths of a DPI; -1 means "unset". + Object dpi = Toolkit.getDefaultToolkit().getDesktopProperty("gnome.Xft/DPI"); + return dpi instanceof Integer d && d > 0 ? d / 1024.0 / BASE_DPI : 0; + } + + private static double kwinXwaylandScale() { + // Left behind by a Wayland session, the key would be stale in an X11 one. + if (System.getenv("WAYLAND_DISPLAY") == null) return 0; + String configHome = System.getenv("XDG_CONFIG_HOME"); + Path kwinrc = (configHome == null || configHome.isEmpty() + ? Path.of(System.getProperty("user.home"), ".config") + : Path.of(configHome)).resolve("kwinrc"); + try { + return parseDouble(iniValue(Files.readAllLines(kwinrc), "Xwayland", "Scale")); + } catch (IOException e) { + return 0; + } + } + + private static double gdkScale() { + return parseDouble(System.getenv("GDK_SCALE")); + } + + /** The value of {@code key} in {@code [group]} of a KConfig-style file, or {@code null}. */ + static String iniValue(List lines, String group, String key) { + boolean inGroup = false; + for (String line : lines) { + String t = line.trim(); + if (t.startsWith("[")) { + inGroup = t.equals("[" + group + "]"); + } else if (inGroup) { + int eq = t.indexOf('='); + if (eq > 0 && t.substring(0, eq).trim().equals(key)) { + return t.substring(eq + 1).trim(); + } + } + } + return null; + } + + private static double parseDouble(String s) { + if (s == null) return 0; + try { + return Double.parseDouble(s.trim()); + } catch (NumberFormatException e) { + return 0; + } + } + + private static boolean isLinux() { + return System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("linux"); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DropDownToggleButton.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DropDownToggleButton.java new file mode 100644 index 0000000..8bcc9e2 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DropDownToggleButton.java @@ -0,0 +1,122 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.UIScale; + +import javax.swing.BorderFactory; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.JToggleButton; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Insets; +import java.awt.RenderingHints; +import java.awt.event.ActionListener; +import java.util.function.Supplier; + +/** + * A toolbar toggle button with a small arrow next to it that opens a menu: + * clicking the button toggles, clicking the arrow offers the related actions. + * + *

    The menu is built on every click by the supplier, so it can reflect the + * current state (checked items, the presets that exist right now). + */ +public final class DropDownToggleButton extends JPanel { + + private final JToggleButton button = new JToggleButton(); + private final JButton arrow = new JButton(new ArrowIcon()); + + public DropDownToggleButton(Icon icon, String tooltip, Supplier menu) { + super(new BorderLayout()); + setOpaque(false); + // Sitting inside this panel, the halves are not toolbar children any more, so the + // look and feel would paint them as filled buttons; ask for the flat toolbar look + // the plain toggles next to us get. + button.putClientProperty("JButton.buttonType", "toolBarButton"); + arrow.putClientProperty("JButton.buttonType", "toolBarButton"); + button.setIcon(icon); + button.setToolTipText(tooltip); + + arrow.setToolTipText(tooltip); + arrow.setMargin(new Insets(0, 2, 0, 2)); + arrow.setFocusable(false); + arrow.addActionListener(e -> { + JPopupMenu popup = menu.get(); + if (popup != null) popup.show(this, 0, getHeight()); + }); + + // Keep the whole control the size of a plain toolbar button: the arrow's + // width comes out of the toggle half instead of being added to it. + Dimension plain = button.getPreferredSize(); + button.setPreferredSize(new Dimension( + Math.max(icon.getIconWidth() + UIScale.scale(8), plain.width - arrow.getPreferredSize().width), + plain.height)); + + add(button, BorderLayout.CENTER); + add(arrow, BorderLayout.EAST); + } + + /** Listener for the toggle half only; the arrow half opens the menu instead. */ + public void addActionListener(ActionListener l) { + button.addActionListener(l); + } + + public boolean isSelected() { + return button.isSelected(); + } + + public void setSelected(boolean selected) { + button.setSelected(selected); + } + + public void setIcon(Icon icon) { + button.setIcon(icon); + } + + @Override + public void setEnabled(boolean enabled) { + super.setEnabled(enabled); + button.setEnabled(enabled); + arrow.setEnabled(enabled); + } + + /** Disables the toggle half on its own, leaving the menu reachable. */ + public void setToggleEnabled(boolean enabled) { + button.setEnabled(enabled); + } + + @Override + public Dimension getMaximumSize() { + return getPreferredSize(); // keep the toolbar from stretching us + } + + /** The downward triangle on the menu half of the button. */ + private static final class ArrowIcon implements Icon { + + @Override + public void paintIcon(Component c, Graphics g0, int x, int y) { + Graphics2D g = (Graphics2D) g0.create(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(c.isEnabled() ? Color.DARK_GRAY : Color.GRAY); + int[] xs = {x, x + getIconWidth(), x + getIconWidth() / 2}; + int[] ys = {y, y, y + getIconHeight()}; + g.fillPolygon(xs, ys, 3); + g.dispose(); + } + + @Override + public int getIconWidth() { + return UIScale.scale(7); + } + + @Override + public int getIconHeight() { + return UIScale.scale(4); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DropIndicatorTree.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DropIndicatorTree.java new file mode 100644 index 0000000..ea48caa --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DropIndicatorTree.java @@ -0,0 +1,342 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.net.ChannelNode; +import eu.lixko.ts3j.client.net.Spacers; +import eu.lixko.ts3j.client.net.ClientEntry; +import eu.lixko.ts3j.client.net.ClientStatus; +import eu.lixko.ts3j.client.net.ServerModel; + +import javax.swing.Icon; +import javax.swing.JTree; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.TreeModel; +import javax.swing.tree.TreePath; +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.RenderingHints; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.function.Predicate; + +/** + * The {@link ServerTreePanel} tree, extended to draw where a drag-and-drop would + * land: an insertion line between rows, or an outline around the row that will + * receive the dragged node. Also keeps the server row permanently expanded and + * paints the right-aligned group icon strip, both of which need to hook into + * this component's own paint cycle. + */ +final class DropIndicatorTree extends JTree { + + /** Gap kept between a row's label and the right-aligned icon strip. */ + private static final int BADGE_GAP = 8; + /** Inset of the strip from the visible right edge. */ + private static final int BADGE_MARGIN = 4; + + private final ServerModel model; + private final GroupIcons groupIcons; + private final Settings settings; + /** Set while a drop would move a client into this channel row. */ + private TreePath highlight; + /** The row the pointer is over, or -1 when it is over none. */ + private int hoverRow = -1; + /** User objects of the rows a find bar matched, compared by identity. */ + private Set searchHits = Collections.emptySet(); + private Predicate pathEditable = path -> false; + + DropIndicatorTree(TreeModel treeModel, ServerModel model, GroupIcons groupIcons, Settings settings) { + super(treeModel); + this.model = model; + this.groupIcons = groupIcons; + this.settings = settings; + MouseAdapter hover = new MouseAdapter() { + @Override + public void mouseMoved(MouseEvent e) { + setHoverRow(rowAt(e.getY())); + } + + @Override + public void mouseDragged(MouseEvent e) { + setHoverRow(-1); + } + + @Override + public void mouseExited(MouseEvent e) { + setHoverRow(-1); + } + }; + addMouseMotionListener(hover); + addMouseListener(hover); + // The selected row is filled across the full width below, before the rows + // themselves are drawn, so this component must not clear its own background. + setOpaque(false); + } + + /** + * The row a point falls on, going by its vertical band alone: a row reaches + * across the whole width, not just as far as its label. + */ + int rowAt(int y) { + int row = getClosestRowForLocation(0, y); + if (row < 0) return -1; + Rectangle bounds = getRowBounds(row); + return bounds != null && y >= bounds.y && y < bounds.y + bounds.height ? row : -1; + } + + /** The path a point falls on, by the same rule as {@link #rowAt(int)}. */ + TreePath pathAt(int y) { + int row = rowAt(y); + return row < 0 ? null : getPathForRow(row); + } + + /** + * Re-reads the row the pointer is over. Scrolling moves the rows under a pointer + * that never moved itself, so the enclosing scroll pane calls this on every scroll. + */ + void refreshHoverRow() { + Point pointer = getMousePosition(); + setHoverRow(pointer == null ? -1 : rowAt(pointer.y)); + } + + private void setHoverRow(int row) { + if (row == hoverRow) return; + repaintRow(hoverRow); + hoverRow = row; + repaintRow(row); + } + + private void repaintRow(int row) { + if (row < 0) return; + Rectangle bounds = getRowBounds(row); + if (bounds != null) repaint(0, bounds.y, getWidth(), bounds.height); + } + + /** Which rows an inline editor may open on; nothing, until one is installed. */ + void setPathEditable(Predicate editable) { + this.pathEditable = editable; + } + + @Override + public boolean isPathEditable(TreePath path) { + return isEditable() && pathEditable.test(path); + } + + /** Keeps the server row permanently open; collapsing it would hide everything. */ + @Override + public void setExpandedState(TreePath path, boolean state) { + if (!state && path.getPathCount() == 1) return; + super.setExpandedState(path, state); + } + + /** + * Widens every repaint request to the full visible width. Swing only asks for + * the row rectangle, which stops short of the right-aligned icon strip and would + * leave it behind when a row's label changes width. + */ + @Override + public void repaint(long tm, int x, int y, int width, int height) { + Rectangle visible = getVisibleRect(); + super.repaint(tm, visible.x, y, visible.width, height); + } + + void setSearchHits(Set hits) { + searchHits = hits; + repaint(); + } + + void highlightChannel(TreePath path) { + if (path == highlight || (path != null && path.equals(highlight))) return; + highlight = path; + repaint(); + } + + @Override + protected void paintComponent(Graphics g) { + Rectangle clip = g.getClipBounds(); + g.setColor(getBackground()); + g.fillRect(clip.x, clip.y, clip.width, clip.height); + paintClientColors(g); + paintSearchHits(g); + paintSelection(g); + paintHover(g); + super.paintComponent(g); + paintBadges(g); + JTree.DropLocation loc = getDropLocation(); + if (loc == null || loc.getPath() == null) return; + + Graphics2D g2 = (Graphics2D) g.create(); + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g2.setColor(Theme.accent()); + if (highlight != null || loc.getChildIndex() < 0) { + Rectangle r = getPathBounds(highlight != null ? highlight : loc.getPath()); + if (r != null) { + g2.setStroke(new BasicStroke(UIScale.scale(2f))); + int arc = UIScale.scale(4); + g2.drawRoundRect(r.x, r.y + 1, r.width - 1, r.height - 3, arc, arc); + } + } else { + Rectangle line = insertLine(loc); + if (line != null) { + int dot = UIScale.scale(7); + g2.fillRect(line.x, line.y - line.height / 2, line.width, line.height); + g2.fillOval(line.x - dot / 2, line.y - dot / 2 - 1, dot, dot); + } + } + g2.dispose(); + } + + /** + * Fills the selected row across the full width, in the colour the cell renderer + * puts behind the label itself, so the selection covers the whole line rather + * than stopping where the name ends. + */ + private void paintSelection(Graphics g) { + int[] rows = getSelectionRows(); + if (rows == null) return; + Rectangle visible = getVisibleRect(); + g.setColor(Theme.treeSelection()); + for (int row : rows) { + Rectangle bounds = getRowBounds(row); + if (bounds != null) g.fillRect(visible.x, bounds.y, visible.width, bounds.height); + } + } + + /** Fills client rows across the full width in the colour chosen for what they are doing. */ + private void paintClientColors(Graphics g) { + Rectangle visible = getVisibleRect(); + int first = Math.max(0, getClosestRowForLocation(visible.x, visible.y)); + for (int row = first; row < getRowCount(); row++) { + Rectangle bounds = getRowBounds(row); + if (bounds == null) continue; + if (bounds.y > visible.y + visible.height) break; + Object obj = ((DefaultMutableTreeNode) getPathForRow(row).getLastPathComponent()).getUserObject(); + if (!(obj instanceof ClientEntry cl)) continue; + int argb = settings.clientRowColors.of(ClientStatus.of(cl)); + if (argb == 0) continue; + g.setColor(new Color(argb, true)); + g.fillRect(visible.x, bounds.y, visible.width, bounds.height); + } + } + + private void paintSearchHits(Graphics g) { + if (searchHits.isEmpty()) return; + Rectangle visible = getVisibleRect(); + int first = Math.max(0, getClosestRowForLocation(visible.x, visible.y)); + g.setColor(Theme.searchMatch()); + for (int row = first; row < getRowCount(); row++) { + Rectangle bounds = getRowBounds(row); + if (bounds == null) continue; + if (bounds.y > visible.y + visible.height) break; + Object obj = ((DefaultMutableTreeNode) getPathForRow(row).getLastPathComponent()).getUserObject(); + if (searchHits.contains(obj)) g.fillRect(visible.x, bounds.y, visible.width, bounds.height); + } + } + + /** + * Washes the row under the pointer across the full width it occupies — the same + * area a click on it acts on. A selected row keeps its selection colour, and + * spacers, which nothing can be done with, are left alone. + */ + private void paintHover(Graphics g) { + if (hoverRow < 0 || getDropLocation() != null || isRowSelected(hoverRow)) return; + Rectangle bounds = getRowBounds(hoverRow); + TreePath path = getPathForRow(hoverRow); + if (bounds == null || path == null || isSpacer(path)) return; + + Rectangle visible = getVisibleRect(); + g.setColor(Theme.hover()); + g.fillRect(visible.x, bounds.y, visible.width, bounds.height); + } + + private boolean isSpacer(TreePath path) { + Object obj = ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); + return obj instanceof ChannelNode && Spacers.isSpacer(((ChannelNode) obj).name); + } + + /** The strip where the insertion line goes, in tree coordinates. */ + private Rectangle insertLine(JTree.DropLocation loc) { + DefaultMutableTreeNode parent = (DefaultMutableTreeNode) loc.getPath().getLastPathComponent(); + int index = loc.getChildIndex(); + if (index < parent.getChildCount()) { + Rectangle r = getPathBounds(loc.getPath().pathByAddingChild(parent.getChildAt(index))); + return r == null ? null : new Rectangle(r.x, r.y, getWidth() - r.x, UIScale.scale(2)); + } + if (parent.getChildCount() == 0) { + Rectangle r = getPathBounds(loc.getPath()); + if (r == null) return null; + int x = r.x + getRowHeight(); + return new Rectangle(x, r.y + r.height, getWidth() - x, UIScale.scale(2)); + } + // Past the last child: below that child's whole (expanded) subtree. + TreePath lastChild = loc.getPath().pathByAddingChild(parent.getChildAt(parent.getChildCount() - 1)); + Rectangle head = getPathBounds(lastChild); + Rectangle tail = getPathBounds(lastVisibleRow(lastChild)); + if (head == null || tail == null) return null; + return new Rectangle(head.x, tail.y + tail.height, getWidth() - head.x, 2); + } + + private TreePath lastVisibleRow(TreePath path) { + int row = getRowForPath(path); + if (row < 0) return path; + for (int i = row + 1; i < getRowCount(); i++) { + if (!path.isDescendant(getPathForRow(i))) break; + row = i; + } + return getPathForRow(row); + } + + /** + * Paints the icons of every visible row — a client's group icons, a channel's + * own icon — flush with the right edge of the viewport, the way TeamSpeak lines + * them up. Drawing them separately from the cell renderer keeps the rows' + * measured widths (and thus the selection highlight) tied to the label alone. + */ + private void paintBadges(Graphics g) { + Rectangle visible = getVisibleRect(); + int right = visible.x + visible.width - UIScale.scale(BADGE_MARGIN); + for (int row = 0; row < getRowCount(); row++) { + Rectangle bounds = getRowBounds(row); + if (bounds == null || bounds.y + bounds.height < visible.y) continue; + if (bounds.y > visible.y + visible.height) break; + + List icons = badgesOf((DefaultMutableTreeNode) getPathForRow(row).getLastPathComponent()); + if (icons.isEmpty()) continue; + + GroupIcons.Row strip = new GroupIcons.Row(icons); + int x = Math.max(bounds.x + bounds.width + UIScale.scale(BADGE_GAP), right - strip.getIconWidth()); + strip.paintIcon(this, g, x, bounds.y + (bounds.height - strip.getIconHeight()) / 2); + } + } + + /** The icon strip a row shows on its right, empty when it has none (yet). */ + private List badgesOf(DefaultMutableTreeNode treeNode) { + Object node = treeNode.getUserObject(); + if (treeNode.isRoot()) { + Icon icon = groupIcons.icon(model.serverIconId()); + return icon == null ? List.of() : List.of(icon); + } + if (node instanceof ClientEntry) { + ClientEntry cl = (ClientEntry) node; + List icons = groupIcons.iconsOf( + model.serverGroupsOf(cl.serverGroupIds), model.channelGroup(cl.channelGroupId)); + // The country's flag comes last, at the row's edge, as in TeamSpeak. + Icon flag = settings.countryFlags ? CountryFlagIcons.of(cl.country) : null; + if (flag != null) icons.add(flag); + return icons; + } + if (node instanceof ChannelNode) { + ChannelNode ch = (ChannelNode) node; + Icon icon = Spacers.isSpacer(ch.name) ? null : groupIcons.icon(ch.iconId); + if (icon != null) return List.of(icon); + } + return List.of(); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/FileBrowserDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/FileBrowserDialog.java new file mode 100644 index 0000000..ec77bb6 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/FileBrowserDialog.java @@ -0,0 +1,482 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.net.ChannelNode; +import eu.lixko.ts3j.client.net.TeamspeakConnection; +import eu.lixko.ts3j.client.net.filetransfer.FileTransfer; +import eu.lixko.ts3j.client.net.filetransfer.RemoteFile; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JFileChooser; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JProgressBar; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.ListSelectionModel; +import javax.swing.SwingUtilities; +import javax.swing.table.AbstractTableModel; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.io.File; +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.List; + +/** + * Browses a channel's file repository and drives uploads and downloads. The table + * lists the current directory; the toolbar navigates and acts on the selection; the + * strip at the bottom shows live progress for each active transfer. + * + *

    All server calls run on background threads so the dialog never blocks the EDT; + * results are marshalled back with {@link SwingUtilities#invokeLater}. + */ +public final class FileBrowserDialog extends JDialog { + + private final TeamspeakConnection conn; + private final int channelId; + private final String channelPassword; + + private final FileTableModel tableModel = new FileTableModel(); + private final JTable table = new JTable(tableModel); + private final JLabel pathLabel = new JLabel("/"); + private final JButton upButton = new JButton("Up", Icons.of("FILE_UP")); + private final JButton downloadButton = new JButton("Download", Icons.of("DOWNLOAD")); + private final JButton deleteButton = new JButton("Delete", Icons.of("DELETE")); + private final JPanel transfersPanel = new JPanel(); + + private volatile String currentPath = "/"; + + public FileBrowserDialog(Frame owner, TeamspeakConnection conn, ChannelNode channel) { + super(owner, "Files — " + channel.name, false); + this.conn = conn; + this.channelId = channel.id; + this.channelPassword = ""; + + JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(8))); + content.setBackground(Theme.windowBg()); + content.setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); + content.add(buildToolbar(), BorderLayout.NORTH); + content.add(buildTable(), BorderLayout.CENTER); + content.add(buildTransfers(), BorderLayout.SOUTH); + setContentPane(content); + + setPreferredSize(UIScale.scale(new Dimension(640, 480))); + pack(); + setLocationRelativeTo(owner); + + refresh(); + } + + // ---- construction ---- + + private JPanel buildToolbar() { + JPanel bar = new JPanel(); + bar.setLayout(new BoxLayout(bar, BoxLayout.X_AXIS)); + bar.setBackground(Theme.windowBg()); + + upButton.addActionListener(e -> navigateUp()); + JButton refresh = new JButton("Refresh", Icons.of("FILE_REFRESH")); + refresh.addActionListener(e -> refresh()); + JButton mkdir = new JButton("New folder", Icons.of("ADD_FOLDER")); + mkdir.addActionListener(e -> createDirectory()); + JButton upload = new JButton("Upload…", Icons.of("UPLOAD")); + upload.addActionListener(e -> chooseUpload()); + downloadButton.addActionListener(e -> downloadSelected()); + deleteButton.addActionListener(e -> deleteSelected()); + + bar.add(upButton); + bar.add(Box.createHorizontalStrut(UIScale.scale(6))); + bar.add(refresh); + bar.add(Box.createHorizontalStrut(UIScale.scale(16))); + bar.add(pathLabel); + bar.add(Box.createHorizontalGlue()); + bar.add(mkdir); + bar.add(Box.createHorizontalStrut(UIScale.scale(6))); + bar.add(upload); + bar.add(Box.createHorizontalStrut(UIScale.scale(6))); + bar.add(downloadButton); + bar.add(Box.createHorizontalStrut(UIScale.scale(6))); + bar.add(deleteButton); + + pathLabel.setFont(Theme.uiFont()); + pathLabel.setForeground(Theme.treeText()); + return bar; + } + + private JScrollPane buildTable() { + table.setFont(Theme.uiFont()); + table.setRowHeight(UIScale.scale(20)); + table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); + table.setFillsViewportHeight(true); + table.getColumnModel().getColumn(0).setPreferredWidth(UIScale.scale(300)); + table.getColumnModel().getColumn(0).setCellRenderer(new NameRenderer()); + table.getColumnModel().getColumn(1).setPreferredWidth(UIScale.scale(90)); + table.getColumnModel().getColumn(2).setPreferredWidth(UIScale.scale(70)); + table.getColumnModel().getColumn(3).setPreferredWidth(UIScale.scale(150)); + table.getSelectionModel().addListSelectionListener(e -> updateButtons()); + table.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) { + int row = table.rowAtPoint(e.getPoint()); + if (row >= 0) openEntry(tableModel.get(row)); + } + } + }); + JScrollPane scroll = new JScrollPane(table); + scroll.getViewport().setBackground(Theme.treeBg()); + return scroll; + } + + private JScrollPane buildTransfers() { + transfersPanel.setLayout(new BoxLayout(transfersPanel, BoxLayout.Y_AXIS)); + transfersPanel.setBackground(Theme.windowBg()); + JScrollPane scroll = new JScrollPane(transfersPanel); + scroll.setBorder(BorderFactory.createTitledBorder("Transfers")); + scroll.setPreferredSize(UIScale.scale(new Dimension(10, 120))); + scroll.getViewport().setBackground(Theme.windowBg()); + return scroll; + } + + // ---- navigation ---- + + private void navigateUp() { + String path = currentPath; + if (path.equals("/")) return; + String trimmed = path.substring(0, path.length() - 1); // drop trailing slash + int slash = trimmed.lastIndexOf('/'); + currentPath = slash <= 0 ? "/" : trimmed.substring(0, slash + 1); + refresh(); + } + + private void openEntry(RemoteFile file) { + if (file == null) return; + if (file.isDirectory()) { + currentPath = currentPath + file.getName() + "/"; + refresh(); + } else { + download(file); + } + } + + /** Reloads the current directory listing from the server. */ + private void refresh() { + pathLabel.setText(currentPath); + upButton.setEnabled(!currentPath.equals("/")); + final String path = currentPath; + new Thread(() -> { + try { + List files = conn.listFiles(channelId, channelPassword, path); + Collections.sort(files, DIRECTORIES_FIRST); + SwingUtilities.invokeLater(() -> { + if (path.equals(currentPath)) tableModel.setFiles(files); + updateButtons(); + }); + } catch (Exception ex) { + SwingUtilities.invokeLater(() -> { + if (path.equals(currentPath)) tableModel.setFiles(new ArrayList<>()); + error("Could not list files", ex); + }); + } + }, "ts3j-ft-list").start(); + } + + private void updateButtons() { + boolean hasSelection = table.getSelectedRowCount() > 0; + deleteButton.setEnabled(hasSelection); + boolean fileSelected = false; + for (int row : table.getSelectedRows()) { + if (!tableModel.get(row).isDirectory()) { + fileSelected = true; + break; + } + } + downloadButton.setEnabled(fileSelected); + } + + // ---- actions ---- + + private void downloadSelected() { + List files = new ArrayList<>(); + for (int row : table.getSelectedRows()) { + RemoteFile f = tableModel.get(row); + if (!f.isDirectory()) files.add(f); + } + if (files.isEmpty()) return; + if (files.size() == 1) { + download(files.get(0)); + return; + } + // Multiple files: pick a target directory once. + JFileChooser chooser = new JFileChooser(); + chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + chooser.setDialogTitle("Download " + files.size() + " files to…"); + if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return; + File dir = chooser.getSelectedFile(); + for (RemoteFile f : files) { + startDownload(f, new File(dir, f.getName())); + } + } + + private void download(RemoteFile file) { + JFileChooser chooser = new JFileChooser(); + chooser.setSelectedFile(new File(file.getName())); + chooser.setDialogTitle("Download " + file.getName()); + if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return; + startDownload(file, chooser.getSelectedFile()); + } + + private void startDownload(RemoteFile file, File target) { + TransferRow row = new TransferRow(); + FileTransfer transfer = conn.downloadFile(channelId, channelPassword, file.getFullPath(), target, + t -> SwingUtilities.invokeLater(() -> row.update(t))); + row.attach(transfer); + addTransferRow(row); + } + + private void chooseUpload() { + JFileChooser chooser = new JFileChooser(); + chooser.setMultiSelectionEnabled(true); + chooser.setDialogTitle("Upload to " + currentPath); + if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return; + for (File source : chooser.getSelectedFiles()) { + if (!source.isFile()) continue; + String remotePath = currentPath + source.getName(); + TransferRow row = new TransferRow(); + FileTransfer transfer = conn.uploadFile(channelId, channelPassword, remotePath, source, true, + t -> SwingUtilities.invokeLater(() -> { + row.update(t); + if (t.getState() == FileTransfer.State.COMPLETED) refresh(); + })); + row.attach(transfer); + addTransferRow(row); + } + } + + private void createDirectory() { + String name = JOptionPane.showInputDialog(this, "New folder name:", "New folder", + JOptionPane.PLAIN_MESSAGE); + if (name == null || name.trim().isEmpty()) return; + final String dirPath = currentPath + name.trim(); + new Thread(() -> { + try { + conn.createDirectory(channelId, channelPassword, dirPath); + SwingUtilities.invokeLater(this::refresh); + } catch (Exception ex) { + SwingUtilities.invokeLater(() -> error("Could not create folder", ex)); + } + }, "ts3j-ft-mkdir").start(); + } + + private void deleteSelected() { + List files = new ArrayList<>(); + for (int row : table.getSelectedRows()) files.add(tableModel.get(row)); + if (files.isEmpty()) return; + int choice = JOptionPane.showConfirmDialog(this, + "Delete " + (files.size() == 1 ? "\"" + files.get(0).getName() + "\"" : files.size() + " items") + + "?", "Delete", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); + if (choice != JOptionPane.OK_OPTION) return; + new Thread(() -> { + Exception failure = null; + for (RemoteFile f : files) { + try { + conn.deleteFile(channelId, channelPassword, f.getFullPath()); + } catch (Exception ex) { + failure = ex; + } + } + final Exception shown = failure; + SwingUtilities.invokeLater(() -> { + refresh(); + if (shown != null) error("Could not delete some items", shown); + }); + }, "ts3j-ft-delete").start(); + } + + private void addTransferRow(TransferRow row) { + transfersPanel.add(row); + transfersPanel.revalidate(); + transfersPanel.repaint(); + } + + private void error(String title, Exception ex) { + JOptionPane.showMessageDialog(this, rootMessage(ex), title, JOptionPane.ERROR_MESSAGE); + } + + // ---- one transfer's row ---- + + private final class TransferRow extends JPanel { + private final JLabel label = new JLabel(); + private final JProgressBar bar = new JProgressBar(0, 1000); + private final JButton action = new JButton("Cancel"); + private FileTransfer transfer; + + TransferRow() { + setLayout(new BorderLayout(UIScale.scale(8), 0)); + setBackground(Theme.windowBg()); + setBorder(new ScaledEmptyBorder(3, 2, 3, 2)); + setMaximumSize(new Dimension(Integer.MAX_VALUE, UIScale.scale(44))); + label.setFont(Theme.uiFont()); + bar.setStringPainted(true); + add(label, BorderLayout.NORTH); + add(bar, BorderLayout.CENTER); + add(action, BorderLayout.EAST); + } + + void attach(FileTransfer t) { + this.transfer = t; + action.addActionListener(e -> { + if (transfer.isDone()) { + transfersPanel.remove(this); + transfersPanel.revalidate(); + transfersPanel.repaint(); + } else { + transfer.cancel(); + } + }); + update(t); + } + + void update(FileTransfer t) { + String arrow = t.getDirection() == FileTransfer.Direction.UPLOAD ? "↑" : "↓"; + String head = arrow + " " + t.getRemoteName(); + switch (t.getState()) { + case PENDING: + label.setText(head + " — starting…"); + break; + case ACTIVE: + label.setText(head + " — " + formatBytes(t.getTransferredBytes()) + " / " + + formatBytes(t.getTotalBytes()) + " (" + formatRate(t.getAverageSpeed()) + ")"); + break; + case COMPLETED: + label.setText(head + " — done (" + formatBytes(t.getTotalBytes()) + ")"); + break; + case CANCELLED: + label.setText(head + " — cancelled"); + break; + case FAILED: + label.setText(head + " — failed: " + orEmpty(t.getErrorMessage())); + break; + default: + break; + } + int permille = (int) Math.round(t.getProgress() * 1000); + bar.setValue(permille); + bar.setString(t.getTotalBytes() > 0 ? (permille / 10) + "%" : ""); + if (t.isDone()) { + bar.setValue(t.getState() == FileTransfer.State.COMPLETED ? 1000 : bar.getValue()); + action.setText("Clear"); + } + } + } + + // ---- table model ---- + + private static final Comparator DIRECTORIES_FIRST = (a, b) -> { + if (a.isDirectory() != b.isDirectory()) return a.isDirectory() ? -1 : 1; + return a.getName().compareToIgnoreCase(b.getName()); + }; + + private static final class FileTableModel extends AbstractTableModel { + private static final String[] COLUMNS = {"Name", "Size", "Type", "Modified"}; + private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + private List files = new ArrayList<>(); + + void setFiles(List files) { + this.files = files; + fireTableDataChanged(); + } + + RemoteFile get(int row) { + return files.get(row); + } + + @Override + public int getRowCount() { + return files.size(); + } + + @Override + public int getColumnCount() { + return COLUMNS.length; + } + + @Override + public String getColumnName(int column) { + return COLUMNS[column]; + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + RemoteFile f = files.get(rowIndex); + switch (columnIndex) { + case 0: + return f.getName(); + case 1: + return f.isDirectory() ? "" : formatBytes(f.getSize()); + case 2: + return f.isDirectory() ? "Folder" : "File"; + case 3: + long sec = f.getLastModifiedEpochSec(); + return sec > 0 ? dateFormat.format(new Date(sec * 1000)) : ""; + default: + return ""; + } + } + } + + /** Marks folders and files with the icon pack's own glyphs. */ + private final class NameRenderer extends javax.swing.table.DefaultTableCellRenderer { + @Override + public java.awt.Component getTableCellRendererComponent(JTable t, Object value, boolean selected, + boolean focus, int row, int column) { + super.getTableCellRendererComponent(t, value, selected, focus, row, column); + boolean directory = row >= 0 && row < tableModel.getRowCount() && tableModel.get(row).isDirectory(); + setIcon(Icons.of(directory ? "FOLDER" : "DEFAULT")); + return this; + } + } + + // ---- formatting ---- + + private static String formatBytes(long bytes) { + if (bytes < 0) return "—"; + if (bytes < 1024) return bytes + " B"; + double kib = bytes / 1024.0; + if (kib < 1024) return new DecimalFormat("0.0").format(kib) + " KiB"; + double mib = kib / 1024.0; + if (mib < 1024) return new DecimalFormat("0.00").format(mib) + " MiB"; + return new DecimalFormat("0.00").format(mib / 1024.0) + " GiB"; + } + + private static String formatRate(double bytesPerSecond) { + if (bytesPerSecond <= 0) return "—"; + return formatBytes(Math.round(bytesPerSecond)) + "/s"; + } + + private static String orEmpty(String s) { + return s == null ? "" : s; + } + + private static String rootMessage(Throwable t) { + Throwable r = t; + while (r.getCause() != null && r.getCause() != r) r = r.getCause(); + String m = r.getMessage(); + return m != null ? m : r.getClass().getSimpleName(); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/FindBar.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/FindBar.java new file mode 100644 index 0000000..e16ca9c --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/FindBar.java @@ -0,0 +1,379 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.FlatClientProperties; +import com.formdev.flatlaf.icons.FlatAbstractIcon; +import com.formdev.flatlaf.icons.FlatSearchIcon; +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.text.TextQuery; + +import javax.swing.AbstractAction; +import javax.swing.AbstractButton; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.JToggleButton; +import javax.swing.JToolBar; +import javax.swing.KeyStroke; +import javax.swing.Timer; +import javax.swing.UIManager; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import java.awt.BasicStroke; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Insets; +import java.awt.Graphics2D; +import java.awt.event.ActionEvent; +import java.awt.event.KeyEvent; +import java.awt.geom.Path2D; +import java.util.ArrayList; +import java.util.List; +import java.util.function.BooleanSupplier; + +/** + * A single-row find bar for a view: the search field with its match-case, whole-word + * and regex toggles, the match count, previous/next and close. A view puts its own + * controls (what to search, whether to filter) in front of the field via + * {@link #addLeading} and {@link #addFilterToggle}. + * + *

    Typing is debounced; a toggle takes effect at once. Enter / F3 go to the next + * match, Shift+Enter / Shift+F3 to the previous one. Escape first resets the bar (text + * and every option) and closes it only once there is nothing left to reset. + */ +final class FindBar extends JPanel { + + interface Listener { + void queryChanged(TextQuery query); + + void next(); + + void previous(); + + void closed(); + } + + private static final int TYPING_DELAY_MS = 150; + + private final Listener listener; + private final JTextField field = new JTextField(); + private final JToggleButton matchCase = fieldToggle("Aa", "Match case"); + private final JToggleButton wholeWord = fieldToggle("ab", "Whole words"); + private final JToggleButton regex = fieldToggle(".*", "Regular expression"); + /** Wide enough for "00 / 00" whatever it shows, so the field beside it keeps its width. */ + private final JLabel status = new JLabel("", JLabel.TRAILING) { + @Override + public Dimension getPreferredSize() { + Dimension d = super.getPreferredSize(); + Insets in = getInsets(); + int reserved = getFontMetrics(getFont()).stringWidth("00 / 00") + in.left + in.right; + return new Dimension(Math.max(d.width, reserved), d.height); + } + + @Override + public Dimension getMinimumSize() { + return getPreferredSize(); + } + + @Override + public Dimension getMaximumSize() { + return getPreferredSize(); + } + }; + private final JButton previous = navButton(new Glyph(Glyph.UP), "Previous match (Shift+Enter)"); + private final JButton next = navButton(new Glyph(Glyph.DOWN), "Next match (Enter)"); + private final JPanel leading = new JPanel(); + private final Timer typing = new Timer(TYPING_DELAY_MS, e -> fireQueryChanged()); + /** Options beyond the built-in toggles: whether each is at its default, and how to put it back. */ + private final List optionDefaults = new ArrayList<>(); + private final List optionResets = new ArrayList<>(); + + FindBar(Listener listener) { + super(new BorderLayout(UIScale.scale(2), 0)); + this.listener = listener; + setBorder(new ScaledEmptyBorder(4, 4, 4, 4)); + setVisible(false); + + typing.setRepeats(false); + field.putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, "Find"); + field.putClientProperty(FlatClientProperties.TEXT_FIELD_LEADING_ICON, new FlatSearchIcon()); + field.putClientProperty(FlatClientProperties.TEXT_FIELD_SHOW_CLEAR_BUTTON, true); + JToolBar toggles = new JToolBar(); + toggles.setFloatable(false); + toggles.setBorder(null); + toggles.setOpaque(false); + for (JToggleButton b : new JToggleButton[]{matchCase, wholeWord, regex}) { + b.addActionListener(e -> fireQueryChanged()); + toggles.add(b); + } + field.putClientProperty(FlatClientProperties.TEXT_FIELD_TRAILING_COMPONENT, toggles); + field.getDocument().addDocumentListener(new DocumentListener() { + @Override + public void insertUpdate(DocumentEvent e) { + typing.restart(); + } + + @Override + public void removeUpdate(DocumentEvent e) { + typing.restart(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + } + }); + + status.setFont(Theme.uiSmall()); + status.setForeground(Theme.chatSystem()); + JButton close = navButton(new Glyph(Glyph.CLOSE), "Close (Escape)"); + previous.addActionListener(e -> goPrevious()); + next.addActionListener(e -> goNext()); + close.addActionListener(e -> close()); + + JPanel controls = new JPanel(); + controls.setLayout(new BoxLayout(controls, BoxLayout.LINE_AXIS)); + controls.setBorder(new ScaledEmptyBorder(0, 6, 0, 0)); + controls.add(status); + controls.add(Box.createHorizontalStrut(UIScale.scale(4))); + controls.add(previous); + controls.add(next); + controls.add(close); + + leading.setLayout(new BoxLayout(leading, BoxLayout.LINE_AXIS)); + leading.setVisible(false); + add(leading, BorderLayout.WEST); + add(field, BorderLayout.CENTER); + add(controls, BorderLayout.EAST); + + bind(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), this::goNext); + bind(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0), this::goNext); + bind(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.SHIFT_DOWN_MASK), this::goPrevious); + bind(KeyStroke.getKeyStroke(KeyEvent.VK_F3, KeyEvent.SHIFT_DOWN_MASK), this::goPrevious); + bind(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), this::resetOrClose); + } + + /** Adds a view-specific control in front of the field; one that changes the query should call {@link #fireQueryChanged()}. */ + void addLeading(JComponent c) { + if (c instanceof AbstractButton b) { + b.setFocusable(false); + b.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON); + } + leading.add(c); + leading.setVisible(true); + } + + /** Adds the "show only matches" toggle: a funnel that turns from grey to the accent colour when on. */ + JToggleButton addFilterToggle(String tooltip) { + JToggleButton filter = new JToggleButton(new Glyph(Glyph.FILTER)); + filter.setToolTipText(tooltip); + filter.addActionListener(e -> fireQueryChanged()); + addLeading(filter); + addResettable(() -> !filter.isSelected(), () -> filter.setSelected(false)); + return filter; + } + + /** + * Lets Escape reset a view-specific option. {@code reset} only puts the option back; + * the bar re-runs the query itself afterwards. + */ + void addResettable(BooleanSupplier isDefault, Runnable reset) { + optionDefaults.add(isDefault); + optionResets.add(reset); + } + + private boolean isDefault() { + if (!field.getText().isEmpty() || matchCase.isSelected() || wholeWord.isSelected() || regex.isSelected()) { + return false; + } + for (BooleanSupplier d : optionDefaults) { + if (!d.getAsBoolean()) return false; + } + return true; + } + + private void resetOrClose() { + if (isDefault()) { + close(); + return; + } + field.setText(""); + matchCase.setSelected(false); + wholeWord.setSelected(false); + regex.setSelected(false); + for (Runnable r : optionResets) r.run(); + fireQueryChanged(); + } + + void setPlaceholder(String text) { + field.putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, text); + } + + /** Shows the bar (if hidden) and puts the cursor in the field with its text selected. */ + void open() { + if (!isVisible()) { + setVisible(true); + revalidate(); + } + field.requestFocusInWindow(); + field.selectAll(); + if (!field.getText().isEmpty()) fireQueryChanged(); + } + + void close() { + if (!isVisible()) return; + typing.stop(); + setVisible(false); + revalidate(); + listener.closed(); + } + + boolean isOpen() { + return isVisible(); + } + + TextQuery query() { + return isVisible() + ? new TextQuery(field.getText(), matchCase.isSelected(), wholeWord.isSelected(), regex.isSelected()) + : TextQuery.EMPTY; + } + + /** + * Shows where the view is among the matches, as "3 / 17". It keeps that shape even + * with no match or none selected (" / 0"), so the field does not change width as + * the count comes and goes while typing. + * + * @param position the 1-based match the view is on, or 0 for none + * @param more whether there are more matches than {@code total} + */ + void setCount(int position, int total, boolean more) { + showStatus((position > 0 ? String.valueOf(position) : " ") + " / " + total + (more ? "+" : ""), total == 0); + } + + /** No query, nothing to count. */ + void clearCount() { + showStatus("", false); + } + + private void showStatus(String text, boolean noMatch) { + status.setText(text); + status.setToolTipText(null); + field.putClientProperty(FlatClientProperties.OUTLINE, noMatch ? FlatClientProperties.OUTLINE_ERROR : null); + } + + void setNavigable(boolean navigable) { + previous.setEnabled(navigable); + next.setEnabled(navigable); + } + + /** Re-runs the query now, e.g. after an option changed. */ + void fireQueryChanged() { + typing.stop(); + TextQuery q = query(); + if (q.isInvalid()) { + setCount(0, 0, false); + status.setToolTipText(q.error()); + setNavigable(false); + } + listener.queryChanged(q); + } + + /** Stepping through matches acts on what is typed, even if the pause that would run it is still pending. */ + private void goNext() { + if (typing.isRunning()) fireQueryChanged(); + listener.next(); + } + + private void goPrevious() { + if (typing.isRunning()) fireQueryChanged(); + listener.previous(); + } + + private void bind(KeyStroke key, Runnable action) { + String name = "ts3-find-" + key; + getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(key, name); + getActionMap().put(name, new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + action.run(); + } + }); + } + + private static JToggleButton fieldToggle(String text, String tooltip) { + JToggleButton b = new JToggleButton(text); + b.setToolTipText(tooltip); + b.setFont(Theme.uiSmall()); + b.setFocusable(false); + b.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON); + b.setMargin(new Insets(1, 3, 1, 3)); + return b; + } + + private static JButton navButton(Glyph icon, String tooltip) { + JButton b = new JButton(icon); + b.setToolTipText(tooltip); + b.setFocusable(false); + b.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON); + return b; + } + + /** The bar's line icons, drawn in the button's own text colour so they follow the theme. */ + private static final class Glyph extends FlatAbstractIcon { + static final int UP = 0; + static final int DOWN = 1; + static final int CLOSE = 2; + static final int FILTER = 3; + + private final int shape; + + Glyph(int shape) { + super(shape == FILTER ? 14 : 12, shape == FILTER ? 14 : 12, null); + this.shape = shape; + } + + @Override + protected void paintIcon(Component c, Graphics2D g) { + if (!c.isEnabled()) g.setColor(UIManager.getColor("Label.disabledForeground")); + else if (shape == FILTER) g.setColor(((AbstractButton) c).isSelected() ? Theme.accent() : Theme.chatSystem()); + else g.setColor(c.getForeground()); + if (shape == FILTER) { + Path2D.Float funnel = new Path2D.Float(); + funnel.moveTo(1.5f, 2.5f); + funnel.lineTo(12.5f, 2.5f); + funnel.lineTo(8.25f, 7.5f); + funnel.lineTo(8.25f, 12f); + funnel.lineTo(5.75f, 10.75f); + funnel.lineTo(5.75f, 7.5f); + funnel.closePath(); + g.fill(funnel); + return; + } + g.setStroke(new BasicStroke(1.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); + Path2D.Float p = new Path2D.Float(); + switch (shape) { + case UP -> { + p.moveTo(2.5f, 8f); + p.lineTo(6f, 4.5f); + p.lineTo(9.5f, 8f); + } + case DOWN -> { + p.moveTo(2.5f, 4.5f); + p.lineTo(6f, 8f); + p.lineTo(9.5f, 4.5f); + } + default -> { + p.moveTo(3f, 3f); + p.lineTo(9f, 9f); + p.moveTo(9f, 3f); + p.lineTo(3f, 9f); + } + } + g.draw(p); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/FormPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/FormPanel.java new file mode 100644 index 0000000..9c843b9 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/FormPanel.java @@ -0,0 +1,178 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; + +import javax.swing.Box; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JSeparator; +import javax.swing.JSlider; +import javax.swing.Scrollable; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.Rectangle; + +/** + * Base for a settings tab's field grid: follows the scroll pane's width instead of + * demanding its own preferred one, so rows stay inside the dialog instead of scrolling + * sideways. Also holds the small GridBagLayout helpers every such tab needs. + */ +class FormPanel extends JPanel implements Scrollable { + + static final int FIELD_WIDTH = 240; + static final int SLIDER_WIDTH = 200; + static final int MIN_FIELD_WIDTH = 60; + + FormPanel() { + this(true); + } + + /** @param padded {@code false} for a form embedded in another one, which pads it already */ + FormPanel(boolean padded) { + super(new GridBagLayout()); + if (padded) setBorder(new ScaledEmptyBorder(12, 12, 12, 12)); + } + + @Override + public Dimension getPreferredScrollableViewportSize() { + return getPreferredSize(); + } + + @Override + public int getScrollableUnitIncrement(Rectangle visible, int orientation, int direction) { + return 16; + } + + @Override + public int getScrollableBlockIncrement(Rectangle visible, int orientation, int direction) { + return visible.height; + } + + @Override + public boolean getScrollableTracksViewportWidth() { + return true; + } + + @Override + public boolean getScrollableTracksViewportHeight() { + return false; + } + + static GridBagConstraints gbc() { + GridBagConstraints c = new GridBagConstraints(); + c.insets = UIScale.scale(new Insets(4, 4, 4, 4)); + c.anchor = GridBagConstraints.WEST; + c.fill = GridBagConstraints.HORIZONTAL; + return c; + } + + /** A group heading: the title in bold, followed by a rule to the right edge. */ + static JComponent sectionHeader(String title) { + JPanel header = new JPanel(new GridBagLayout()); + JLabel label = new JLabel(title) { + @Override + public void updateUI() { + super.updateUI(); + setFont(getFont().deriveFont(Font.BOLD)); + } + }; + GridBagConstraints c = new GridBagConstraints(); + c.insets = UIScale.scale(new Insets(0, 0, 0, 8)); + header.add(label, c); + c.gridx = 1; + c.weightx = 1; + c.fill = GridBagConstraints.HORIZONTAL; + c.insets = new Insets(0, 0, 0, 0); + header.add(new JSeparator(), c); + return header; + } + + /** + * Adds a {@link #sectionHeader} spanning the grid at {@code row}, with space above it + * unless it is the first row; leaves {@code c} as it found it. + */ + static void addSection(JPanel p, GridBagConstraints c, int row, String title) { + Insets insets = c.insets; + int width = c.gridwidth; + c.gridx = 0; + c.gridy = row; + c.gridwidth = 2; + c.weightx = 0; + c.insets = UIScale.scale(new Insets(row == 0 ? 0 : 14, 0, 2, 0)); + p.add(sectionHeader(title), c); + c.insets = insets; + c.gridwidth = width; + } + + /** Adds a component spanning the whole grid at {@code row}, such as a check box. */ + static void addWide(JPanel p, GridBagConstraints c, int row, Component comp) { + int width = c.gridwidth; + c.gridx = 0; + c.gridy = row; + // No weight of its own: GridBag would hand part of it to the label column. + c.gridwidth = 2; + c.weightx = 0; + p.add(comp, c); + c.gridwidth = width; + } + + /** + * Pushes the rows above it to the top of a taller viewport, and gives the field column + * the spare width, which a form of only {@link #addWide} rows would otherwise centre. + */ + static void addFiller(JPanel p, GridBagConstraints c, int row) { + c.gridx = 1; + c.gridy = row; + c.gridwidth = 1; + c.weightx = 1; + c.weighty = 1; + p.add(Box.createGlue(), c); + c.weighty = 0; + } + + static void addRow(JPanel p, GridBagConstraints c, int row, Component label, Component field) { + c.gridx = 0; + c.gridy = row; + c.weightx = 0; + c.gridwidth = 1; + p.add(label, c); + c.gridx = 1; + c.weightx = 1; + p.add(field, c); + } + + /** + * Caps a field's preferred width and lets it shrink: long device names and wide sliders + * would otherwise force the form past the dialog's edge, where the scroll pane (which + * never scrolls horizontally) simply clips them. + */ + static void limitWidth(JComponent comp, int preferredWidth) { + int height = comp.getPreferredSize().height; + comp.setPreferredSize(new Dimension(UIScale.scale(preferredWidth), height)); + comp.setMinimumSize(new Dimension(UIScale.scale(MIN_FIELD_WIDTH), height)); + } + + static JPanel sliderWithLabel(JSlider slider, JLabel valueLabel) { + return sliderWithLabel(slider, valueLabel, 56); + } + + /** + * Pairs a slider with its value readout. The readout gets a fixed width wide enough for + * the longest value so the slider does not jump around as it is dragged. + */ + static JPanel sliderWithLabel(JSlider slider, JLabel valueLabel, int labelWidth) { + JPanel panel = new JPanel(new BorderLayout(UIScale.scale(6), 0)); + limitWidth(slider, SLIDER_WIDTH); + panel.add(slider, BorderLayout.CENTER); + valueLabel.setPreferredSize(new Dimension(UIScale.scale(labelWidth), valueLabel.getPreferredSize().height)); + panel.add(valueLabel, BorderLayout.EAST); + return panel; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/GiantPttWindow.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/GiantPttWindow.java new file mode 100644 index 0000000..88e06fa --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/GiantPttWindow.java @@ -0,0 +1,111 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.UIScale; + +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JFrame; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; + +/** + * A resizable window that is one big push-to-talk button. Pressing it transmits in any + * input mode, past the voice-activation gate. + */ +final class GiantPttWindow extends JDialog { + + private static final Color IDLE = new Color(0x1C, 0x6F, 0xB8); + private static final Color TALKING = new Color(0x2E, 0x9B, 0xF0); + + private final Consumer transmit; + private final BooleanSupplier talking; + private final Pad pad = new Pad(); + private boolean pressed; + + /** + * @param transmit forces transmission on the server holding the microphone while given {@code true} + * @param talking whether we are talking on that server, as it reports + */ + GiantPttWindow(JFrame owner, Consumer transmit, BooleanSupplier talking) { + super(owner, "Giant PTT", false); + this.transmit = transmit; + this.talking = talking; + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + setContentPane(pad); + pad.addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + press(true); + } + + @Override + public void mouseReleased(MouseEvent e) { + press(false); + } + }); + addWindowListener(new WindowAdapter() { + @Override + public void windowDeactivated(WindowEvent e) { + press(false); + } + + @Override + public void windowClosed(WindowEvent e) { + press(false); + } + }); + pad.setPreferredSize(new Dimension(UIScale.scale(360), UIScale.scale(360))); + pack(); + setLocationRelativeTo(owner); + } + + /** Our talking state changed on some server. */ + void refresh() { + pad.repaint(); + } + + private void press(boolean down) { + if (pressed == down) return; + pressed = down; + transmit.accept(down); + pad.repaint(); + } + + private final class Pad extends JComponent { + + @Override + protected void paintComponent(Graphics g) { + Graphics2D g2 = (Graphics2D) g.create(); + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + g2.setColor(Theme.windowBg()); + g2.fillRect(0, 0, getWidth(), getHeight()); + + boolean lit = pressed || talking.getAsBoolean(); + int margin = UIScale.scale(12); + int arc = UIScale.scale(32); + g2.setColor(lit ? TALKING : IDLE); + g2.fillRoundRect(margin, margin, getWidth() - 2 * margin, getHeight() - 2 * margin, arc, arc); + + String text = lit ? "Talking…" : "Hold to talk"; + float size = Math.max(UIScale.scale(12f), Math.min(getWidth() / 8f, getHeight() / 4f)); + g2.setFont(Theme.uiFont().deriveFont(Font.BOLD, size)); + FontMetrics fm = g2.getFontMetrics(); + g2.setColor(Color.WHITE); + g2.drawString(text, (getWidth() - fm.stringWidth(text)) / 2, + (getHeight() - fm.getHeight()) / 2 + fm.getAscent()); + g2.dispose(); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/GroupIcons.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/GroupIcons.java new file mode 100644 index 0000000..c17bf53 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/GroupIcons.java @@ -0,0 +1,140 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.net.Group; +import eu.lixko.ts3j.client.net.IconRepository; + +import javax.swing.Icon; +import javax.swing.ImageIcon; +import java.awt.Component; +import java.awt.Graphics; +import java.awt.Image; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Turns the {@link IconRepository}'s icon bytes into Swing icons for one server's + * groups, caching the decoded images. Icons that still have to be downloaded simply + * do not render yet; the repository repaints the view once they arrive. + */ +public final class GroupIcons { + + /** Tree rows are 16×16 like TeamSpeak's own icon set. */ + private static final int SIZE = 16; + + private static final Map DISK_CACHED = new ConcurrentHashMap<>(); + + private final IconRepository repository; + private final Map decoded = new ConcurrentHashMap<>(); + + public GroupIcons(IconRepository repository) { + this.repository = repository; + } + + /** @return the group's icon, or {@code null} if it has none or it is not loaded yet */ + public ImageIcon iconOf(Group group) { + if (group == null || group.iconId == 0) return null; + return icon(group.iconId); + } + + public ImageIcon icon(long iconId) { + if (iconId == 0) return null; + ImageIcon themed = themed(iconId); + if (themed != null) return themed; + + ImageIcon cached = decoded.get(iconId); + if (cached != null) return cached; + + ImageIcon icon = decode(repository.get(iconId)); + if (icon != null) decoded.put(iconId, icon); + return icon; + } + + /** + * An icon from the client's own cache, without a server to fetch it from, as + * bookmarks show their server's. + * + * @return the icon, or {@code null} when it has never been downloaded + */ + public static ImageIcon cached(long iconId) { + if (iconId == 0) return null; + ImageIcon themed = themed(iconId); + if (themed != null) return themed; + ImageIcon icon = DISK_CACHED.get(iconId); + if (icon != null) return icon; + icon = decode(IconRepository.cached(iconId)); + if (icon != null) DISK_CACHED.put(iconId, icon); + return icon; + } + + /** + * TeamSpeak's default group icons belong to the icon pack, which draws them in its + * own style; only server-uploaded icons come off the wire. The theme keeps its own + * cache, so those are not cached again here. + */ + private static ImageIcon themed(long iconId) { + if (iconId <= 0 || iconId > IconRepository.MAX_BUNDLED_ID) return null; + return IconTheme.icon("GROUP_" + iconId, UIScale.scale(SIZE)); + } + + private static ImageIcon decode(byte[] data) { + if (data == null) return null; + ImageIcon icon = new ImageIcon(data); + if (icon.getIconWidth() <= 0) return null; + int size = UIScale.scale(SIZE); + if (icon.getIconWidth() != size || icon.getIconHeight() != size) { + icon = new ImageIcon(icon.getImage().getScaledInstance(size, size, Image.SCALE_SMOOTH)); + } + return icon; + } + + /** Collects the icons of a client's server groups plus its channel group, in display order. */ + public List iconsOf(List serverGroups, Group channelGroup) { + List icons = new ArrayList<>(); + for (Group g : serverGroups) { + ImageIcon icon = iconOf(g); + if (icon != null) icons.add(icon); + } + ImageIcon channelIcon = iconOf(channelGroup); + if (channelIcon != null) icons.add(channelIcon); + return icons; + } + + /** Lays several icons out in a row, so a single tree cell can show a badge strip. */ + public static final class Row implements Icon { + + private static final int GAP = 2; + + private final List icons; + + public Row(List icons) { + this.icons = icons; + } + + @Override + public void paintIcon(Component c, Graphics g, int x, int y) { + int offset = x; + for (Icon icon : icons) { + icon.paintIcon(c, g, offset, y + (getIconHeight() - icon.getIconHeight()) / 2); + offset += icon.getIconWidth() + UIScale.scale(GAP); + } + } + + @Override + public int getIconWidth() { + int width = 0; + int gap = UIScale.scale(GAP); + for (Icon icon : icons) width += icon.getIconWidth() + gap; + return Math.max(0, width - gap); + } + + @Override + public int getIconHeight() { + int height = 0; + for (Icon icon : icons) height = Math.max(height, icon.getIconHeight()); + return height; + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HostButtonView.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HostButtonView.java new file mode 100644 index 0000000..6929483 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HostButtonView.java @@ -0,0 +1,74 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.net.HostButton; +import eu.lixko.ts3j.client.net.PictureDownloads; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.SwingUtilities; +import java.awt.Image; +import java.io.File; +import java.util.Objects; + +/** + * The server's host button in the toolbar's corner: its own picture, fitted to the + * toolbar's height, or TeamSpeak's host button icon while there is none (yet). + */ +final class HostButtonView extends JButton { + + /** Keeps a banner-shaped picture from crowding out the rest of the toolbar. */ + private static final int MAX_ASPECT = 6; + + private final PictureDownloads pictures; + private final Runnable onPictureLoaded = () -> SwingUtilities.invokeLater(this::refreshIcon); + private HostButton shown; + + HostButtonView(PictureDownloads pictures) { + this.pictures = pictures; + setVisible(false); + addActionListener(e -> { + if (shown != null && !shown.url().isEmpty()) Links.open(shown.url(), this); + }); + } + + /** @param button the selected server's, or {@code null} to hide it */ + void show(HostButton button) { + if (Objects.equals(button, shown)) return; + shown = button; + setVisible(button != null); + if (button == null) return; + setToolTipText(!button.tooltip().isEmpty() ? button.tooltip() : button.url().isEmpty() ? null : button.url()); + refreshIcon(); + } + + @Override + public void addNotify() { + super.addNotify(); + pictures.addListener(onPictureLoaded); + } + + @Override + public void removeNotify() { + pictures.removeListener(onPictureLoaded); + super.removeNotify(); + } + + private void refreshIcon() { + if (shown == null) return; + ImageIcon picture = shown.gfxUrl().isEmpty() ? null : picture(pictures.get(shown.gfxUrl())); + setIcon(picture != null ? picture : Icons.of("HOSTER_BUTTON", UIScale.scale(IconTheme.TOOLBAR_SIZE))); + } + + private static ImageIcon picture(File file) { + if (file == null) return null; + ImageIcon icon = new ImageIcon(file.getPath()); + int w = icon.getIconWidth(); + int h = icon.getIconHeight(); + if (w <= 0 || h <= 0) return null; + int height = UIScale.scale(IconTheme.TOOLBAR_SIZE); + int width = Math.min(Math.max(1, Math.round((float) w * height / h)), height * MAX_ASPECT); + if (w == width && h == height) return icon; + return new ImageIcon(icon.getImage().getScaledInstance(width, height, Image.SCALE_SMOOTH)); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HotkeyActions.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HotkeyActions.java new file mode 100644 index 0000000..0065ce8 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HotkeyActions.java @@ -0,0 +1,170 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.hotkey.Hotkey; +import eu.lixko.ts3j.client.hotkey.HotkeyEngine; + +import javax.swing.SwingUtilities; +import java.util.List; + +/** + * Carries a fired hotkey out on the client. + * + *

    Activations arrive on the input hook's thread, so everything is handed to the + * event dispatch thread first. Which connections an action reaches is the binding's + * "on active server" flag: set, only the selected tab; clear, every connected one. + */ +final class HotkeyActions implements HotkeyEngine.Handler { + + /** How much one press of the master-volume hotkeys moves the slider. */ + private static final double VOLUME_STEP = 0.05; + + private final MainFrame frame; + /** Latched push-to-talk, driven by the "Toggle Push-to-Talk" action. */ + private boolean pttLatched; + + HotkeyActions(MainFrame frame) { + this.frame = frame; + } + + @Override + public void onHotkey(Hotkey hotkey, boolean active) { + SwingUtilities.invokeLater(() -> perform(hotkey, active)); + } + + private void perform(Hotkey hotkey, boolean active) { + List targets = frame.hotkeyTargets(hotkey.activeServerOnly); + switch (hotkey.action) { + case CONNECT_CURRENT_TAB -> frame.connectBookmark(hotkey.argument, false); + case CONNECT_NEW_TAB -> frame.connectBookmark(hotkey.argument, true); + case DISCONNECT_CURRENT -> { + ServerTab tab = frame.selectedTab(); + if (tab != null) tab.session().disconnect(); + } + case DISCONNECT_ALL -> { + for (ServerTab tab : frame.allTabs()) tab.session().disconnect(); + } + + case MIC_ACTIVATE -> frame.moveMicrophoneToSelectedTab(); + case MIC_MUTE -> setMicMuted(targets, true); + case MIC_UNMUTE -> setMicMuted(targets, false); + case MIC_TOGGLE -> setMicMuted(targets, !anyMicMuted(targets)); + + case MIC_LOCAL_MUTE -> setMicLocalMuted(targets, true); + case MIC_LOCAL_UNMUTE -> setMicLocalMuted(targets, false); + case MIC_LOCAL_TOGGLE -> setMicLocalMuted(targets, !anyMicLocalMuted(targets)); + + case SPEAKER_MUTE -> setDeafened(targets, true); + case SPEAKER_UNMUTE -> setDeafened(targets, false); + case SPEAKER_TOGGLE -> setDeafened(targets, !anyDeafened(targets)); + + case AWAY_SET -> setAway(targets, true, ""); + case AWAY_ONLINE -> setAway(targets, false, ""); + case AWAY_TOGGLE -> setAway(targets, !anyAway(targets), ""); + case AWAY_TOGGLE_WITH_MESSAGE -> setAway(targets, !anyAway(targets), hotkey.argument); + + case COMMANDER_ACTIVATE -> setCommander(targets, true); + case COMMANDER_DEACTIVATE -> setCommander(targets, false); + case COMMANDER_TOGGLE -> setCommander(targets, !anyCommander(targets)); + + // Momentary: the engine reports the release too, so the key simply holds it open. + case PTT_ACTIVATE -> frame.setPushToTalk(active || pttLatched); + case PTT_DEACTIVATE -> { + pttLatched = false; + frame.setPushToTalk(false); + } + case PTT_TOGGLE -> { + pttLatched = !pttLatched; + frame.setPushToTalk(pttLatched); + } + + case CHANNEL_SWITCH -> { + for (ServerTab tab : targets) tab.session().joinChannelPath(hotkey.argument); + } + case SERVER_TAB_SELECT -> frame.selectTabNumber(parseIndex(hotkey.argument)); + case SERVER_TAB_NEXT -> frame.stepTab(1); + case SERVER_TAB_PREVIOUS -> frame.stepTab(-1); + + case SOUND_MUTE -> frame.setSoundsMuted(true); + case SOUND_UNMUTE -> frame.setSoundsMuted(false); + case SOUND_TOGGLE -> frame.setSoundsMuted(!frame.areSoundsMuted()); + + case VOLUME_INCREASE -> frame.adjustMasterVolume(VOLUME_STEP); + case VOLUME_DECREASE -> frame.adjustMasterVolume(-VOLUME_STEP); + + case NICKNAME_CHANGE -> frame.changeNickname(hotkey.argument); + + case RECORDING_START -> startRecording(targets, false); + case RECORDING_START_MULTITRACK -> startRecording(targets, true); + case RECORDING_STOP -> { + for (ServerTab tab : targets) tab.session().stopRecording(); + } + + case FILEBROWSER -> frame.browseCurrentChannel(); + case SKIN_RELOAD -> frame.reloadSkin(); + case BRING_TO_FRONT -> frame.bringToFront(); + case SEND_TO_BACK -> frame.sendToBack(); + + default -> { + // Listed for completeness in the action catalogue, but not implemented here. + } + } + } + + private void startRecording(List targets, boolean multitrack) { + for (ServerTab tab : targets) frame.recordings().startNow(tab.session(), multitrack); + } + + private void setMicMuted(List targets, boolean muted) { + for (ServerTab tab : targets) tab.session().setMicMuted(muted); + frame.refreshAfterHotkey(); + } + + private void setMicLocalMuted(List targets, boolean muted) { + for (ServerTab tab : targets) tab.session().setMicLocalMuted(muted); + frame.refreshAfterHotkey(); + } + + private void setDeafened(List targets, boolean deaf) { + for (ServerTab tab : targets) tab.session().setDeafened(deaf); + frame.refreshAfterHotkey(); + } + + private void setAway(List targets, boolean away, String message) { + for (ServerTab tab : targets) tab.session().setAway(away, message == null ? "" : message); + frame.refreshAfterHotkey(); + } + + private void setCommander(List targets, boolean commander) { + for (ServerTab tab : targets) tab.session().setCommander(commander); + frame.refreshAfterHotkey(); + } + + private static boolean anyMicMuted(List tabs) { + return tabs.stream().anyMatch(t -> t.session().isMicMuted()); + } + + private static boolean anyMicLocalMuted(List tabs) { + return tabs.stream().anyMatch(t -> t.session().isMicLocalMuted()); + } + + private static boolean anyDeafened(List tabs) { + return tabs.stream().anyMatch(t -> t.session().isDeafened()); + } + + private static boolean anyAway(List tabs) { + return tabs.stream().anyMatch(t -> t.session().isAway()); + } + + private static boolean anyCommander(List tabs) { + return tabs.stream().anyMatch(t -> t.session().isCommander()); + } + + /** @return the 1-based tab number in the argument, or 1 when it is not a number */ + private static int parseIndex(String argument) { + try { + return Math.max(1, Integer.parseInt(argument.trim())); + } catch (RuntimeException e) { + return 1; + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HotkeyArguments.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HotkeyArguments.java new file mode 100644 index 0000000..f280d00 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HotkeyArguments.java @@ -0,0 +1,16 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.hotkey.HotkeyAction; + +import java.util.List; + +/** + * Supplies the concrete values an action's parameter can take — the bookmarks, sound + * packs and channels the hotkey tree hangs under an action as its leaves, so a binding + * reads as "Sounds / Activate Soundpack / Default Sound Pack (Male)". + */ +interface HotkeyArguments { + + /** @return the choices for this action, or an empty list when it is free-form */ + List choices(HotkeyAction action); +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HotkeyDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HotkeyDialog.java new file mode 100644 index 0000000..d694433 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HotkeyDialog.java @@ -0,0 +1,386 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.hotkey.Hotkey; +import eu.lixko.ts3j.client.hotkey.HotkeyAction; +import eu.lixko.ts3j.client.hotkey.HotkeyCombo; +import eu.lixko.ts3j.client.hotkey.HotkeyEngine; + +import javax.swing.Box; +import javax.swing.DefaultListCellRenderer; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextField; +import javax.swing.JTree; +import javax.swing.SwingUtilities; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeCellRenderer; +import javax.swing.tree.DefaultTreeModel; +import javax.swing.tree.TreePath; +import javax.swing.tree.TreeSelectionModel; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.Window; +import java.util.List; + +/** + * Adds or edits one hotkey, following the official client's dialog: pick the action + * from the tree — category, action group, action, and where the action takes one, the + * concrete bookmark, sound pack or channel — press the key combination to bind, and + * choose the edge it triggers on and whether it applies to the active server only. + */ +final class HotkeyDialog extends JDialog { + + /** + * A tree node: a category or group heading ({@code action == null}), an action, or + * one of the values an action's parameter can take ({@code argument != null}). + */ + private record Node(HotkeyAction action, String argument, String label) { + + static Node heading(String label) { + return new Node(null, null, label); + } + + static Node of(HotkeyAction action) { + return new Node(action, null, action.label()); + } + + static Node value(HotkeyAction action, String argument) { + return new Node(action, argument, argument); + } + + boolean isHeading() { + return action == null; + } + + @Override + public String toString() { + return label; + } + } + + private final HotkeyService service; + private final Hotkey hotkey; + + private final DefaultMutableTreeNode root = new DefaultMutableTreeNode("Actions"); + private final DefaultTreeModel treeModel = new DefaultTreeModel(root); + private final JTree tree = new JTree(treeModel); + private final JCheckBox advancedCheck = new JCheckBox("Show advanced actions"); + private final JButton keyButton = new JButton(); + private final JComboBox triggerCombo = new JComboBox<>(Hotkey.Trigger.values()); + private final JCheckBox activeServerCheck = new JCheckBox("On active server"); + private final JLabel argumentLabel = new JLabel(); + private final JTextField argumentField = new JTextField(); + private final JLabel hint = new JLabel(); + + private HotkeyCombo combo; + private boolean recording; + private boolean confirmed; + + HotkeyDialog(Window owner, HotkeyService service, Hotkey existing) { + // Any window may open this: the options dialog's hotkey tab as much as a frame. + super(owner, existing == null ? "Add hotkey" : "Edit hotkey", ModalityType.APPLICATION_MODAL); + this.service = service; + this.hotkey = existing == null ? new Hotkey() : existing.copy(); + this.combo = hotkey.combo; + + advancedCheck.setSelected(hotkey.action != null && hotkey.action.advanced()); + advancedCheck.addActionListener(e -> rebuildTree()); + tree.setRootVisible(false); + tree.setShowsRootHandles(true); + tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); + tree.setCellRenderer(new NodeRenderer()); + tree.addTreeSelectionListener(e -> selectionChanged()); + rebuildTree(); + + keyButton.addActionListener(e -> startRecording()); + triggerCombo.setRenderer(new DefaultListCellRenderer() { + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, + boolean selected, boolean focused) { + super.getListCellRendererComponent(list, value, index, selected, focused); + if (value instanceof Hotkey.Trigger t) setText(t.label()); + return this; + } + }); + triggerCombo.setSelectedItem(hotkey.trigger); + activeServerCheck.setSelected(hotkey.activeServerOnly); + argumentField.setText(hotkey.argument == null ? "" : hotkey.argument); + hint.setFont(hint.getFont().deriveFont(Font.ITALIC, hint.getFont().getSize2D() - 1f)); + + getContentPane().setLayout(new BorderLayout(UIScale.scale(8), UIScale.scale(8))); + ((JComponent) getContentPane()).setBorder(new ScaledEmptyBorder(8, 8, 8, 8)); + getContentPane().add(buildActionPane(), BorderLayout.CENTER); + getContentPane().add(buildForm(), BorderLayout.SOUTH); + + updateKeyButton(); + updateForAction(); + Dialogs.closeOnEscape(this, this::cancel); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + setSize(UIScale.scale(new Dimension(470, 560))); + setLocationRelativeTo(owner); + } + + private JPanel buildActionPane() { + JPanel p = new JPanel(new BorderLayout(0, UIScale.scale(4))); + p.add(new JLabel("Action:"), BorderLayout.NORTH); + p.add(new JScrollPane(tree), BorderLayout.CENTER); + p.add(advancedCheck, BorderLayout.SOUTH); + return p; + } + + private JPanel buildForm() { + JPanel p = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + c.insets = UIScale.scale(new Insets(3, 3, 3, 3)); + c.anchor = GridBagConstraints.WEST; + c.fill = GridBagConstraints.HORIZONTAL; + + int row = 0; + addRow(p, c, row++, new JLabel("Hotkey:"), keyButton); + addRow(p, c, row++, argumentLabel, argumentField); + addRow(p, c, row++, new JLabel("Trigger:"), triggerCombo); + + c.gridx = 1; + c.gridy = row++; + p.add(activeServerCheck, c); + c.gridx = 0; + c.gridy = row++; + c.gridwidth = 2; + p.add(hint, c); + + JPanel buttons = new JPanel(); + JButton ok = new JButton("OK"); + JButton cancel = new JButton("Cancel"); + ok.addActionListener(e -> confirm()); + cancel.addActionListener(e -> cancel()); + buttons.add(Box.createHorizontalGlue()); + buttons.add(ok); + buttons.add(cancel); + c.gridy = row; + p.add(buttons, c); + getRootPane().setDefaultButton(ok); + return p; + } + + private static void addRow(JPanel p, GridBagConstraints c, int row, JComponent left, JComponent right) { + c.gridwidth = 1; + c.gridx = 0; + c.gridy = row; + c.weightx = 0; + p.add(left, c); + c.gridx = 1; + c.weightx = 1; + p.add(right, c); + } + + /** + * Builds category → group → action → value, collapsing the groups TS3 leaves + * unnamed so their actions sit directly under the category. + */ + private void rebuildTree() { + boolean advanced = advancedCheck.isSelected(); + root.removeAllChildren(); + for (HotkeyAction.Category category : HotkeyAction.Category.values()) { + List actions = HotkeyAction.of(category, advanced); + if (actions.isEmpty()) continue; + DefaultMutableTreeNode categoryNode = + new DefaultMutableTreeNode(Node.heading(category.label())); + DefaultMutableTreeNode groupNode = null; + String groupName = null; + for (HotkeyAction action : actions) { + DefaultMutableTreeNode parent = categoryNode; + if (!action.group().isEmpty()) { + if (groupNode == null || !action.group().equals(groupName)) { + groupName = action.group(); + groupNode = new DefaultMutableTreeNode(Node.heading(groupName)); + categoryNode.add(groupNode); + } + parent = groupNode; + } + DefaultMutableTreeNode actionNode = new DefaultMutableTreeNode(Node.of(action)); + parent.add(actionNode); + for (String value : service.argumentChoices(action)) { + actionNode.add(new DefaultMutableTreeNode(Node.value(action, value))); + } + } + root.add(categoryNode); + } + treeModel.reload(); + // Categories open, groups closed: the whole action set at a glance, as in TS3. + for (int i = 0; i < root.getChildCount(); i++) { + tree.expandPath(new TreePath(((DefaultMutableTreeNode) root.getChildAt(i)).getPath())); + } + selectCurrent(); + } + + /** Reveals and selects the node matching the binding being edited. */ + private void selectCurrent() { + if (hotkey.action == null) return; + DefaultMutableTreeNode match = null; + var nodes = root.depthFirstEnumeration(); + while (nodes.hasMoreElements()) { + DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodes.nextElement(); + if (!(node.getUserObject() instanceof Node n) || n.action() != hotkey.action) continue; + boolean sameArgument = n.argument() != null && n.argument().equals(hotkey.argument); + if (sameArgument) { + match = node; + break; + } + if (n.argument() == null && match == null) match = node; + } + if (match == null) return; + TreePath path = new TreePath(match.getPath()); + tree.setSelectionPath(path); + SwingUtilities.invokeLater(() -> tree.scrollPathToVisible(path)); + } + + private void selectionChanged() { + if (!(tree.getLastSelectedPathComponent() instanceof DefaultMutableTreeNode node) + || !(node.getUserObject() instanceof Node selected)) { + return; + } + if (selected.isHeading()) { + // Headings only structure the tree; keep the action that was chosen before. + tree.clearSelection(); + selectCurrent(); + return; + } + hotkey.action = selected.action(); + if (selected.argument() != null) argumentField.setText(selected.argument()); + updateForAction(); + } + + /** Syncs the form to the selected action: parameter row, trigger, scope and hint. */ + private void updateForAction() { + HotkeyAction action = hotkey.action; + boolean takesArgument = action != null && action.argument() != HotkeyAction.Argument.NONE; + argumentLabel.setText(takesArgument ? argumentLabel(action) : ""); + argumentLabel.setVisible(takesArgument); + argumentField.setVisible(takesArgument); + + boolean momentary = action != null && action.momentary(); + triggerCombo.setEnabled(!momentary); + activeServerCheck.setEnabled(action != null && action.category() != HotkeyAction.Category.MISC); + + if (action != null && !action.supported()) { + hint.setText("This action is part of TeamSpeak's hotkey set but is not implemented yet."); + } else if (momentary) { + hint.setText("Held down: the action lasts as long as the hotkey is pressed."); + } else { + hint.setText(service.isRunning() ? " " : service.status()); + } + } + + private static String argumentLabel(HotkeyAction action) { + return switch (action.argument()) { + case BOOKMARK -> "Bookmark:"; + case CHANNEL -> "Channel path:"; + case PROFILE -> "Profile:"; + default -> "Parameter:"; + }; + } + + private void startRecording() { + if (recording) return; + if (!service.isRunning()) { + hint.setText(service.status()); + return; + } + recording = true; + keyButton.setText("Press hotkey combination…"); + service.record(new HotkeyEngine.Recorder() { + @Override + public void onRecording(HotkeyCombo partial) { + SwingUtilities.invokeLater(() -> keyButton.setText(service.display(partial) + "…")); + } + + @Override + public void onRecorded(HotkeyCombo recorded) { + SwingUtilities.invokeLater(() -> { + combo = recorded; + stopRecording(); + }); + } + }); + } + + private void stopRecording() { + if (!recording) return; + recording = false; + service.stopRecording(); + updateKeyButton(); + } + + private void updateKeyButton() { + keyButton.setText(combo == null || combo.isEmpty() + ? "No hotkey assigned" : service.display(combo)); + } + + private void confirm() { + stopRecording(); + if (hotkey.action == null || combo == null || combo.isEmpty()) { + hint.setText("Pick an action and press a key combination first."); + return; + } + if (!hotkey.action.supported()) { + hint.setText("This action is not implemented yet — pick another one."); + return; + } + hotkey.combo = combo; + hotkey.trigger = (Hotkey.Trigger) triggerCombo.getSelectedItem(); + hotkey.activeServerOnly = activeServerCheck.isSelected(); + hotkey.argument = argumentField.getText().trim(); + confirmed = true; + dispose(); + } + + private void cancel() { + stopRecording(); + dispose(); + } + + boolean isConfirmed() { + return confirmed; + } + + Hotkey result() { + return hotkey; + } + + /** Draws headings in bold and greys out the actions this client cannot perform. */ + private static final class NodeRenderer extends DefaultTreeCellRenderer { + @Override + public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, + boolean expanded, boolean leaf, int row, + boolean focused) { + super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, focused); + setIcon(null); + if (!(value instanceof DefaultMutableTreeNode node) + || !(node.getUserObject() instanceof Node n)) { + return this; + } + if (n.isHeading()) { + setFont(getFont().deriveFont(Font.BOLD)); + setToolTipText(null); + } else { + setEnabled(n.action().supported()); + setToolTipText(n.action().supported() ? null : "Not implemented by this client"); + } + return this; + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HotkeyService.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HotkeyService.java new file mode 100644 index 0000000..eca2ef5 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HotkeyService.java @@ -0,0 +1,111 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.hotkey.GlobalInputHook; +import eu.lixko.ts3j.client.hotkey.Hotkey; +import eu.lixko.ts3j.client.hotkey.HotkeyAction; +import eu.lixko.ts3j.client.hotkey.HotkeyCombo; +import eu.lixko.ts3j.client.hotkey.HotkeyEngine; +import eu.lixko.ts3j.client.hotkey.HotkeyKey; +import eu.lixko.ts3j.client.hotkey.Hotkeys; +import eu.lixko.ts3j.client.hotkey.desktop.DesktopInputHooks; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * Owns the hotkey machinery for the UI: the stored bindings, the matching engine and + * the platform input hook they are fed from. Everything the dialogs need — recording a + * combination, naming keys, telling the user why hotkeys are dead — goes through here. + */ +final class HotkeyService { + + private final Hotkeys hotkeys = Hotkeys.load(); + private final HotkeyEngine engine; + private final GlobalInputHook hook; + private final HotkeyArguments arguments; + private final List keyPressListeners = new CopyOnWriteArrayList<>(); + + HotkeyService(HotkeyEngine.Handler handler, HotkeyArguments arguments) { + this.arguments = arguments; + engine = new HotkeyEngine(hotkeys, handler); + hook = DesktopInputHooks.start((key, pressed) -> { + engine.onInput(key, pressed); + if (pressed && key.device() == HotkeyKey.Device.KEYBOARD) { + for (Runnable l : keyPressListeners) l.run(); + } + }); + } + + /** + * Runs {@code l} on the input hook's thread for every key going down anywhere on the + * system, which is what typing attenuation listens for. Keep it cheap. + */ + void addKeyPressListener(Runnable l) { + keyPressListeners.add(l); + } + + void removeKeyPressListener(Runnable l) { + keyPressListeners.remove(l); + } + + /** The values this action's parameter can take right now, for the action tree. */ + List argumentChoices(HotkeyAction action) { + if (arguments == null || action.argument() == HotkeyAction.Argument.NONE) return List.of(); + try { + return arguments.choices(action); + } catch (RuntimeException e) { + return List.of(); + } + } + + List all() { + return hotkeys.all(); + } + + void replaceAll(List updated) { + engine.releaseAll(); + hotkeys.replaceAll(updated); + hotkeys.save(); + } + + /** The binding for an action with no argument, or {@code null} when unbound. */ + Hotkey find(HotkeyAction action) { + for (Hotkey h : hotkeys.all()) { + if (h.action == action) return h; + } + return null; + } + + boolean isRunning() { + return hook.isRunning(); + } + + /** One line for the options dialog: either working, or why it is not. */ + String status() { + return hook.isRunning() + ? "Global hotkeys are active." + : "Global hotkeys are unavailable (" + hook.unavailableReason() + ")."; + } + + String display(HotkeyCombo combo) { + return combo == null ? "No hotkey assigned" : combo.display(this::keyName); + } + + private String keyName(HotkeyKey key) { + return hook.keyName(key); + } + + /** Captures the next combination instead of firing bindings; see {@link #stopRecording()}. */ + void record(HotkeyEngine.Recorder recorder) { + engine.record(recorder); + } + + void stopRecording() { + engine.stopRecording(); + } + + void dispose() { + engine.releaseAll(); + hook.close(); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HotkeysPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HotkeysPanel.java new file mode 100644 index 0000000..00401de --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HotkeysPanel.java @@ -0,0 +1,167 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.hotkey.Hotkey; + +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.ListSelectionModel; +import javax.swing.SwingUtilities; +import javax.swing.table.AbstractTableModel; +import java.awt.BorderLayout; +import java.awt.Font; +import java.awt.Window; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.ArrayList; +import java.util.List; + +/** + * The options dialog's hotkey tab: the list of bindings with the buttons to add, edit + * and remove them. Edits happen on a working copy and only reach the running engine + * when the dialog is applied. + */ +final class HotkeysPanel extends JPanel { + + private static final String[] COLUMNS = {"Action", "Hotkey", "Trigger", "Active server", "On"}; + + private final HotkeyService service; + private final List working = new ArrayList<>(); + private final Model model = new Model(); + private final JTable table = new JTable(model); + + HotkeysPanel(HotkeyService service) { + super(new BorderLayout(UIScale.scale(6), UIScale.scale(6))); + this.service = service; + setBorder(new ScaledEmptyBorder(8, 8, 8, 8)); + + for (Hotkey h : service.all()) working.add(h.copy()); + + table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + table.setRowHeight(table.getRowHeight() + UIScale.scale(4)); + table.getColumnModel().getColumn(0).setPreferredWidth(UIScale.scale(240)); + table.getColumnModel().getColumn(1).setPreferredWidth(UIScale.scale(150)); + table.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() == 2) edit(); + } + }); + + JButton add = new JButton("Add…"); + JButton edit = new JButton("Edit…"); + JButton remove = new JButton("Remove"); + add.addActionListener(e -> add()); + edit.addActionListener(e -> edit()); + remove.addActionListener(e -> remove()); + + JPanel buttons = new JPanel(); + buttons.add(add); + buttons.add(edit); + buttons.add(remove); + + JLabel status = new JLabel(service.status()); + status.setFont(status.getFont().deriveFont(Font.ITALIC, status.getFont().getSize2D() - 1f)); + + add(new JScrollPane(table), BorderLayout.CENTER); + JPanel south = new JPanel(new BorderLayout()); + south.add(buttons, BorderLayout.WEST); + south.add(status, BorderLayout.SOUTH); + add(south, BorderLayout.SOUTH); + } + + private void add() { + HotkeyDialog dlg = new HotkeyDialog(owner(), service, null); + dlg.setVisible(true); + if (!dlg.isConfirmed()) return; + working.add(dlg.result()); + model.fireTableDataChanged(); + } + + private void edit() { + int row = table.getSelectedRow(); + if (row < 0) return; + HotkeyDialog dlg = new HotkeyDialog(owner(), service, working.get(row)); + dlg.setVisible(true); + if (!dlg.isConfirmed()) return; + working.set(row, dlg.result()); + model.fireTableRowsUpdated(row, row); + } + + private void remove() { + int row = table.getSelectedRow(); + if (row < 0) return; + working.remove(row); + model.fireTableDataChanged(); + } + + private Window owner() { + return SwingUtilities.getWindowAncestor(this); + } + + /** Commits the edited list to the engine and to disk. */ + void apply() { + service.replaceAll(working); + } + + /** Picks the stored bindings up again after something else changed them. */ + void reload() { + working.clear(); + for (Hotkey h : service.all()) working.add(h.copy()); + model.fireTableDataChanged(); + } + + private final class Model extends AbstractTableModel { + + @Override + public int getRowCount() { + return working.size(); + } + + @Override + public int getColumnCount() { + return COLUMNS.length; + } + + @Override + public String getColumnName(int column) { + return COLUMNS[column]; + } + + @Override + public Class getColumnClass(int column) { + return column >= 3 ? Boolean.class : String.class; + } + + @Override + public boolean isCellEditable(int row, int column) { + return column == 4 || (column == 3 && working.get(row).isServerScoped()); + } + + @Override + public Object getValueAt(int row, int column) { + Hotkey h = working.get(row); + return switch (column) { + case 0 -> h.path(); + case 1 -> service.display(h.combo); + case 2 -> h.action.momentary() ? "While held" : h.trigger.label(); + case 3 -> h.isServerScoped() && h.activeServerOnly; + default -> h.enabled; + }; + } + + @Override + public void setValueAt(Object value, int row, int column) { + Hotkey h = working.get(row); + if (column == 3) { + h.activeServerOnly = Boolean.TRUE.equals(value); + } else if (column == 4) { + h.enabled = Boolean.TRUE.equals(value); + } + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HtmlStyles.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HtmlStyles.java new file mode 100644 index 0000000..a289b35 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/HtmlStyles.java @@ -0,0 +1,213 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.text.BBCode; +import eu.lixko.ts3j.client.text.ChatHtml; + +import javax.swing.JEditorPane; +import javax.swing.JViewport; +import javax.swing.SwingUtilities; +import javax.swing.text.html.HTMLEditorKit; +import javax.swing.text.AttributeSet; +import javax.swing.text.Document; +import javax.swing.text.html.HTMLDocument; +import javax.swing.text.Element; +import javax.swing.text.View; +import javax.swing.text.ViewFactory; +import javax.swing.text.html.ImageView; +import javax.swing.text.html.StyleSheet; +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.RenderingHints; +import java.awt.Shape; + +/** + * The HTML panes showing TeamSpeak text — chat logs, client and channel information — + * and the theme-dependent stylesheet they share. + * + *

    Text that is already on screen keeps the colours its stylesheet was built with, so + * a look-and-feel change re-installs the editor kit and parses the pane's content again + * instead of only recolouring what is written afterwards. + */ +final class HtmlStyles { + + private static final String BODY_STYLE = "HtmlStyles.bodyStyle"; + + private HtmlStyles() { + } + + /** + * @param bodyStyle extra CSS for {@code body}, e.g. font and margins; the text colour + * is added by the theme + * @return a read-only HTML pane whose stylesheet follows the current theme + */ + static JEditorPane pane(String bodyStyle) { + JEditorPane pane = new JEditorPane() { + @Override + public void updateUI() { + super.updateUI(); + restyle(this); + } + }; + pane.putClientProperty(BODY_STYLE, bodyStyle); + pane.setEditable(false); + installKit(pane, null, false); + return pane; + } + + /** + * Paints the scroll pane {@code pane} sits in with the pane's own background: text + * only reaches as far as it goes, and the empty space below it would otherwise show + * the window's colour instead of the log's. + */ + static void fillViewport(JEditorPane pane) { + if (pane.getParent() instanceof JViewport viewport) { + viewport.setBackground(pane.getBackground()); + } + } + + /** Re-themes {@code pane}, keeping the text it shows. */ + private static void restyle(JEditorPane pane) { + // Also runs from JEditorPane's constructor, before the pane is one of ours. + if (pane.getClientProperty(BODY_STYLE) == null) return; + + int length = pane.getDocument().getLength(); + String html = length == 0 ? null : pane.getText(); + // A chat log sits at its newest line; keep it there rather than jumping to the top. + boolean atEnd = pane.getCaretPosition() >= length; + // Not during the look-and-feel update that got us here: the pane is rebuilding its + // views, and replacing the document underneath it would race with that. + SwingUtilities.invokeLater(() -> installKit(pane, html, atEnd)); + } + + private static void installKit(JEditorPane pane, String html, boolean atEnd) { + HTMLEditorKit kit = new ZoomedKit(pane); + StyleSheet css = new StyleSheet(); + css.addStyleSheet(kit.getStyleSheet()); + + Object bodyStyle = pane.getClientProperty(BODY_STYLE); + css.addRule("body { " + (bodyStyle == null ? "" : bodyStyle + " ") + + "color:" + hex(Theme.chatText()) + "; }"); + // Secondary text (timestamps, labels, placeholders), an author's name and the lines + // about what happened on the server. + css.addRule(".muted { color:" + hex(Theme.chatSystem()) + "; }"); + css.addRule(".name { color:" + hex(Theme.chatName()) + "; font-weight:bold; }"); + css.addRule(".event { color:" + hex(Theme.chatEvent()) + "; }"); + css.addRule("a { color:" + hex(Theme.chatName()) + "; text-decoration:none; }"); + // Client references look exactly like a message author's name. + css.addRule("a." + BBCode.IDENTITY_LINK_CLASS + + " { color:" + hex(Theme.chatName()) + "; font-weight:bold; text-decoration:none; }"); + // Channel (and other TeamSpeak protocol) references stand out of a line the same + // way a client's name does. + css.addRule("a." + BBCode.TS_LINK_CLASS + + " { color:" + hex(Theme.chatName()) + "; font-weight:bold; text-decoration:none; }"); + // External links are underlined so they can't be mistaken for an identity. + css.addRule("a." + BBCode.EXTERNAL_LINK_CLASS + + " { color:" + hex(Theme.link()) + "; text-decoration:underline; }"); + css.addRule("a." + ChatHtml.ATTACHMENT_CLASS + + " { color:" + hex(Theme.link()) + "; text-decoration:underline; }"); + kit.setStyleSheet(css); + + pane.setEditorKit(kit); + fillViewport(pane); + if (html != null) { + pane.setText(html); + pane.setCaretPosition(atEnd ? pane.getDocument().getLength() : 0); + } + } + + /** A CSS length of {@code px} at the interface scale. */ + static String px(int px) { + return UIScale.scale(px) + "px"; + } + + private static String hex(Color c) { + return String.format("#%02x%02x%02x", c.getRed(), c.getGreen(), c.getBlue()); + } + + /** Scales every font size by the pane's {@link TextZoom}; FlatLaf has already applied the interface scale. */ + private static final class ZoomedStyleSheet extends StyleSheet { + private final JEditorPane pane; + + ZoomedStyleSheet(JEditorPane pane) { + this.pane = pane; + } + + @Override + public Font getFont(AttributeSet a) { + Font font = super.getFont(a); + float zoom = TextZoom.of(pane); + return zoom == 1f ? font : font.deriveFont(font.getSize2D() * zoom); + } + } + + /** Zooms the text of the documents it makes, and draws their pictures at the pane's {@link TextZoom}. */ + private static final class ZoomedKit extends HTMLEditorKit { + private final JEditorPane pane; + private final ViewFactory factory = new HTMLFactory() { + @Override + public View create(Element elem) { + View view = super.create(elem); + return view instanceof ImageView ? new ZoomedImageView(elem) : view; + } + }; + + ZoomedKit(JEditorPane pane) { + this.pane = pane; + } + + /** As the default, but the document takes its fonts from a {@link ZoomedStyleSheet}. */ + @Override + public Document createDefaultDocument() { + StyleSheet css = new ZoomedStyleSheet(pane); + css.addStyleSheet(getStyleSheet()); + HTMLDocument doc = new HTMLDocument(css); + doc.setParser(getParser()); + doc.setAsynchronousLoadPriority(4); + doc.setTokenThreshold(100); + return doc; + } + + @Override + public ViewFactory getViewFactory() { + return factory; + } + } + + private static final class ZoomedImageView extends ImageView { + ZoomedImageView(Element elem) { + super(elem); + } + + private float zoom() { + return TextZoom.of(getContainer()); + } + + @Override + public float getPreferredSpan(int axis) { + return super.getPreferredSpan(axis) * zoom(); + } + + @Override + public void paint(Graphics g, Shape a) { + float zoom = zoom(); + if (zoom == 1f) { + super.paint(g, a); + return; + } + Rectangle r = a.getBounds(); + Graphics2D g2 = (Graphics2D) g.create(); + try { + g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); + g2.translate(r.x, r.y); + g2.scale(zoom, zoom); + super.paint(g2, new Rectangle(0, 0, Math.round(r.width / zoom), Math.round(r.height / zoom))); + } finally { + g2.dispose(); + } + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IconChooserDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IconChooserDialog.java new file mode 100644 index 0000000..6555b51 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IconChooserDialog.java @@ -0,0 +1,272 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.net.IconRepository; +import eu.lixko.ts3j.client.net.TeamspeakConnection; + +import javax.swing.BorderFactory; +import javax.swing.DefaultListModel; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JFileChooser; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.ListSelectionModel; +import javax.swing.SwingUtilities; +import javax.swing.Timer; +import javax.swing.filechooser.FileNameExtensionFilter; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Window; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.io.File; + +/** + * TeamSpeak's icon viewer: the icons uploaded to this virtual server on one side (which + * can be added to and removed from here) and the ones the icon pack ships on the other. + * + *

    Server icons arrive through the {@link IconRepository}, which downloads them in the + * background, so the lists are simply repainted until every icon has turned up. + */ +final class IconChooserDialog extends JDialog { + + /** How often the lists are repainted while icons are still being downloaded. */ + private static final int REFRESH_MS = 300; + /** Give up repainting once nothing has arrived for this long. */ + private static final int REFRESH_TIMEOUT_MS = 20_000; + + private final TeamspeakConnection conn; + private final GroupIcons groupIcons; + + private final DefaultListModel remoteModel = new DefaultListModel<>(); + private final JList remoteList = new JList<>(remoteModel); + private final JList localList = new JList<>(new DefaultListModel<>()); + private final JButton deleteButton = new JButton("Delete"); + private final JButton selectButton = new JButton("Select"); + private final JLabel status = new JLabel(" "); + + private long chosenIconId; + private boolean accepted; + + IconChooserDialog(Window owner, TeamspeakConnection conn, GroupIcons groupIcons) { + super(owner, "Icons", ModalityType.APPLICATION_MODAL); + this.conn = conn; + this.groupIcons = groupIcons; + + configure(remoteList); + configure(localList); + DefaultListModel localModel = (DefaultListModel) localList.getModel(); + for (Long id : IconRepository.BUNDLED_IDS) localModel.addElement(id); + + JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, + group("Remote", remoteList, remoteButtons()), + group("Local", localList, localFooter())); + split.setResizeWeight(0.6); + + status.setBorder(new ScaledEmptyBorder(2, 8, 2, 8)); + status.setForeground(Theme.chatSystem()); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(split, BorderLayout.CENTER); + JPanel south = new JPanel(new BorderLayout()); + south.add(status, BorderLayout.NORTH); + south.add(buttons(), BorderLayout.SOUTH); + getContentPane().add(south, BorderLayout.SOUTH); + + Dialogs.closeOnEscape(this); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + setSize(UIScale.scale(new Dimension(520, 360))); + setLocationRelativeTo(owner); + + loadRemoteIcons(); + startRefreshing(); + } + + /** @return whether an icon was picked; {@link #getIconId()} then holds it */ + boolean isAccepted() { + return accepted; + } + + long getIconId() { + return chosenIconId; + } + + private void configure(JList list) { + list.setLayoutOrientation(JList.HORIZONTAL_WRAP); + list.setVisibleRowCount(-1); + list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + list.setFixedCellWidth(UIScale.scale(32)); + list.setFixedCellHeight(UIScale.scale(32)); + list.setCellRenderer(new IconCellRenderer()); + list.addListSelectionListener(e -> onSelectionChanged(list)); + list.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() == 2 && list.getSelectedValue() != null) choose(list.getSelectedValue()); + } + }); + } + + /** Keeps one list's selection exclusive: picking on one side clears the other. */ + private void onSelectionChanged(JList list) { + JList other = list == remoteList ? localList : remoteList; + if (list.getSelectedValue() != null) other.clearSelection(); + deleteButton.setEnabled(remoteList.getSelectedValue() != null); + selectButton.setEnabled(selectedIcon() != 0); + } + + private long selectedIcon() { + Long remote = remoteList.getSelectedValue(); + if (remote != null) return remote; + Long local = localList.getSelectedValue(); + return local == null ? 0 : local; + } + + private JPanel group(String title, JList list, Component footer) { + JPanel panel = new JPanel(new BorderLayout(0, UIScale.scale(4))); + panel.setBorder(BorderFactory.createTitledBorder(title)); + panel.add(new JScrollPane(list), BorderLayout.CENTER); + panel.add(footer, BorderLayout.SOUTH); + return panel; + } + + private Component remoteButtons() { + JButton upload = new JButton("Upload"); + upload.addActionListener(a -> uploadIcon()); + deleteButton.setEnabled(false); + deleteButton.addActionListener(a -> deleteSelectedIcon()); + JPanel row = new JPanel(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 4, 0)); + row.add(upload); + row.add(deleteButton); + return row; + } + + private Component localFooter() { + eu.lixko.ts3j.client.gfx.IconPack active = IconTheme.get().activePack(); + JLabel pack = new JLabel("Icon Pack: " + (active == null ? "none" : active.name())); + pack.setBorder(new ScaledEmptyBorder(0, 4, 0, 4)); + return pack; + } + + private JPanel buttons() { + selectButton.setEnabled(false); + selectButton.addActionListener(a -> choose(selectedIcon())); + JButton cancel = new JButton("Cancel"); + cancel.addActionListener(a -> dispose()); + JPanel panel = new JPanel(new BorderLayout()); + JPanel right = new JPanel(); + right.add(selectButton); + right.add(cancel); + panel.add(right, BorderLayout.EAST); + getRootPane().setDefaultButton(selectButton); + return panel; + } + + private void choose(long iconId) { + if (iconId == 0) return; + chosenIconId = iconId; + accepted = true; + dispose(); + } + + private void loadRemoteIcons() { + status.setText("Loading icons…"); + conn.requestServerIcons((ids, error) -> SwingUtilities.invokeLater(() -> { + if (error != null) { + status.setText("Could not list the server's icons: " + error); + return; + } + status.setText(" "); + remoteModel.clear(); + for (Long id : ids) remoteModel.addElement(id); + })); + } + + private void uploadIcon() { + JFileChooser chooser = new JFileChooser(); + chooser.setDialogTitle("Select an image to upload"); + chooser.setFileFilter(new FileNameExtensionFilter("Images", "png", "jpg", "jpeg", "gif", "bmp", "svg")); + if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return; + File file = chooser.getSelectedFile(); + status.setText("Uploading " + file.getName() + "…"); + conn.uploadIcon(file, (iconId, error) -> SwingUtilities.invokeLater(() -> { + if (error != null) { + status.setText(" "); + JOptionPane.showMessageDialog(this, "Error uploading icon: " + error, + "Error", JOptionPane.ERROR_MESSAGE); + return; + } + loadRemoteIcons(); + startRefreshing(); + })); + } + + private void deleteSelectedIcon() { + Long id = remoteList.getSelectedValue(); + if (id == null) return; + int answer = JOptionPane.showConfirmDialog(this, + "Permanently delete this icon from the server?", "Confirmation", + JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); + if (answer != JOptionPane.YES_OPTION) return; + conn.deleteIcon(id, error -> SwingUtilities.invokeLater(() -> { + if (error != null) { + JOptionPane.showMessageDialog(this, "Failed to delete remote icon file: " + error, + "Error", JOptionPane.ERROR_MESSAGE); + return; + } + remoteModel.removeElement(id); + })); + } + + /** + * Repaints while the repository is still fetching icons; it hands them over silently, + * so the only way to show them as they land is to keep asking. + */ + private void startRefreshing() { + Timer timer = new Timer(REFRESH_MS, null); + long deadline = System.currentTimeMillis() + REFRESH_TIMEOUT_MS; + timer.addActionListener(e -> { + remoteList.repaint(); + localList.repaint(); + if (!isDisplayable() || System.currentTimeMillis() > deadline || allIconsLoaded()) timer.stop(); + }); + timer.start(); + } + + private boolean allIconsLoaded() { + for (int i = 0; i < remoteModel.size(); i++) { + if (groupIcons.icon(remoteModel.get(i)) == null) return false; + } + return true; + } + + /** Draws one icon, blank until the repository has it. */ + private final class IconCellRenderer extends javax.swing.DefaultListCellRenderer { + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, + boolean selected, boolean focused) { + super.getListCellRendererComponent(list, "", index, selected, focused); + long id = value instanceof Long ? (Long) value : 0; + ImageIcon icon = groupIcons.icon(id); + setIcon(icon); + setHorizontalAlignment(CENTER); + setToolTipText("Icon " + id); + return this; + } + } + + /** Convenience for callers that only need the picked id. */ + static long pick(Window owner, TeamspeakConnection conn, GroupIcons groupIcons, long current) { + IconChooserDialog dialog = new IconChooserDialog(owner, conn, groupIcons); + dialog.setVisible(true); + return dialog.isAccepted() ? dialog.getIconId() : current; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IconFiles.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IconFiles.java new file mode 100644 index 0000000..f7862ff --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IconFiles.java @@ -0,0 +1,64 @@ +package eu.lixko.ts3j.client.ui; + +import javax.imageio.ImageIO; +import javax.swing.ImageIcon; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Icons of the active pack, and country flags, as PNG files, for HTML views, which only + * show pictures by URL. A pack change gives the theme new icons, and so new files. + */ +final class IconFiles { + + private static final Map FILES = new ConcurrentHashMap<>(); + private static File dir; + + private IconFiles() { + } + + /** @return the icon's file, or {@code null} if no pack has it or it could not be written */ + static File of(String key, int size) { + ImageIcon icon = IconTheme.icon(key, size); + if (icon == null) return null; + String name = key + '_' + size + '_' + Integer.toHexString(System.identityHashCode(icon)) + ".png"; + File file = FILES.computeIfAbsent(name, n -> write(icon, n)); + return file.isFile() ? file : null; + } + + /** @return the country's flag as drawn in the tree, or {@code null} for none */ + static File flag(String code) { + ImageIcon icon = CountryFlagIcons.of(code); + if (icon == null) return null; + File file = FILES.computeIfAbsent("flag_" + code + '_' + icon.getIconWidth() + ".png", n -> write(icon, n)); + return file.isFile() ? file : null; + } + + private static File write(ImageIcon icon, String name) { + try { + File file = new File(dir(), name); + BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB); + Graphics2D g = image.createGraphics(); + icon.paintIcon(null, g, 0, 0); + g.dispose(); + ImageIO.write(image, "png", file); + file.deleteOnExit(); + return file; + } catch (IOException e) { + return new File(name); // never a file, so asked for again next time + } + } + + private static synchronized File dir() throws IOException { + if (dir == null) { + dir = Files.createTempDirectory("ts3client-icons").toFile(); + dir.deleteOnExit(); + } + return dir; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IconTheme.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IconTheme.java new file mode 100644 index 0000000..1418cdb --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IconTheme.java @@ -0,0 +1,194 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.UIScale; +import com.github.weisj.jsvg.SVGDocument; +import com.github.weisj.jsvg.parser.LoaderContext; +import com.github.weisj.jsvg.parser.SVGLoader; +import com.github.weisj.jsvg.view.ViewBox; +import eu.lixko.ts3j.client.config.AppDirs; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.gfx.IconPack; +import eu.lixko.ts3j.client.gfx.IconPacks; + +import javax.imageio.ImageIO; +import javax.swing.ImageIcon; +import javax.swing.UIManager; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.RenderingHints; +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * The icons the user interface draws itself with, taken from the active + * {@link IconPack}. + * + *

    Packs are TeamSpeak's, so an installed client's {@code gfx/} folder (and the + * packs from its add-on site) can be used as they are. A pack's own + * {@code FALLBACK} option decides whether icons it does not define are looked up + * in {@code default.zip}; whatever is still missing is drawn by {@link Icons} + * instead, so the client always has a complete set. + * + *

    Rendering is cached per key and size: vector art is rasterised at the size it + * is asked for, in the look-and-feel's text colour where it paints with + * {@code currentColor}; bitmaps are scaled from the closest resolution the pack ships. + * {@link #SIZE} and {@link #TOOLBAR_SIZE} are unscaled; sizes passed in are pixels. + */ +public final class IconTheme { + + /** The size of a tree row / menu item icon, as in the official client. */ + public static final int SIZE = 16; + /** The size of the toolbar's buttons. */ + public static final int TOOLBAR_SIZE = 24; + + private static final IconTheme INSTANCE = new IconTheme(); + + private final Map cache = new ConcurrentHashMap<>(); + private final List listeners = new CopyOnWriteArrayList<>(); + + private volatile List packs = List.of(); + private volatile IconPack active; + /** Where icons are looked up; what none of these has is drawn by {@link Icons}. */ + private volatile List lookupOrder = List.of(); + + private IconTheme() { + } + + public static IconTheme get() { + return INSTANCE; + } + + /** The packs found on this machine, in display order. */ + public List packs() { + return packs; + } + + public IconPack activePack() { + return active; + } + + /** Re-scans the pack folders and activates the one the settings name. */ + public void reload(Settings settings) { + packs = IconPacks.findAll(new File(AppDirs.profile(), "gfx"), settings.iconPackDir); + IconPack pack = IconPacks.select(packs, settings.iconPack); + // The shipped pack survives a re-scan as the same object, so setPack alone may not notice. + lookupOrder = IconPacks.lookupOrder(pack, packs, null); + setPack(pack); + } + + /** Switches to a pack (which may be {@code null} for the built-in icons). */ + public void setPack(IconPack pack) { + if (active == pack) return; + active = pack; + lookupOrder = IconPacks.lookupOrder(pack, packs, null); + cache.clear(); + for (Runnable listener : listeners) listener.run(); + } + + /** Re-renders the icons, which follow the look-and-feel's text colour. */ + public void refresh() { + cache.clear(); + for (Runnable listener : listeners) listener.run(); + } + + /** Registers a repaint to run whenever the icons change. */ + public void addListener(Runnable listener) { + listeners.add(listener); + } + + public void removeListener(Runnable listener) { + listeners.remove(listener); + } + + /** @return the icon for a TeamSpeak icon key at tree-row size, or {@code null} if no pack has it */ + public static ImageIcon icon(String key) { + return icon(key, UIScale.scale(SIZE)); + } + + /** @return the icon for a TeamSpeak icon key at {@code size} pixels, or {@code null} if no pack has it */ + public static ImageIcon icon(String key, int size) { + return INSTANCE.lookup(key, size); + } + + private ImageIcon lookup(String key, int size) { + if (key == null) return null; + String cacheKey = key + '@' + size; + ImageIcon cached = cache.get(cacheKey); + if (cached != null) return cached; + + ImageIcon icon = null; + for (IconPack pack : lookupOrder) { + icon = render(pack, key, size); + if (icon != null) break; + } + if (icon != null) cache.put(cacheKey, icon); + return icon; + } + + private static ImageIcon render(IconPack pack, String key, int size) { + byte[] data = pack.icon(key, size); + if (data == null || data.length == 0) return null; + BufferedImage image = pack.isVector(key, size) + ? rasterize(IconPack.withCurrentColor(data, textColor().getRGB()), size) + : decode(data, size); + return image == null ? null : new ImageIcon(image); + } + + private static Color textColor() { + Color c = UIManager.getColor("Label.foreground"); + return c != null ? c : Color.BLACK; + } + + static BufferedImage rasterize(byte[] data, int size) { + try { + SVGDocument document = new SVGLoader().load( + new ByteArrayInputStream(data), null, LoaderContext.createDefault()); + if (document == null) return null; + BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); + Graphics2D g = image.createGraphics(); + try { + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); + document.render(null, g, new ViewBox(size, size)); + } finally { + g.dispose(); + } + return image; + } catch (Exception e) { + return null; + } + } + + private static BufferedImage decode(byte[] data, int size) { + try { + BufferedImage source = ImageIO.read(new ByteArrayInputStream(data)); + if (source == null) return null; + if (source.getWidth() == size && source.getHeight() == size) return source; + + BufferedImage scaled = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); + Graphics2D g = scaled.createGraphics(); + try { + g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, + RenderingHints.VALUE_INTERPOLATION_BILINEAR); + g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); + // Keep the aspect ratio of packs whose art is not square. + double factor = Math.min((double) size / source.getWidth(), (double) size / source.getHeight()); + int w = Math.max(1, (int) Math.round(source.getWidth() * factor)); + int h = Math.max(1, (int) Math.round(source.getHeight() * factor)); + g.drawImage(source.getScaledInstance(w, h, Image.SCALE_SMOOTH), + (size - w) / 2, (size - h) / 2, null); + } finally { + g.dispose(); + } + return scaled; + } catch (Exception e) { + return null; + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/Icons.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/Icons.java new file mode 100644 index 0000000..31f150e --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/Icons.java @@ -0,0 +1,487 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.gfx.IconKeys; + +import javax.swing.ImageIcon; +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.RenderingHints; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +/** + * The user interface's icons, taken from the active {@link IconTheme} pack and + * named by TeamSpeak's icon keys. + * + *

    The icons the client cannot do without are also drawn programmatically here, + * so a machine with no icon pack installed still gets a complete (if plain) set. + * Everything else — menu and dialog decoration — simply stays blank without a pack, + * which is why {@link #of(String)} may return {@code null}. + * + *

    Icons come at the interface's scale; the variants taking a size take it in pixels. + */ +public final class Icons { + + /** The box the built-in painters draw in. */ + private static final int SZ = IconTheme.SIZE; + + private Icons() { + } + + private static int small() { + return UIScale.scale(IconTheme.SIZE); + } + + private static int large() { + return UIScale.scale(IconTheme.TOOLBAR_SIZE); + } + + private interface Painter { + void paint(Graphics2D g); + } + + /** @return the pack's icon for a TeamSpeak icon key, or {@code null} when it has none */ + public static ImageIcon of(String key) { + return IconTheme.icon(key); + } + + /** + * @return the pack's icon for the first key it has, or {@code null} when it has none + * of them — packs differ in which variants they ship + */ + public static ImageIcon ofAny(String... keys) { + for (String key : keys) { + ImageIcon icon = IconTheme.icon(key); + if (icon != null) return icon; + } + return null; + } + + /** @return the pack's icon at {@code size} pixels, or {@code null} when it has none */ + public static ImageIcon of(String key, int size) { + return IconTheme.icon(key, size); + } + + private static ImageIcon themed(String key, Painter fallback) { + return themed(key, small(), fallback); + } + + private static ImageIcon themed(String key, int size, Painter fallback) { + ImageIcon icon = IconTheme.icon(key, size); + return icon != null ? icon : make(size, fallback); + } + + /** Like {@link #themed(String, Painter)}, but tries the keys in turn. */ + private static ImageIcon themed(String[] keys, Painter fallback) { + for (String key : keys) { + ImageIcon icon = IconTheme.icon(key, small()); + if (icon != null) return icon; + } + return make(fallback); + } + + private static ImageIcon make(Painter p) { + return make(small(), p); + } + + /** Runs a painter (which draws in a 16×16 box) scaled to {@code size}. */ + private static ImageIcon make(int size, Painter p) { + BufferedImage img = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); + Graphics2D g = img.createGraphics(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); + g.scale(size / (double) SZ, size / (double) SZ); + p.paint(g); + g.dispose(); + return new ImageIcon(img); + } + + // ---- tree icons ---- + + public static ImageIcon server() { + return themed("SERVER_GREEN", Icons::paintServer); + } + + public static ImageIcon channel(boolean subscribed) { + return themed(IconKeys.channel(false, false, subscribed), + g -> paintChannel(g, new Color(0x3E7CB1), false, subscribed)); + } + + /** A channel nobody can join without its password. */ + public static ImageIcon channelLocked(boolean subscribed) { + return themed(IconKeys.channel(true, false, subscribed), + g -> paintChannel(g, new Color(0x8A6D3B), true, subscribed)); + } + + /** A channel that has reached its client limit. */ + public static ImageIcon channelFull(boolean subscribed) { + return themed(IconKeys.channel(false, true, subscribed), + g -> paintChannel(g, new Color(0xA53F3F), false, subscribed)); + } + + /** The chat tab for the current channel. */ + public static ImageIcon channelChat() { + ImageIcon icon = of("CHANNEL_CHAT"); + return icon != null ? icon : channel(true); + } + + /** The chat tab of a private conversation. */ + public static ImageIcon privateChat() { + ImageIcon icon = ofAny("PLAYER_CHAT", "NEW_CHAT"); + return icon != null ? icon : clientIdle(); + } + + // ---- client status icons ---- + + public static ImageIcon clientIdle() { + return clientIdle(small()); + } + + public static ImageIcon clientIdle(int size) { + return themed("PLAYER_OFF", size, g -> paintPerson(g, Theme.idleClient())); + } + + public static ImageIcon clientTalking() { + return clientTalking(small()); + } + + public static ImageIcon clientTalking(int size) { + return themed("PLAYER_ON", size, g -> paintPerson(g, Theme.talking())); + } + + public static ImageIcon clientAway() { + return clientAway(small()); + } + + public static ImageIcon clientAway(int size) { + return themed("AWAY", size, g -> paintPerson(g, Theme.away())); + } + + /** A channel commander that is not talking. */ + public static ImageIcon clientCommander() { + return clientCommander(small()); + } + + /** A channel commander that is talking. */ + public static ImageIcon clientCommanderTalking() { + return clientCommanderTalking(small()); + } + + public static ImageIcon clientQuery() { + return themed("SERVER_QUERY", g -> paintPerson(g, Theme.idleClient())); + } + + public static ImageIcon micMuted() { + return micMuted(small()); + } + + public static ImageIcon micMuted(int size) { + return themed("INPUT_MUTED", size, Icons::paintMicMuted); + } + + public static ImageIcon speakerMuted() { + return speakerMuted(small()); + } + + public static ImageIcon speakerMuted(int size) { + return themed("OUTPUT_MUTED", size, Icons::paintSpeakerMuted); + } + + /** The capture device is unavailable (another tab holds it), as opposed to muted. */ + public static ImageIcon micDisabled() { + return micDisabled(small()); + } + + public static ImageIcon micDisabled(int size) { + return themed("HARDWARE_INPUT_MUTED", size, Icons::paintMicDisabled); + } + + /** The playback device is unavailable, as opposed to muted/deafened. */ + public static ImageIcon speakerDisabled() { + return speakerDisabled(small()); + } + + public static ImageIcon speakerDisabled(int size) { + return themed("HARDWARE_OUTPUT_MUTED", size, Icons::paintSpeakerDisabled); + } + + /** TS3's "Local Mic Mute": silenced, but not reported as muted. */ + public static ImageIcon micLocalMuted() { + return micLocalMuted(small()); + } + + public static ImageIcon micLocalMuted(int size) { + return themed("INPUT_MUTED_LOCAL", size, Icons::paintMicLocalMuted); + } + + /** A channel commander that is not talking. */ + public static ImageIcon clientCommander(int size) { + return themed("PLAYER_COMMANDER_OFF", size, g -> paintPerson(g, Theme.idleClient())); + } + + /** A channel commander that is talking. */ + public static ImageIcon clientCommanderTalking(int size) { + return themed("PLAYER_COMMANDER_ON", size, g -> paintPerson(g, Theme.talking())); + } + + // ---- toolbar / action icons ---- + + public static ImageIcon connect() { + return themed("CONNECT", large(), Icons::paintConnect); + } + + public static ImageIcon disconnect() { + return themed("DISCONNECT", large(), Icons::paintDisconnect); + } + + public static ImageIcon mic() { + return themed("CAPTURE", large(), Icons::paintMic); + } + + public static ImageIcon speaker() { + return themed("PLAYBACK", large(), Icons::paintSpeaker); + } + + public static ImageIcon micMutedLarge() { + return themed("INPUT_MUTED", large(), Icons::paintMicMuted); + } + + public static ImageIcon speakerMutedLarge() { + return themed("OUTPUT_MUTED", large(), Icons::paintSpeakerMuted); + } + + /** Marks the server that currently owns the microphone. */ + public static ImageIcon micActive() { + return themed("ACTIVATE_MICROPHONE", large(), Icons::paintMicActive); + } + + /** The same marker at tab-label size. */ + public static ImageIcon micActiveSmall() { + return themed("ACTIVATE_MICROPHONE", Icons::paintMicActive); + } + + /** + * A fixed-width "channel icon / edit icon" label icon, used where a tab must not + * change width as the object it shows changes (e.g. the info-panel-in-chat tab). + */ + public static ImageIcon channelClientPair() { + ImageIcon channel = channel(true); + ImageIcon edit = themed("EDIT", Icons::paintEdit); + int gap = UIScale.scale(8); + int width = channel.getIconWidth() + gap + edit.getIconWidth(); + int height = Math.max(channel.getIconHeight(), edit.getIconHeight()); + BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); + Graphics2D g = img.createGraphics(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.drawImage(channel.getImage(), 0, (height - channel.getIconHeight()) / 2, null); + g.setColor(Theme.idleClient()); + g.setFont(Theme.uiFont()); + java.awt.FontMetrics fm = g.getFontMetrics(); + int slashX = channel.getIconWidth() + (gap - fm.stringWidth("/")) / 2; + g.drawString("/", slashX, (height + fm.getAscent()) / 2 - 1); + g.drawImage(edit.getImage(), channel.getIconWidth() + gap, + (height - edit.getIconHeight()) / 2, null); + g.dispose(); + return new ImageIcon(img); + } + + /** The toolbar's away marker. */ + public static ImageIcon away() { + return themed("AWAY", large(), g -> paintPerson(g, Theme.away())); + } + + public static ImageIcon settings() { + return themed("SETTINGS", large(), Icons::paintSettings); + } + + public static ImageIcon app() { + return app(small()); + } + + /** Below 32 pixels a variant with a bolder headset, whose thin lines would blur away. */ + public static ImageIcon app(int size) { + String name = size < 32 ? "app-icon-small.svg" : "app-icon.svg"; + try (InputStream in = Icons.class.getResourceAsStream(name)) { + BufferedImage image = IconTheme.rasterize(in.readAllBytes(), size); + if (image != null) return new ImageIcon(image); + } catch (IOException | RuntimeException ignored) { + } + return new ImageIcon(new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB)); + } + + /** The window icon at the sizes task bars and switchers pick from. */ + public static List appImages() { + return List.of(16, 24, 32, 48, 64, 128).stream() + .map(size -> app(size).getImage()) + .toList(); + } + + // ---- built-in painters ---- + + private static void paintServer(Graphics2D g) { + g.setColor(new Color(0x2C6EA5)); + g.fillRoundRect(2, 3, 12, 4, 2, 2); + g.fillRoundRect(2, 9, 12, 4, 2, 2); + g.setColor(new Color(0x9FD0F0)); + g.fillOval(4, 4, 2, 2); + g.fillOval(4, 10, 2, 2); + } + + /** + * The speaker-cone glyph. An unsubscribed channel is drawn hollow and without the + * sound waves, so the two states stay apart even without an icon pack. + */ + private static void paintChannel(Graphics2D g, Color c, boolean lock, boolean subscribed) { + int[] xs = {5, 9, 9, 5}; + int[] ys = {6, 3, 13, 10}; + g.setColor(c); + g.setStroke(new BasicStroke(subscribed ? 1.6f : 1.2f)); + if (subscribed) { + g.fillRect(2, 6, 3, 4); + g.fillPolygon(xs, ys, 4); + g.setStroke(new BasicStroke(1.4f)); + g.drawArc(9, 5, 4, 6, -60, 120); + } else { + g.drawRect(2, 6, 3, 4); + g.drawPolygon(xs, ys, 4); + } + if (lock) { + g.setColor(new Color(0xB8860B)); + g.fillRoundRect(10, 9, 5, 5, 1, 1); + g.setColor(Color.WHITE); + g.fillRect(12, 10, 1, 2); + } + } + + private static void paintPerson(Graphics2D g, Color c) { + g.setColor(c); + g.fillOval(5, 2, 6, 6); // head + g.fillRoundRect(3, 9, 10, 6, 4, 4); // shoulders + } + + private static void paintMicMuted(Graphics2D g) { + g.setColor(Theme.muted()); + g.fillRoundRect(6, 2, 4, 7, 2, 2); + g.setStroke(new BasicStroke(1.4f)); + g.drawArc(4, 6, 8, 6, 200, 140); + g.drawLine(8, 12, 8, 14); + g.setStroke(new BasicStroke(2f)); + g.drawLine(2, 2, 14, 14); // slash + } + + private static void paintSpeakerMuted(Graphics2D g) { + g.setColor(Theme.muted()); + g.fillRect(2, 6, 3, 4); + int[] xs = {5, 9, 9, 5}; + int[] ys = {6, 3, 13, 10}; + g.fillPolygon(xs, ys, 4); + g.setStroke(new BasicStroke(2f)); + g.drawLine(2, 2, 14, 14); + } + + /** Same shape as {@link #paintMicMuted}, but grey: unavailable, not muted by choice. */ + private static void paintMicDisabled(Graphics2D g) { + g.setColor(Theme.idleClient()); + g.fillRoundRect(6, 2, 4, 7, 2, 2); + g.setStroke(new BasicStroke(1.4f)); + g.drawArc(4, 6, 8, 6, 200, 140); + g.drawLine(8, 12, 8, 14); + g.setStroke(new BasicStroke(2f)); + g.drawLine(2, 2, 14, 14); + } + + /** Same shape as {@link #paintSpeakerMuted}, but grey: unavailable, not muted by choice. */ + private static void paintSpeakerDisabled(Graphics2D g) { + g.setColor(Theme.idleClient()); + g.fillRect(2, 6, 3, 4); + int[] xs = {5, 9, 9, 5}; + int[] ys = {6, 3, 13, 10}; + g.fillPolygon(xs, ys, 4); + g.setStroke(new BasicStroke(2f)); + g.drawLine(2, 2, 14, 14); + } + + /** {@link #paintMicMuted}, marked with a small dot: silenced, but not reported as muted. */ + private static void paintMicLocalMuted(Graphics2D g) { + paintMicMuted(g); + g.setColor(Theme.accent()); + g.fillOval(11, 10, 4, 4); + } + + private static void paintConnect(Graphics2D g) { + g.setColor(new Color(0x2E8B57)); + g.setStroke(new BasicStroke(2f)); + g.drawLine(3, 8, 8, 8); + g.fillRoundRect(8, 5, 5, 6, 2, 2); + g.drawLine(10, 3, 10, 5); + g.drawLine(12, 3, 12, 5); + } + + private static void paintDisconnect(Graphics2D g) { + g.setColor(Theme.muted()); + g.setStroke(new BasicStroke(2f)); + g.drawLine(3, 8, 8, 8); + g.fillRoundRect(8, 5, 5, 6, 2, 2); + g.drawLine(2, 3, 6, 13); + } + + private static void paintMic(Graphics2D g) { + g.setColor(new Color(0x37474F)); + g.fillRoundRect(6, 2, 4, 7, 2, 2); + g.setStroke(new BasicStroke(1.4f)); + g.drawArc(4, 6, 8, 6, 200, 140); + g.drawLine(8, 12, 8, 14); + g.drawLine(6, 14, 10, 14); + } + + private static void paintSpeaker(Graphics2D g) { + g.setColor(new Color(0x37474F)); + g.fillRect(2, 6, 3, 4); + int[] xs = {5, 9, 9, 5}; + int[] ys = {6, 3, 13, 10}; + g.fillPolygon(xs, ys, 4); + g.setStroke(new BasicStroke(1.4f)); + g.drawArc(9, 5, 4, 6, -60, 120); + } + + private static void paintMicActive(Graphics2D g) { + g.setColor(Theme.talking()); + g.fillOval(1, 1, 14, 14); + g.setColor(Color.WHITE); + g.fillRoundRect(6, 3, 4, 6, 2, 2); + g.setStroke(new BasicStroke(1.4f)); + g.drawArc(4, 6, 8, 6, 200, 140); + g.drawLine(8, 11, 8, 13); + } + + /** A pencil glyph, drawn when no icon pack ships an "EDIT" icon. */ + private static void paintEdit(Graphics2D g) { + g.setColor(new Color(0x37474F)); + g.setStroke(new BasicStroke(1.4f)); + g.drawLine(3, 13, 11, 5); + g.drawLine(3, 13, 4, 10); + g.drawLine(4, 10, 11, 3); + g.drawLine(11, 3, 13, 5); + g.drawLine(13, 5, 11, 7); + g.drawLine(11, 5, 13, 7); + } + + private static void paintSettings(Graphics2D g) { + g.setColor(new Color(0x37474F)); + g.setStroke(new BasicStroke(2f)); + g.drawOval(5, 5, 6, 6); + for (int a = 0; a < 360; a += 45) { + double r = Math.toRadians(a); + int x1 = (int) (8 + Math.cos(r) * 5); + int y1 = (int) (8 + Math.sin(r) * 5); + int x2 = (int) (8 + Math.cos(r) * 7); + int y2 = (int) (8 + Math.sin(r) * 7); + g.drawLine(x1, y1, x2, y2); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IdentitiesDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IdentitiesDialog.java new file mode 100644 index 0000000..7dd7e32 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IdentitiesDialog.java @@ -0,0 +1,432 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.config.Bookmarks; +import eu.lixko.ts3j.client.config.IdentityEntry; +import eu.lixko.ts3j.client.config.IdentityStore; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter; +import eu.lixko.ts3j.client.teamspeak.TeamSpeakSettingsDb; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.DefaultListCellRenderer; +import javax.swing.DefaultListModel; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JFileChooser; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextField; +import javax.swing.SwingUtilities; +import javax.swing.filechooser.FileNameExtensionFilter; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.io.File; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; + +/** + * Identity manager, mirroring the TeamSpeak 3 client's Tools → Identities: + * create, import, export, rename and delete identities, mark one as the default + * and raise an identity's security level. + */ +public final class IdentitiesDialog extends JDialog { + + private final IdentityStore identities; + private final Settings settings; + private final Bookmarks bookmarks; + private final Runnable onChanged; + + private final DefaultListModel listModel = new DefaultListModel<>(); + private final JList list = new JList<>(listModel); + + private final JTextField nameField = new JTextField(); + private final JTextField uidField = new JTextField(); + private final JTextField levelField = new JTextField(); + private final JTextField nicknameField = new JTextField(); + private final JTextField phoneticField = new JTextField(); + /** The identity the nickname fields belong to, which the list may already have moved off. */ + private IdentityEntry shown; + + public IdentitiesDialog(Frame owner, IdentityStore identities, Settings settings, + Bookmarks bookmarks, Runnable onChanged) { + super(owner, "Identities", true); + this.identities = identities; + this.settings = settings; + this.bookmarks = bookmarks; + this.onChanged = onChanged; + + list.setCellRenderer(new DefaultListCellRenderer() { + @Override + public Component getListCellRendererComponent(JList l, Object value, int index, + boolean isSelected, boolean cellHasFocus) { + String text = value instanceof IdentityEntry ? label((IdentityEntry) value) : String.valueOf(value); + return super.getListCellRendererComponent(l, text, index, isSelected, cellHasFocus); + } + }); + list.addListSelectionListener(e -> showDetails(list.getSelectedValue())); + list.setVisibleRowCount(10); + + JScrollPane scroll = new JScrollPane(list); + scroll.setBorder(new ScaledEmptyBorder(8, 8, 8, 8)); + scroll.setPreferredSize(UIScale.scale(new Dimension(220, 260))); + + JPanel buttons = new JPanel(); + buttons.setLayout(new BoxLayout(buttons, BoxLayout.Y_AXIS)); + buttons.setBorder(new ScaledEmptyBorder(8, 0, 8, 8)); + addButton(buttons, "New…", this::newIdentity); + addButton(buttons, "Import…", this::importIdentity); + if (TeamSpeakSettingsDb.locate() != null) { + addButton(buttons, "Import from TeamSpeak 3…", this::importFromTeamSpeak); + } + addButton(buttons, "Export…", this::exportSelected); + addButton(buttons, "Rename…", this::renameSelected); + addButton(buttons, "Set as default", this::setSelectedDefault); + addButton(buttons, "Improve security…", this::improveSelected); + addButton(buttons, "Remove", this::removeSelected); + buttons.add(Box.createVerticalGlue()); + addButton(buttons, "Close", this::dispose); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(scroll, BorderLayout.WEST); + getContentPane().add(buildDetails(), BorderLayout.CENTER); + getContentPane().add(buttons, BorderLayout.EAST); + + reload(); + if (!listModel.isEmpty()) list.setSelectedIndex(0); + + Dialogs.closeOnEscape(this); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + pack(); + setMinimumSize(UIScale.scale(new Dimension(640, 320))); + setLocationRelativeTo(owner); + } + + private JPanel buildDetails() { + JPanel form = new JPanel(new GridBagLayout()); + form.setBorder(new ScaledEmptyBorder(12, 4, 12, 8)); + GridBagConstraints c = new GridBagConstraints(); + c.insets = UIScale.scale(new Insets(4, 4, 4, 4)); + c.anchor = GridBagConstraints.NORTHWEST; + c.fill = GridBagConstraints.HORIZONTAL; + + nameField.setEditable(false); + uidField.setEditable(false); + levelField.setEditable(false); + + int row = 0; + addRow(form, c, row++, "Name:", nameField); + addRow(form, c, row++, "Unique ID:", uidField); + addRow(form, c, row++, "Security level:", levelField); + addRow(form, c, row++, "Nickname:", nicknameField); + addRow(form, c, row++, "Phonetic nickname:", phoneticField); + + nicknameField.setToolTipText("Empty: the global nickname"); + for (JTextField field : new JTextField[]{nicknameField, phoneticField}) { + field.addActionListener(e -> applyNicknames()); + field.addFocusListener(new FocusAdapter() { + @Override + public void focusLost(FocusEvent e) { + applyNicknames(); + } + }); + } + + c.gridx = 0; + c.gridy = row; + c.gridwidth = 2; + c.weighty = 1; + c.fill = GridBagConstraints.BOTH; + form.add(Box.createGlue(), c); + return form; + } + + private void addRow(JPanel form, GridBagConstraints c, int row, String label, Component field) { + c.gridx = 0; + c.gridy = row; + c.weightx = 0; + form.add(new JLabel(label), c); + c.gridx = 1; + c.weightx = 1; + form.add(field, c); + } + + private void addButton(JPanel panel, String text, Runnable action) { + JButton b = new JButton(text); + b.setAlignmentX(LEFT_ALIGNMENT); + b.setMaximumSize(new Dimension(Integer.MAX_VALUE, b.getPreferredSize().height)); + b.addActionListener(e -> action.run()); + panel.add(b); + panel.add(Box.createVerticalStrut(UIScale.scale(4))); + } + + private String label(IdentityEntry e) { + return e.getId().equals(settings.defaultIdentityId) ? e.getName() + " (default)" : e.getName(); + } + + private void reload() { + IdentityEntry selected = list.getSelectedValue(); + listModel.clear(); + for (IdentityEntry e : identities.all()) listModel.addElement(e); + if (selected != null && listModel.contains(selected)) { + list.setSelectedValue(selected, true); + } else if (!listModel.isEmpty()) { + list.setSelectedIndex(0); + } else { + showDetails(null); + } + if (onChanged != null) onChanged.run(); + } + + private void showDetails(IdentityEntry e) { + applyNicknames(); + shown = e; + nicknameField.setEnabled(e != null); + phoneticField.setEnabled(e != null); + nicknameField.setText(e == null ? "" : e.getNickname()); + phoneticField.setText(e == null ? "" : e.getPhoneticNickname()); + nameField.setText(e == null ? "" : e.getName()); + uidField.setText(e == null ? "" : e.getUniqueId()); + levelField.setText(e == null ? "" : Integer.toString(e.getSecurityLevel())); + } + + @Override + public void dispose() { + // Escape closes without the field losing focus first. + applyNicknames(); + super.dispose(); + } + + // ---- actions ---- + + private void applyNicknames() { + IdentityEntry e = shown; + if (e == null || identities.byId(e.getId()) == null) return; + String nickname = nicknameField.getText().trim(); + String phonetic = phoneticField.getText().trim(); + if (nickname.equals(e.getNickname()) && phonetic.equals(e.getPhoneticNickname())) return; + try { + identities.setNicknames(e, nickname, phonetic); + } catch (Exception ex) { + error("Could not save the nicknames", ex); + } + } + + private void newIdentity() { + String name = JOptionPane.showInputDialog(this, "Name for the new identity:", "New identity"); + if (name == null || name.trim().isEmpty()) return; + + int level = askLevel("Security level to generate:", IdentityStore.DEFAULT_SECURITY_LEVEL); + if (level < 0) return; + + runWithProgress("Generating identity…", (cancelled, status) -> { + IdentityEntry created = identities.generate(name.trim(), level); + if (settings.defaultIdentityId == null || identities.byId(settings.defaultIdentityId) == null) { + settings.defaultIdentityId = created.getId(); + settings.save(); + } + return created; + }, false); + } + + private void importIdentity() { + JFileChooser chooser = new JFileChooser(); + chooser.setDialogTitle("Import identity"); + chooser.setFileFilter(new FileNameExtensionFilter("TeamSpeak identity (*.ini)", "ini")); + if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return; + File file = chooser.getSelectedFile(); + try { + IdentityEntry imported = identities.importFile(file, null); + if (identities.byId(settings.defaultIdentityId) == null) { + settings.defaultIdentityId = imported.getId(); + settings.save(); + } + reload(); + list.setSelectedValue(imported, true); + } catch (Exception e) { + error("Could not import identity", e); + } + } + + private void importFromTeamSpeak() { + File db = TeamSpeakSettingsDb.locate(); + if (db == null) return; + try { + TeamSpeakImporter.Result result = new TeamSpeakImporter(identities, bookmarks, settings).importIdentities(db); + reload(); + JOptionPane.showMessageDialog(this, result.identities() + " identit" + (result.identities() == 1 ? "y" : "ies") + + " read from " + db + "\n" + result.identitiesAdded() + " new, " + + result.identitiesKnown() + " already present.", + "Import from TeamSpeak 3", JOptionPane.INFORMATION_MESSAGE); + } catch (Exception e) { + error("Could not read " + db, e); + } + } + + private void exportSelected() { + IdentityEntry e = list.getSelectedValue(); + if (e == null) return; + JFileChooser chooser = new JFileChooser(); + chooser.setDialogTitle("Export identity"); + chooser.setFileFilter(new FileNameExtensionFilter("TeamSpeak identity (*.ini)", "ini")); + chooser.setSelectedFile(new File(e.getName().replaceAll("[^\\w.-]+", "_") + ".ini")); + if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return; + + File target = chooser.getSelectedFile(); + if (target.exists() && JOptionPane.showConfirmDialog(this, + target.getName() + " already exists. Overwrite?", "Export identity", + JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) { + return; + } + try { + identities.exportTo(e, target); + JOptionPane.showMessageDialog(this, "Identity exported to\n" + target.getAbsolutePath(), + "Export identity", JOptionPane.INFORMATION_MESSAGE); + } catch (Exception ex) { + error("Could not export identity", ex); + } + } + + private void renameSelected() { + IdentityEntry e = list.getSelectedValue(); + if (e == null) return; + String name = JOptionPane.showInputDialog(this, "Identity name:", e.getName()); + if (name == null || name.trim().isEmpty()) return; + try { + identities.rename(e, name.trim()); + reload(); + } catch (Exception ex) { + error("Could not rename identity", ex); + } + } + + private void setSelectedDefault() { + IdentityEntry e = list.getSelectedValue(); + if (e == null) return; + settings.defaultIdentityId = e.getId(); + settings.save(); + reload(); + } + + private void removeSelected() { + IdentityEntry e = list.getSelectedValue(); + if (e == null) return; + int result = JOptionPane.showConfirmDialog(this, + "Delete identity \"" + e.getName() + "\"?\n\n" + + "Server groups and permissions tied to it will be lost.\n" + + "Export it first if you may need it again.", + "Remove identity", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); + if (result != JOptionPane.YES_OPTION) return; + identities.remove(e, settings, bookmarks); + reload(); + } + + private void improveSelected() { + IdentityEntry e = list.getSelectedValue(); + if (e == null) return; + int level = askLevel("Target security level (current: " + e.getSecurityLevel() + "):", + Math.max(e.getSecurityLevel() + 1, IdentityStore.DEFAULT_SECURITY_LEVEL)); + if (level < 0) return; + if (level <= e.getSecurityLevel()) { + JOptionPane.showMessageDialog(this, "The identity already reaches that level."); + return; + } + runWithProgress("Improving security level…", + (cancelled, status) -> { + identities.improveSecurity(e, level, (best, offset) -> { + status.accept("Improving security level… reached " + best + " of " + level); + return !cancelled.get(); + }); + return e; + }, true); + } + + private int askLevel(String prompt, int suggestion) { + String s = JOptionPane.showInputDialog(this, prompt, Integer.toString(suggestion)); + if (s == null) return -1; + try { + int level = Integer.parseInt(s.trim()); + if (level < 0 || level > 40) throw new NumberFormatException(); + return level; + } catch (NumberFormatException e) { + JOptionPane.showMessageDialog(this, "Enter a security level between 0 and 40."); + return -1; + } + } + + /** Work that produces the identity to select once it finishes. */ + private interface IdentityTask { + IdentityEntry run(AtomicBoolean cancelled, Consumer status) throws Exception; + } + + /** + * Runs a long identity computation off the EDT behind a modal progress dialog. + * Both generating and improving an identity are proof-of-work searches whose + * duration grows exponentially with the security level. + */ + private void runWithProgress(String message, IdentityTask task, boolean cancellable) { + AtomicBoolean cancelled = new AtomicBoolean(false); + + JDialog progress = new JDialog(this, "Please wait", true); + JLabel status = new JLabel(message); + JPanel panel = new JPanel(new BorderLayout(UIScale.scale(8), UIScale.scale(8))); + panel.setBorder(new ScaledEmptyBorder(16, 16, 12, 16)); + panel.add(status, BorderLayout.CENTER); + if (cancellable) { + JButton cancel = new JButton("Stop"); + cancel.setToolTipText("Keep the best level found so far"); + cancel.addActionListener(e -> cancelled.set(true)); + JPanel south = new JPanel(); + south.add(cancel); + panel.add(south, BorderLayout.SOUTH); + } + progress.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); + progress.getContentPane().add(panel); + progress.pack(); + progress.setLocationRelativeTo(this); + + Consumer report = text -> SwingUtilities.invokeLater(() -> status.setText(text)); + Thread worker = new Thread(() -> { + IdentityEntry result = null; + Exception failure = null; + try { + result = task.run(cancelled, report); + } catch (Exception e) { + failure = e; + } + IdentityEntry selected = result; + Exception thrown = failure; + SwingUtilities.invokeLater(() -> { + progress.dispose(); + if (thrown != null) { + error("Identity operation failed", thrown); + return; + } + reload(); + if (selected != null) list.setSelectedValue(selected, true); + }); + }, "identity-work"); + + // Start only once the modal dialog is up, so a fast task can't dispose it + // before it becomes visible (which would leave it on screen forever). + SwingUtilities.invokeLater(worker::start); + progress.setVisible(true); + } + + private void error(String what, Exception e) { + String detail = e.getMessage() == null ? e.toString() : e.getMessage(); + JOptionPane.showMessageDialog(this, what + ":\n" + detail, "Identities", JOptionPane.ERROR_MESSAGE); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IdentityChooser.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IdentityChooser.java new file mode 100644 index 0000000..5a69f70 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IdentityChooser.java @@ -0,0 +1,65 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.config.IdentityEntry; +import eu.lixko.ts3j.client.config.IdentityStore; + +import javax.swing.DefaultListCellRenderer; +import javax.swing.JComboBox; +import javax.swing.JList; +import java.awt.Component; + +/** + * Drop-down for picking the identity to connect with. Optionally offers a + * "use the default identity" entry for places where the choice may stay unset + * (bookmarks), so changing the default later applies retroactively. + */ +final class IdentityChooser extends JComboBox { + + private static final String USE_DEFAULT = "‹Default identity›"; + + private final IdentityStore identities; + private final boolean allowDefault; + + IdentityChooser(IdentityStore identities, boolean allowDefault, String selectedId) { + this.identities = identities; + this.allowDefault = allowDefault; + reload(); + setSelectedIdentityId(selectedId); + + setRenderer(new DefaultListCellRenderer() { + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, + boolean isSelected, boolean cellHasFocus) { + String text = value instanceof IdentityEntry + ? ((IdentityEntry) value).getName() + : String.valueOf(value); + return super.getListCellRendererComponent(list, text, index, isSelected, cellHasFocus); + } + }); + } + + /** Re-reads the store's identities, keeping the selection where it still exists. */ + void reload() { + String selected = getSelectedIdentityId(); + removeAllItems(); + if (allowDefault) addItem(USE_DEFAULT); + for (IdentityEntry e : identities.all()) addItem(e); + setSelectedIdentityId(selected); + } + + /** Selected identity id, or an empty string when the default is to be used. */ + String getSelectedIdentityId() { + Object v = getSelectedItem(); + return v instanceof IdentityEntry ? ((IdentityEntry) v).getId() : ""; + } + + /** Selects the identity with the given id, falling back to the default entry. */ + void setSelectedIdentityId(String id) { + IdentityEntry selected = identities.byId(id); + if (selected != null) { + setSelectedItem(selected); + } else if (allowDefault) { + setSelectedItem(USE_DEFAULT); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/InfoPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/InfoPanel.java new file mode 100644 index 0000000..3eed1da --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/InfoPanel.java @@ -0,0 +1,479 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.contacts.Contact; +import eu.lixko.ts3j.client.net.ChannelNode; +import eu.lixko.ts3j.client.net.ClientEntry; +import eu.lixko.ts3j.client.net.Details; +import eu.lixko.ts3j.client.net.Group; +import eu.lixko.ts3j.client.net.IconRepository; +import eu.lixko.ts3j.client.net.PictureDownloads; +import eu.lixko.ts3j.client.net.ServerModel; +import eu.lixko.ts3j.client.net.avatar.Avatar; +import eu.lixko.ts3j.client.text.BBCode; + +import javax.swing.BorderFactory; +import javax.swing.JEditorPane; +import javax.swing.JFileChooser; +import javax.swing.JLabel; +import javax.swing.JLayeredPane; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.JScrollPane; +import javax.swing.SwingUtilities; +import javax.swing.text.AttributeSet; +import javax.swing.text.BadLocationException; +import javax.swing.text.StyleConstants; +import javax.swing.text.html.HTML; +import javax.swing.text.html.HTMLDocument; +import java.awt.BorderLayout; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.geom.Rectangle2D; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.List; + +/** + * Read-only detail view for the server, channel or client selected, mirroring the + * TeamSpeak 3 info box; what it says comes from {@link Details}. + */ +public final class InfoPanel extends JPanel { + + /** Moves the whole info panel's content out to a persistent chat tab. */ + public interface DescriptionHandler { + /** Shows/updates {@code html} in the info chat tab, creating it if needed. */ + void showInfoTab(String html, Runnable onClose); + + /** Closes the info chat tab (the user chose to show details in the panel again). */ + void closeInfoTab(); + + /** Hides (or restores) the panel itself, freeing its space, while its content lives in the chat tab. */ + void setPanelHidden(boolean hidden); + } + + /** What the avatar's menu does. */ + public interface AvatarHandler { + /** Takes someone else's avatar as ours. */ + void steal(Avatar avatar); + + /** Whether we may upload an avatar. */ + boolean canSet(); + + /** Whether we may delete other clients' avatars. */ + boolean canDeleteOthers(); + + void deleteOf(ClientEntry client); + + /** Asks for an image to upload as our avatar. */ + void set(); + + void delete(); + } + + private static final int AVATAR_MIN_SIZE = 64; + private static final int AVATAR_BOX_STEP = 16; + /** Pictures in a chat tab have no panel to fit, so they get this much. */ + private static final int CHAT_TAB_PICTURE_WIDTH = 480; + private static final int PICTURE_WIDTH_STEP = 32; + + private final JEditorPane pane = HtmlStyles.pane("font-family:sans-serif; font-size:11px;"); + private final JScrollPane scroll = new JScrollPane(pane); + /** Floats over the bottom-right corner of the details, out of the text's way. */ + private final JLabel toggle = new JLabel("Show in chat tab"); + private DescriptionHandler descriptionHandler; + private AvatarHandler avatarHandler; + private ChannelNode shownChannel; + private ClientEntry shownClient; + /** The server's address while the server itself is shown. */ + private String shownServer; + private ServerModel shownModel; + private IconRepository shownIcons; + private Contact shownContact; + private Avatar shownAvatar; + private boolean inChatTab; + /** The avatar box the current HTML was built for; a resize that changes it re-renders. */ + private int renderedAvatarBox; + private final PictureDownloads downloads; + private final DescriptionPictures pictures; + /** Whether the description shown has pictures, which re-render it as they come or the panel resizes. */ + private boolean showsPictures; + private int renderedPictureWidth; + private final Runnable onPicture = () -> SwingUtilities.invokeLater(() -> { + if (showsPictures) keepingScroll(this::render); + }); + + public InfoPanel(Settings settings, PictureDownloads downloads, TextZoom zoom) { + super(new BorderLayout()); + zoom.attach(pane); + this.downloads = downloads; + this.pictures = new DescriptionPictures(downloads, settings); + pane.setBorder(new ScaledEmptyBorder(6, 8, 6, 8)); + pane.addHyperlinkListener(e -> { + if (e.getEventType() != javax.swing.event.HyperlinkEvent.EventType.ACTIVATED) return; + Links.open(e.getDescription(), this); + }); + pane.addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + if (e.isPopupTrigger()) showAvatarMenu(e); + } + + @Override + public void mouseReleased(MouseEvent e) { + if (e.isPopupTrigger()) showAvatarMenu(e); + } + }); + HtmlStyles.fillViewport(pane); + scroll.getViewport().addComponentListener(new ComponentAdapter() { + @Override + public void componentResized(ComponentEvent e) { + if (inChatTab) return; + boolean avatar = shownAvatar != null && avatarBox() != renderedAvatarBox; + boolean pictures = showsPictures && pictureWidth() != renderedPictureWidth; + if (avatar || pictures) keepingScroll(InfoPanel.this::render); + } + }); + + toggle.setFont(Theme.uiSmall()); + toggle.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + toggle.setToolTipText("Show these details in a chat tab instead"); + toggle.setOpaque(true); + toggle.setBorder(new ScaledEmptyBorder(1, 4, 1, 4)); + toggle.addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + inChatTab = true; + render(); + } + }); + + // The link floats on top of the text rather than following it, so it stays + // in the corner however long the description is. + JLayeredPane layers = new JLayeredPane() { + @Override + public void doLayout() { + scroll.setBounds(0, 0, getWidth(), getHeight()); + // Lay the scroll pane out first: the link goes in the corner of the + // viewport, which is where the scroll bars have already been taken out. + scroll.doLayout(); + Rectangle view = scroll.getViewport().getBounds(); + Dimension d = toggle.getPreferredSize(); + toggle.setBounds(view.x + view.width - d.width, view.y + view.height - d.height, + d.width, d.height); + } + + // Without a layout manager we have no size of our own, and the split pane + // above us sizes the panel from it. + @Override + public Dimension getPreferredSize() { + return scroll.getPreferredSize(); + } + + @Override + public Dimension getMinimumSize() { + return scroll.getMinimumSize(); + } + }; + layers.add(scroll, JLayeredPane.DEFAULT_LAYER); + layers.add(toggle, JLayeredPane.PALETTE_LAYER); + add(layers, BorderLayout.CENTER); + applyTheme(); + clear(); + } + + @Override + public void addNotify() { + super.addNotify(); + downloads.addListener(onPicture); + } + + @Override + public void removeNotify() { + downloads.removeListener(onPicture); + super.removeNotify(); + } + + /** Runs {@code change}, which renders again, without the view jumping back to the top. */ + private void keepingScroll(Runnable change) { + Point at = scroll.getViewport().getViewPosition(); + change.run(); + SwingUtilities.invokeLater(() -> scroll.getViewport().setViewPosition(at)); + } + + @Override + public void updateUI() { + super.updateUI(); + // Runs from the superclass constructor too, before our own fields exist. + if (scroll != null) applyTheme(); + } + + private void applyTheme() { + scroll.setBorder(BorderFactory.createLineBorder(Theme.border())); + toggle.setBackground(pane.getBackground()); + toggle.setForeground(Theme.link()); + } + + public void clear() { + shownChannel = null; + shownClient = null; + shownServer = null; + inChatTab = false; + render(); + } + + public void setDescriptionHandler(DescriptionHandler handler) { + this.descriptionHandler = handler; + } + + public void setAvatarHandler(AvatarHandler handler) { + this.avatarHandler = handler; + } + + /** Runs when the user closes the info chat tab; shows details in the panel again. */ + private void onInfoTabClosed() { + inChatTab = false; + render(); + } + + public void showServer(ServerModel model, String address) { + shownServer = address; + shownModel = model; + shownChannel = null; + shownClient = null; + render(); + } + + public void showChannel(ChannelNode ch) { + shownChannel = ch; + shownClient = null; + shownServer = null; + render(); + } + + /** @param avatar the client's avatar, or {@code null} while there is none to show */ + public void showClient(ClientEntry cl, ServerModel model, IconRepository icons, Contact contact, + Avatar avatar) { + shownClient = cl; + shownChannel = null; + shownServer = null; + shownModel = model; + shownIcons = icons; + shownContact = contact; + shownAvatar = avatar; + render(); + } + + private void render() { + boolean selected = shownChannel != null || shownClient != null || shownServer != null; + boolean hide = inChatTab && selected; + if (descriptionHandler != null) descriptionHandler.setPanelHidden(hide); + toggle.setVisible(selected && !hide); + if (hide) { + descriptionHandler.showInfoTab(body(), this::onInfoTabClosed); + } else { + setHtml(body()); + } + } + + private String body() { + showsPictures = false; + if (shownServer != null) return html(Details.server(shownModel, shownServer), "", "", null, null); + if (shownChannel != null) return html(Details.channel(shownChannel), "", "", null, "No description."); + if (shownClient != null) { + renderedAvatarBox = inChatTab ? UIScale.scale(AvatarHtml.MAX_SIZE) : avatarBox(); + return clientBody(shownClient, shownModel, shownIcons, shownContact, shownAvatar, renderedAvatarBox); + } + return "Select the server, a channel or a client to see details."; + } + + /** + * How large an avatar may be drawn beside the details: a share of the panel's + * width, so a narrow panel keeps room for the text. Rounded to steps so that + * dragging a divider does not rebuild the HTML on every pixel. + */ + private int avatarBox() { + int width = scroll.getViewport().getWidth(); + int max = UIScale.scale(AvatarHtml.MAX_SIZE); + if (width <= 0) return max; + int step = UIScale.scale(AVATAR_BOX_STEP); + int box = width * 2 / 5 / step * step; + return Math.max(UIScale.scale(AVATAR_MIN_SIZE), Math.min(max, box)); + } + + private void showAvatarMenu(MouseEvent e) { + Avatar avatar = shownClient == null ? null : shownAvatar; + if (avatar == null || !overAvatar(avatar, e.getPoint())) return; + JPopupMenu menu = new JPopupMenu(); + String name = "avatar_" + shownClient.nickname; + menu.add(item("Save…", null, () -> saveAvatar(avatar, name))); + if (avatarHandler != null && !shownClient.self) { + if (avatarHandler.canSet()) menu.add(item("Steal for avatar", null, () -> avatarHandler.steal(avatar))); + ClientEntry client = shownClient; + if (avatarHandler.canDeleteOthers()) { + menu.add(item("Delete avatar", "DELETE_AVATAR_OTHER", () -> avatarHandler.deleteOf(client))); + } + } else if (avatarHandler != null) { + if (avatarHandler.canSet()) menu.add(item("Set avatar…", "UPLOAD_AVATAR", avatarHandler::set)); + menu.add(item("Delete avatar", "DELETE_AVATAR", avatarHandler::delete)); + } + menu.show(pane, e.getX(), e.getY()); + } + + private static JMenuItem item(String text, String icon, Runnable action) { + JMenuItem item = new JMenuItem(text, icon == null ? null : Icons.of(icon)); + item.addActionListener(e -> action.run()); + return item; + } + + /** Whether {@code point} falls on the avatar's {@code }. */ + private boolean overAvatar(Avatar avatar, Point point) { + if (avatar.file() == null) return false; + String src = avatar.file().toURI().toString(); + int pos = pane.viewToModel2D(point); + for (int at : new int[]{pos, pos - 1}) { + if (at < 0) continue; + var el = ((HTMLDocument) pane.getDocument()).getCharacterElement(at); + AttributeSet attrs = el.getAttributes(); + if (attrs.getAttribute(StyleConstants.NameAttribute) != HTML.Tag.IMG + || !src.equals(attrs.getAttribute(HTML.Attribute.SRC))) continue; + try { + Rectangle2D start = pane.modelToView2D(el.getStartOffset()); + Rectangle2D end = pane.modelToView2D(el.getEndOffset()); + if (start != null && end != null && start.createUnion(end).contains(point)) return true; + } catch (BadLocationException ignored) { + } + } + return false; + } + + private void saveAvatar(Avatar avatar, String name) { + JFileChooser chooser = new JFileChooser(); + chooser.setDialogTitle("Save avatar"); + chooser.setSelectedFile(new File(name + "." + avatar.format().extension)); + if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return; + try { + Files.write(chooser.getSelectedFile().toPath(), avatar.data()); + } catch (IOException ex) { + JOptionPane.showMessageDialog(this, "Could not save the avatar: " + ex.getMessage(), + "Error", JOptionPane.ERROR_MESSAGE); + } + } + + private String clientBody(ClientEntry cl, ServerModel model, IconRepository icons, Contact contact, + Avatar avatar, int avatarBox) { + String details = clientDetails(cl, model, icons, contact); + String picture = AvatarHtml.imgTag(avatar, avatarBox); + if (picture.isEmpty()) return details; + // The avatar sits top-right beside the details, like the official client's info frame. + return "" + + "" + + "" + + "
    " + details + "" + picture + "
    "; + } + + private String clientDetails(ClientEntry cl, ServerModel model, IconRepository icons, Contact contact) { + String you = cl.self ? " (you)" : ""; + // The country's flag goes before the name, as in TeamSpeak's info frame. + return html(Details.client(cl, model, contact), flagTag(cl.country), you, icons, null); + } + + /** + * @param titlePrefix HTML before the title + * @param titleSuffix HTML after the title + * @param icons for the icons of the groups a field names; null for none + * @param none what to say when there is no description; null to say nothing + */ + private String html(Details details, String titlePrefix, String titleSuffix, IconRepository icons, String none) { + StringBuilder sb = new StringBuilder(); + sb.append(heading(titlePrefix + esc(details.title()) + titleSuffix)); + for (Details.Field f : details.fields()) row(sb, esc(f.label()), value(f, icons)); + if (!details.description().isEmpty()) { + sb.append("
    ").append(description(details.description())).append("
    "); + } else if (details.pending()) { + sb.append("
    Loading description…"); + } else if (none != null) { + sb.append("
    ").append(none).append(""); + } + return sb.toString(); + } + + private static String value(Details.Field field, IconRepository icons) { + if (field.groups().isEmpty() || icons == null) return esc(field.value()); + StringBuilder sb = new StringBuilder(); + for (Group g : field.groups()) { + if (sb.length() > 0) sb.append(", "); + sb.append(iconTag(g, icons)).append(esc(g.name)); + } + return sb.toString(); + } + + private void setHtml(String body) { + pane.setText("" + body + ""); + pane.setCaretPosition(0); + } + + /** + * An inline {@code } for a group's icon, or nothing while the icon is missing + * or still downloading. Swing's HTML renderer only loads images by URL, so the icon + * is served from the repository's on-disk cache. + */ + private static String iconTag(Group group, IconRepository icons) { + if (group.iconId == 0) return ""; + File file = icons.file(group.iconId); + if (file == null) return ""; + return " "; + } + + /** An inline {@code } for a country's flag, or nothing for no country. */ + private static String flagTag(String country) { + File file = IconFiles.flag(country); + if (file == null) return ""; + return " "; + } + + private static String heading(String text) { + return "
    " + text + "
    "; + } + + private static void row(StringBuilder sb, String label, String value) { + sb.append("
    ") + .append(label).append(": ").append(value).append("
    "); + } + + /** Descriptions may carry BBCode markup, pictures included. */ + private String description(String bbcode) { + String html = BBCode.toHtml(bbcode, true); + if (!DescriptionPictures.hasPictures(html)) return html; + showsPictures = true; + renderedPictureWidth = pictureWidth(); + return pictures.html(html, renderedPictureWidth); + } + + /** + * How wide a picture may be: the panel's width inside its padding, in steps so that + * dragging a divider does not rebuild the HTML on every pixel. + */ + private int pictureWidth() { + if (inChatTab) return UIScale.scale(CHAT_TAB_PICTURE_WIDTH); + int step = UIScale.scale(PICTURE_WIDTH_STEP); + int width = scroll.getViewport().getWidth() - UIScale.scale(24); + return Math.max(step, width / step * step); + } + + private static String esc(String s) { + return BBCode.escape(s); + } + +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/InstanceChannel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/InstanceChannel.java new file mode 100644 index 0000000..c8eedcb --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/InstanceChannel.java @@ -0,0 +1,81 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.config.AppDirs; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.StandardProtocolFamily; +import java.net.UnixDomainSocketAddress; +import java.nio.channels.Channels; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.function.Consumer; + +/** + * Lets a second launch of the client hand what it was started with (a {@code ts3server://} + * link a browser opened) to the instance already running on the same profile, over a Unix + * domain socket. + */ +public final class InstanceChannel { + + private static final int MAX_MESSAGE = 8192; + + private InstanceChannel() { + } + + /** + * In the user's private runtime directory where there is one, as a socket path may not be + * much over 100 bytes and a profile's can be longer; named after the profile, so each + * profile has an instance of its own. + */ + private static Path socketPath() { + String runtime = System.getenv("XDG_RUNTIME_DIR"); + if (runtime == null || runtime.isBlank()) return AppDirs.file("instance.sock").toPath(); + String profile = AppDirs.profile().getAbsolutePath(); + return Path.of(runtime, "ts3j-" + Integer.toHexString(profile.hashCode()) + ".sock"); + } + + /** Sends {@code message} to the running instance; false when there is none to take it. */ + public static boolean send(String message) { + try (SocketChannel channel = SocketChannel.open(UnixDomainSocketAddress.of(socketPath())); + OutputStream out = Channels.newOutputStream(channel)) { + out.write(message.getBytes(StandardCharsets.UTF_8)); + return true; + } catch (IOException | UnsupportedOperationException e) { + return false; + } + } + + /** Takes the messages later launches send, each on a thread of its own; quietly does nothing where it cannot. */ + public static void listen(Consumer onMessage) { + Path path = socketPath(); + ServerSocketChannel server; + try { + AppDirs.createProfile(); + // Left behind by an instance that did not exit cleanly; a live one answered send() already. + Files.deleteIfExists(path); + server = ServerSocketChannel.open(StandardProtocolFamily.UNIX); + server.bind(UnixDomainSocketAddress.of(path)); + path.toFile().deleteOnExit(); + } catch (IOException | UnsupportedOperationException e) { + System.err.println("Cannot take links from other launches: " + e); + return; + } + Thread accept = new Thread(() -> { + while (server.isOpen()) { + try (SocketChannel client = server.accept(); InputStream in = Channels.newInputStream(client)) { + String message = new String(in.readNBytes(MAX_MESSAGE), StandardCharsets.UTF_8).trim(); + if (!message.isEmpty()) onMessage.accept(message); + } catch (IOException e) { + if (!server.isOpen()) return; + } + } + }, "instance-channel"); + accept.setDaemon(true); + accept.start(); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/LevelMeter.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/LevelMeter.java new file mode 100644 index 0000000..f90fd9b --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/LevelMeter.java @@ -0,0 +1,88 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.UIScale; + +import javax.swing.JComponent; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; + +/** + * Horizontal audio level meter with an optional VAD threshold marker. The filled portion + * turns green once the level crosses the threshold, giving immediate visual feedback while + * tuning voice activation. + * + *

    Scaled to {@link eu.lixko.ts3j.client.audio.InputLevel}, matching the TS3 client's slider. + */ +public final class LevelMeter extends JComponent { + + private static final double MIN_DB = eu.lixko.ts3j.client.audio.InputLevel.MIN_DB; + private static final double MAX_DB = eu.lixko.ts3j.client.audio.InputLevel.MAX_DB; + + private volatile double levelDb = MIN_DB; + private volatile double thresholdDb = -40.0; + private volatile boolean showThreshold = true; + private volatile boolean transmitting; + + public LevelMeter() { + setPreferredSize(UIScale.scale(new Dimension(240, 18))); + // A bare JComponent reports no minimum of its own, so a layout tight on space + // collapses the bar to nothing. Keep the height and let only the width give. + setMinimumSize(UIScale.scale(new Dimension(60, 18))); + setMaximumSize(new Dimension(Integer.MAX_VALUE, UIScale.scale(18))); + } + + public void setLevel(double db) { + this.levelDb = db; + repaint(); + } + + public void setThreshold(double db) { + this.thresholdDb = db; + repaint(); + } + + public void setShowThreshold(boolean show) { + this.showThreshold = show; + repaint(); + } + + /** + * Whether the gate is currently open. This is the real transmit decision, which in the + * Automatic and Hybrid modes depends on the speech detector and the hangover as well as + * on the level, so the bar cannot infer it from the threshold alone. + */ + public void setTransmitting(boolean transmitting) { + this.transmitting = transmitting; + repaint(); + } + + private int dbToX(double db, int w) { + double clamped = Math.max(MIN_DB, Math.min(MAX_DB, db)); + return (int) ((clamped - MIN_DB) / (MAX_DB - MIN_DB) * w); + } + + @Override + protected void paintComponent(Graphics g0) { + Graphics2D g = (Graphics2D) g0; + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + int w = getWidth(); + int h = getHeight(); + + g.setColor(new Color(0x2B2B2B)); + int arc = UIScale.scale(6); + g.fillRoundRect(0, 0, w - 1, h - 1, arc, arc); + + int level = dbToX(levelDb, w - 2); + g.setColor(transmitting ? Theme.talking() : new Color(0x5A9BD4)); + g.fillRoundRect(1, 1, Math.max(0, level), h - 3, arc - 1, arc - 1); + + if (showThreshold) { + int tx = dbToX(thresholdDb, w - 2); + g.setColor(new Color(0xF0C419)); + g.fillRect(tx, 1, UIScale.scale(2), h - 3); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/Links.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/Links.java new file mode 100644 index 0000000..74e71f5 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/Links.java @@ -0,0 +1,46 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.session.ServerLink; + +import javax.swing.JOptionPane; +import java.awt.Component; +import java.awt.Desktop; +import java.net.URI; +import java.util.function.Consumer; + +/** + * Opens http(s) links from chat messages and descriptions in the system browser, and + * {@code ts3server://} links in the client itself. + */ +final class Links { + + private static volatile Consumer serverLinks; + + private Links() { + } + + /** Where {@code ts3server://} links go. */ + static void setServerLinkHandler(Consumer handler) { + serverLinks = handler; + } + + static void open(String href, Component parent) { + ServerLink link = ServerLink.parse(href); + Consumer handler = serverLinks; + if (link != null && handler != null) { + handler.accept(link); + return; + } + try { + URI uri = new URI(href); + String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(); + if (!scheme.equals("http") && !scheme.equals("https") && !scheme.equals("ftp")) return; + if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { + Desktop.getDesktop().browse(uri); + return; + } + } catch (Exception ignored) { + } + JOptionPane.showInputDialog(parent, "Could not open the link. Copy it instead:", href); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ListEditorDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ListEditorDialog.java new file mode 100644 index 0000000..6286675 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ListEditorDialog.java @@ -0,0 +1,184 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.DefaultListModel; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JList; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.ListSelectionModel; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Window; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * A small modal editor for a list of text-keyed items: Add, Remove, optionally Move up and + * down, and OK/Cancel. Edits a copy and writes it back only on OK. + */ +abstract class ListEditorDialog extends JDialog { + + protected final DefaultListModel model = new DefaultListModel<>(); + protected final JList list = new JList<>(model); + private final String itemPrompt; + private final JPanel south = new JPanel(new BorderLayout(0, UIScale.scale(8))); + private boolean accepted; + + /** + * @param intro text above the list, or {@code null} + * @param itemPrompt what Add and a double-click ask for + * @param movable whether the order matters, offering Move up and down + */ + ListEditorDialog(Window owner, String title, String intro, String itemPrompt, List items, boolean movable) { + super(owner, title, ModalityType.APPLICATION_MODAL); + this.itemPrompt = itemPrompt; + items.forEach(model::addElement); + + list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + list.addListSelectionListener(e -> { + if (!e.getValueIsAdjusting()) selectionChanged(); + }); + list.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() == 2 && list.getSelectedIndex() >= 0) rename(list.getSelectedIndex()); + } + }); + JScrollPane scroll = new JScrollPane(list); + scroll.setPreferredSize(UIScale.scale(new Dimension(260, 200))); + + JPanel buttons = new JPanel(); + buttons.setLayout(new BoxLayout(buttons, BoxLayout.Y_AXIS)); + buttons.setOpaque(false); + addButton(buttons, "Add", this::add); + JButton remove = addButton(buttons, "Remove", this::remove); + JButton up = movable ? addButton(buttons, "Move Up", () -> move(-1)) : null; + JButton down = movable ? addButton(buttons, "Move Down", () -> move(1)) : null; + list.addListSelectionListener(e -> { + int i = list.getSelectedIndex(); + remove.setEnabled(i >= 0); + if (up != null) up.setEnabled(i > 0); + if (down != null) down.setEnabled(i >= 0 && i < model.size() - 1); + }); + remove.setEnabled(false); + if (up != null) up.setEnabled(false); + if (down != null) down.setEnabled(false); + + JPanel center = new JPanel(new BorderLayout(UIScale.scale(8), UIScale.scale(6))); + center.setOpaque(false); + if (intro != null) center.add(ReasonDialog.label(intro), BorderLayout.NORTH); + center.add(scroll, BorderLayout.CENTER); + center.add(buttons, BorderLayout.EAST); + + JButton ok = new JButton("OK"); + ok.addActionListener(e -> { + accepted = true; + dispose(); + }); + JButton cancel = new JButton("Cancel"); + cancel.addActionListener(e -> dispose()); + JPanel okCancel = new JPanel(new FlowLayout(FlowLayout.RIGHT, UIScale.scale(6), 0)); + okCancel.setOpaque(false); + okCancel.add(ok); + okCancel.add(cancel); + + south.setOpaque(false); + south.add(okCancel, BorderLayout.SOUTH); + + JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(8))); + content.setBackground(Theme.windowBg()); + content.setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); + content.add(center, BorderLayout.CENTER); + content.add(south, BorderLayout.SOUTH); + setContentPane(content); + getRootPane().setDefaultButton(ok); + Dialogs.closeOnEscape(this); + } + + /** Controls under the list acting on the selected item, or {@code null}. */ + protected JComponent extraControls() { + return null; + } + + protected void selectionChanged() { + } + + /** The item that {@code text} names, typed into Add, or a rename of {@code old} ({@code null} on Add). */ + protected abstract T item(String text, T old); + + protected abstract String text(T item); + + /** Shows the dialog; on OK copies the edited list into {@code target}. */ + protected boolean showAndApply(List target) { + JComponent extra = extraControls(); + if (extra != null) south.add(extra, BorderLayout.NORTH); + selectionChanged(); + pack(); + setLocationRelativeTo(getOwner()); + setVisible(true); + if (!accepted) return false; + target.clear(); + target.addAll(Collections.list(model.elements())); + return true; + } + + private JButton addButton(JPanel column, String text, Runnable action) { + JButton b = new JButton(text); + b.setAlignmentX(Component.LEFT_ALIGNMENT); + b.setMaximumSize(new Dimension(Integer.MAX_VALUE, b.getPreferredSize().height)); + b.addActionListener(e -> action.run()); + if (column.getComponentCount() > 0) column.add(Box.createVerticalStrut(UIScale.scale(4))); + column.add(b); + return b; + } + + private void add() { + String text = ask(itemPrompt, ""); + if (text == null) return; + model.addElement(item(text, null)); + list.setSelectedIndex(model.size() - 1); + } + + private void rename(int index) { + String text = ask(itemPrompt, text(model.get(index))); + if (text != null) model.set(index, item(text, model.get(index))); + } + + private String ask(String prompt, String initial) { + Object answer = JOptionPane.showInputDialog(this, prompt, getTitle(), JOptionPane.PLAIN_MESSAGE, + null, null, initial); + String text = answer == null ? null : answer.toString().trim(); + return text == null || text.isEmpty() ? null : text; + } + + private void remove() { + int i = list.getSelectedIndex(); + if (i < 0) return; + model.remove(i); + if (!model.isEmpty()) list.setSelectedIndex(Math.min(i, model.size() - 1)); + } + + private void move(int delta) { + int i = list.getSelectedIndex(); + int j = i + delta; + if (i < 0 || j < 0 || j >= model.size()) return; + List items = new ArrayList<>(Collections.list(model.elements())); + Collections.swap(items, i, j); + model.clear(); + items.forEach(model::addElement); + list.setSelectedIndex(j); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/LookAndFeelManager.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/LookAndFeelManager.java new file mode 100644 index 0000000..805dfe7 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/LookAndFeelManager.java @@ -0,0 +1,52 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.FlatDarkLaf; +import com.formdev.flatlaf.FlatLaf; +import com.formdev.flatlaf.FlatLightLaf; +import eu.lixko.ts3j.client.config.Settings; + +import java.awt.Window; + +/** + * Installs FlatLaf in the requested variant and keeps {@link Theme} in step with it. + * + *

    The client's own look-and-feel defaults — rounded controls, and the darker palette + * the dark theme is built on — live beside this class as FlatLaf properties files, which + * FlatLaf loads on top of the theme's own. + */ +public final class LookAndFeelManager { + + /** Where our own FlatLaf properties files sit. */ + private static final String DEFAULTS_PACKAGE = "eu.lixko.ts3j.client.ui.laf"; + + static { + // Registered once: FlatLaf keeps every registration, and install() runs again on + // each theme switch. + FlatLaf.registerCustomDefaultsSource(DEFAULTS_PACKAGE); + } + + private LookAndFeelManager() { + } + + /** Installs the look-and-feel for {@code appearance}. Call before building any window. */ + public static void install(Settings.Appearance appearance) { + FlatLaf laf = appearance == Settings.Appearance.DARK ? new FlatDarkLaf() : new FlatLightLaf(); + // Whatever look-and-feel stays installed on failure, Theme falls back to its own palette. + FlatLaf.setup(laf); + Theme.refresh(); + } + + /** + * Switches the look-and-feel of the running client. Components that read {@link Theme} + * while painting follow immediately; the ones that copied a colour when they were built + * are refreshed by the look-and-feel update. + */ + public static void switchTo(Settings.Appearance appearance) { + install(appearance); + IconTheme.get().refresh(); + FlatLaf.updateUI(); + for (Window w : Window.getWindows()) { + w.repaint(); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainFrame.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainFrame.java new file mode 100644 index 0000000..bbb7e71 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainFrame.java @@ -0,0 +1,1170 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.audio.AudioBackend; +import eu.lixko.ts3j.client.audio.desktop.DesktopAudioBackend; +import eu.lixko.ts3j.client.config.AppDirs; +import eu.lixko.ts3j.client.config.AwayMessages; +import eu.lixko.ts3j.client.config.BanReasonPresets; +import eu.lixko.ts3j.client.config.Bookmark; +import eu.lixko.ts3j.client.config.Bookmarks; +import eu.lixko.ts3j.client.session.ServerLink; +import eu.lixko.ts3j.client.config.IdentityStore; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.myts.ChatAttachments; +import eu.lixko.ts3j.client.myts.MyTeamSpeakLogin; +import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter; +import eu.lixko.ts3j.client.contacts.ContactStore; +import eu.lixko.ts3j.client.net.ChannelNode; +import eu.lixko.ts3j.client.net.HostButton; +import eu.lixko.ts3j.client.net.PictureDownloads; +import eu.lixko.ts3j.client.session.SelfState; +import eu.lixko.ts3j.client.session.ServerSession; +import eu.lixko.ts3j.client.session.Sessions; +import eu.lixko.ts3j.client.sound.SoundNotifier; +import eu.lixko.ts3j.client.sound.SoundPlayer; +import eu.lixko.ts3j.client.ui.tray.TrayBackend; + +import javax.swing.AbstractAction; +import javax.swing.JCheckBox; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.JTextField; +import javax.swing.KeyStroke; +import javax.swing.SwingUtilities; +import java.io.File; +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.GridLayout; +import java.awt.KeyboardFocusManager; +import java.awt.Taskbar; +import java.awt.event.ActionEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * The main application window: toolbar, tab bar, status bar and menus, hosting + * one {@link ServerTab} per open server connection. + * + *

    Several servers can be connected at once — their incoming voice is mixed + * into the same output — but only one of them owns the microphone at a time + * ("active" tab, marked in the tab strip and switched from the toolbar). + */ +public final class MainFrame extends JFrame implements ServerTabPane.Listener { + + private final Settings settings; + private final RecordingActions recordings; + private final Bookmarks bookmarks = Bookmarks.load(); + private final AwayMessages awayMessages = AwayMessages.load(); + private final IdentityStore identities; + private final MyTeamSpeakLogin myTeamSpeak = MyTeamSpeakLogin.load(); + /** Friends and blocked clients, shared by every connection. */ + private final ContactStore contacts = ContactStore.load(); + private final AudioBackend audio = new DesktopAudioBackend(); + private final PictureDownloads pictures = new PictureDownloads(new File(AppDirs.profile(), "pictures"), true); + /** Files shared in chat, kept in the myTeamSpeak account's cloud storage. */ + private final ChatAttachments attachments = new ChatAttachments(myTeamSpeak); + private final TextZoom chatZoom; + private final TextZoom infoZoom; + /** Sound pack playback, shared by every connection. */ + private final SoundNotifier sounds; + private final SoundPlayer soundPlayer; + + private final List tabs = new ArrayList<>(); + /** The tabs' sessions: who holds the microphone, and the state shared by every server. */ + private final Sessions sessions = new Sessions(() -> { + refreshTabs(); + updateTray(); + }); + private final ServerTabPane tabPane = new ServerTabPane(this); + + /** The tab whose views are on screen. */ + private ServerTab selected; + private BanReasonPresets banReasonPresets; + + private MainMenuBar menuBar; + private javax.swing.Timer statusTimer; + + /** Mirrors the active server's own client state next to the clock; set once the window is up. */ + private volatile TrayController tray; + private GiantPttWindow giantPtt; + private final DesktopNotifier notifier; + + private MainToolbar toolbar; + private StatusBar statusBar; + + /** Global hotkeys: the bindings, the matching engine and the platform input hook. */ + private final HotkeyService hotkeys; + + /** Guards {@link #shutdown()} so the window listener and JVM hook don't both run it. */ + private final AtomicBoolean shuttingDown = new AtomicBoolean(false); + private final Thread shutdownHook = new Thread(this::shutdown, "ts3j-shutdown"); + + public MainFrame(Settings settings) { + super("TeamSpook TS3j"); + this.settings = settings; + this.recordings = new RecordingActions(this, settings); + this.chatZoom = new TextZoom(settings.chatZoom, z -> { + settings.chatZoom = z; + settings.save(); + }); + this.infoZoom = new TextZoom(settings.infoZoom, z -> { + settings.infoZoom = z; + settings.save(); + }); + this.identities = IdentityStore.load(settings); + new TeamSpeakImporter(identities, bookmarks, settings).seedIfFresh(); + this.sounds = new SoundNotifier(settings); + this.soundPlayer = audio.createSoundPlayer(settings); + this.sounds.setPlayer(soundPlayer); + this.notifier = new DesktopNotifier(this, settings); + pictures.addSource("tsattach:", attachments::fetchPicture); + // Any of the client's windows coming to the front counts, a dialog included. + KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("activeWindow", e -> { + if (e.getNewValue() != null) notifier.windowActivated(); + }); + this.hotkeys = new HotkeyService(new HotkeyActions(this), this::hotkeyArgumentChoices); + hotkeys.addKeyPressListener(() -> SwingUtilities.invokeLater(sessions::keyPressed)); + contacts.addListener(() -> SwingUtilities.invokeLater(this::contactsChanged)); + + setIconImages(Icons.appImages()); + // The macOS dock ignores window icons. + if (Taskbar.isTaskbarSupported() && Taskbar.getTaskbar().isSupported(Taskbar.Feature.ICON_IMAGE)) { + Taskbar.getTaskbar().setIconImage(Icons.app(256).getImage()); + } + // We tear the connections down ourselves on close, so don't let Swing kill the JVM. + setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + quit(); + } + + @Override + public void windowOpened(WindowEvent e) { + // Docking waits for the panel to adopt the icon, so it must not hold up the window. + SwingUtilities.invokeLater(MainFrame.this::installTray); + } + }); + // Catches Ctrl+C / SIGTERM so we still leave the servers cleanly. + Runtime.getRuntime().addShutdownHook(shutdownHook); + setMinimumSize(UIScale.scale(new Dimension(720, 480))); + + menuBar = buildMenuBar(); + setJMenuBar(menuBar); + + toolbar = buildToolbar(); + add(toolbar, BorderLayout.NORTH); + // Switching the icon pack in the options dialog re-decorates the whole window. + IconTheme.get().addListener(() -> SwingUtilities.invokeLater(this::rebuildIcons)); + add(tabPane, BorderLayout.CENTER); + // The tree and the chat each claim Ctrl+F for themselves while they have the focus; + // from anywhere else it searches the chat. + getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) + .put(KeyStroke.getKeyStroke("control F"), "ts3-find"); + getRootPane().getActionMap().put("ts3-find", new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + if (selected != null) selected.chat().openFind(); + } + }); + statusBar = new StatusBar(() -> { + if (selected != null) selected.session().stopRecording(); + }, () -> { + if (selected != null) selected.showOfflineMessages(); + }); + statusBar.setVisible(settings.showStatusBar); + add(statusBar, BorderLayout.SOUTH); + + statusBar.setCodec(audio.description()); + + ServerTab first = newTab(); + selectTab(first); + first.chat().appendSystem("Welcome to TeamSpook TS3j."); + first.chat().appendSystem("Use Connections → Connect to join a server."); + + Links.setServerLinkHandler(this::openServerLink); + + statusTimer = new javax.swing.Timer(3000, e -> updateConnectionStatus()); + statusTimer.start(); + setSize(UIScale.scale(new Dimension(880, 560))); + setLocationRelativeTo(null); + + // Deferred so the window is on screen before we start connecting. + List startup = bookmarks.startupBookmarks(); + if (!startup.isEmpty()) { + SwingUtilities.invokeLater(() -> { + for (Bookmark b : startup) connectToBookmark(b); + }); + } + } + + // ---- UI construction ---- + + private MainMenuBar buildMenuBar() { + return new MainMenuBar(bookmarks, new MainMenuBar.Listener() { + @Override + public void onConnect() { + showConnectDialog(); + } + + @Override + public void onDisconnect() { + doDisconnect(); + } + + @Override + public void onCloseTab() { + closeTab(selected); + } + + @Override + public void onQuit() { + quit(); + } + + @Override + public void onActivate() { + moveMicrophoneToSelectedTab(); + } + + @Override + public void onToggleMic() { + toolbar.clickMic(); + } + + @Override + public void onToggleSpeaker() { + toolbar.clickSpeaker(); + } + + @Override + public void onAwayToggle(boolean away) { + toggleAway(away); + } + + @Override + public void onAwayStatus() { + setAwayStatus(); + } + + @Override + public JPopupMenu buildAwayMenu() { + return MainFrame.this.buildAwayMenu(); + } + + @Override + public void onCommanderToggle(boolean commander) { + if (selected != null) selected.session().setCommander(commander); + } + + @Override + public void onChangeNickname() { + changeNickname(); + } + + @Override + public boolean isTalkPowerRequested() { + return selected != null && selected.session().isTalkRequested(); + } + + @Override + public void onRequestTalkPower() { + requestTalkPower(); + } + + @Override + public void onSetPhoneticNickname() { + setPhoneticNickname(); + } + + @Override + public boolean canSetAvatar() { + return selected != null && selected.session().canSetAvatar(); + } + + @Override + public void onSetAvatar() { + if (selected != null) selected.avatar().choose(); + } + + @Override + public boolean hasAvatar() { + return selected != null && selected.session().hasAvatar(); + } + + @Override + public void onDeleteAvatar() { + if (selected != null) selected.avatar().delete(); + } + + @Override + public void onGiantPtt() { + showGiantPtt(); + } + + @Override + public void onShowIdentities() { + showIdentities(); + } + + @Override + public void onShowContacts() { + showContacts(null); + } + + @Override + public boolean isRecording() { + return selected != null && selected.session().isRecording(); + } + + @Override + public void onStartRecording(boolean multitrack) { + if (selected != null) recordings.choose(selected.session(), multitrack); + } + + @Override + public void onStopRecording() { + if (selected != null) selected.session().stopRecording(); + } + + @Override + public void onShowOfflineMessages() { + if (selected != null) selected.showOfflineMessages(); + } + + @Override + public boolean canViewBanList() { + return selected != null && selected.session().canViewBanList(); + } + + @Override + public void onShowBanList() { + if (selected != null) selected.showBanList(banReasonPresets()); + } + + @Override + public boolean canViewComplaints() { + return selected != null && selected.session().canViewComplaints(); + } + + @Override + public void onShowComplaints() { + if (selected != null) selected.showComplaints(); + } + + @Override + public boolean canViewServerLog() { + return selected != null && selected.session().canViewServerLog(); + } + + @Override + public void onShowServerLog() { + if (selected != null) selected.showServerLog(); + } + + @Override + public boolean canListPrivilegeKeys() { + return selected != null && selected.session().canListPrivilegeKeys(); + } + + @Override + public void onShowPrivilegeKeys() { + if (selected != null) selected.showPrivilegeKeys(); + } + + @Override + public void onUsePrivilegeKey() { + if (selected != null) selected.usePrivilegeKey(); + } + + @Override + public void onShowSettings() { + showSettings(); + } + + @Override + public void onShowAbout() { + showAbout(); + } + + @Override + public void onConnectBookmark(Bookmark bookmark, boolean newTab) { + if (newTab) selectTab(newTab()); + connectToBookmark(bookmark); + } + + @Override + public void onAddCurrentServerBookmark() { + addCurrentServerBookmark(); + } + + @Override + public void onManageBookmarks() { + new BookmarksDialog(MainFrame.this, bookmarks, identities, settings, + MainFrame.this::connectToBookmark, menuBar::rebuildBookmarks).setVisible(true); + } + }); + } + + private MainToolbar buildToolbar() { + return new MainToolbar(settings, new MainToolbar.Listener() { + @Override + public void onConnect() { + showConnectDialog(); + } + + @Override + public void onDisconnect() { + doDisconnect(); + } + + @Override + public void onActivate() { + moveMicrophoneToSelectedTab(); + } + + @Override + public void onMicMuteToggle(boolean muted) { + if (selected == null) return; + selected.session().setMicMuted(muted); + updateToolbar(); + } + + @Override + public void onDeafenToggle(boolean deafened) { + if (selected == null) return; + selected.session().setDeafened(deafened); + updateToolbar(); + } + + @Override + public void onAwayToggle(boolean away) { + toggleAway(away); + } + + @Override + public JPopupMenu buildAwayMenu() { + return MainFrame.this.buildAwayMenu(); + } + + @Override + public void onSettings() { + showSettings(); + } + + @Override + public void onMasterVolumeChanged() { + applyOutputSettingsToAllTabs(); + } + + @Override + public void onStatusBarVisibilityChanged(boolean visible) { + statusBar.setVisible(visible); + revalidate(); + repaint(); + } + }, pictures); + } + + /** Rebuilds the icon-bearing chrome after the active icon pack changed. */ + private void rebuildIcons() { + setIconImages(Icons.appImages()); + menuBar = buildMenuBar(); + setJMenuBar(menuBar); + remove(toolbar); + toolbar = buildToolbar(); + add(toolbar, BorderLayout.NORTH); + updateToolbar(); + refreshTabs(); + if (tray != null) tray.refreshIcon(); + revalidate(); + repaint(); + } + + // ---- tab management ---- + + private ServerTab newTab() { + ServerTab tab = new ServerTab(this, settings, identities, audio, sounds, contacts, pictures); + tabs.add(tab); + sessions.add(tab.session()); + tabPane.addTab(tab); + refreshTabs(); + return tab; + } + + /** The tab a new connection should use: the current one if it is free, else a new one. */ + private ServerTab tabForNewConnection() { + if (selected != null && !selected.session().isBusy()) return selected; + ServerTab tab = newTab(); + selectTab(tab); + return tab; + } + + @Override + public void selectTab(ServerTab tab) { + if (tab == null || !tabs.contains(tab)) return; + selected = tab; + tabPane.setSelected(tab); + refreshTabs(); + updateToolbar(); + updateStatusLabel(); + } + + @Override + public void closeTab(ServerTab tab) { + if (tab == null) return; + tab.session().disconnect(); + if (tabs.size() == 1) return; // always keep one view around + + tabs.remove(tab); + tab.session().dispose(); + tabPane.removeTab(tab); + if (selected == tab) { + selected = null; + selectTab(tabs.get(0)); + } else { + selectTab(selected); // the pane rebuilt itself; restore the selection + } + sessions.remove(tab.session()); + } + + /** The tab that holds the capture device; null when nobody is capturing. */ + private ServerTab micTab() { + ServerSession owner = sessions.microphoneOwner(); + for (ServerTab tab : tabs) { + if (tab.session() == owner) return tab; + } + return null; + } + + /** Repaints the tab labels (title, microphone marker). */ + private void refreshTabs() { + tabPane.refresh(micTab()); + } + + // ---- callbacks from ServerTab ---- + + /** A tab's title, status or connection state changed. */ + void tabUpdated(ServerTab tab) { + if (!tabs.contains(tab)) return; + refreshTabs(); + if (tab == selected) { + updateToolbar(); + updateStatusLabel(); + } + updateTray(); + } + + /** The server on {@code tab} may have changed its host button. */ + void refreshHostButton(ServerTab tab) { + if (tab == selected) toolbar.showHostButton(hostButtonOf(tab)); + } + + /** Bookmarks leading to the server on {@code tab} take on its icon. */ + void serverIconChanged(ServerTab tab, long iconId) { + if (!bookmarks.rememberServerIcon(tab.session().address(), tab.session().port(), iconId)) return; + bookmarks.save(); + menuBar.rebuildBookmarks(); + } + + /** The local client on {@code tab} started or stopped talking, muted itself, … */ + void selfStateChanged(ServerTab tab) { + if (!tabs.contains(tab)) return; + updateTray(); + if (giantPtt != null) giantPtt.refresh(); + } + + void tabConnected(ServerTab tab) { + if (!tabs.contains(tab)) return; + sessions.connected(tab.session()); + tabUpdated(tab); + } + + void tabDisconnected(ServerTab tab) { + if (!tabs.contains(tab)) return; + sessions.disconnected(tab.session()); + notifier.forget(tab); + tabUpdated(tab); + } + + /** Tells the user of a poke or a private message while the client is in the background. */ + TextZoom chatZoom() { + return chatZoom; + } + + TextZoom infoZoom() { + return infoZoom; + } + + DesktopNotifier notifier() { + return notifier; + } + + /** The tray icon when AWT docked it, whose messages are the notifications on Windows and macOS. */ + TrayBackend awtTray() { + TrayController current = tray; + return current == null ? null : current.backend(); + } + + // ---- hotkeys ---- + + /** + * Which connections a fired hotkey reaches: with "on active server" ticked only the + * selected tab, otherwise every connected one. + */ + List hotkeyTargets(boolean activeServerOnly) { + List out = new ArrayList<>(); + if (activeServerOnly) { + if (selected != null && selected.session().isConnected()) out.add(selected); + return out; + } + for (ServerTab tab : tabs) { + if (tab.session().isConnected()) out.add(tab); + } + return out; + } + + RecordingActions recordings() { + return recordings; + } + + ServerTab selectedTab() { + return selected; + } + + List allTabs() { + return new ArrayList<>(tabs); + } + + /** Opens the microphone while a push-to-talk hotkey is held. */ + void setPushToTalk(boolean talking) { + sessions.setPushToTalk(talking); + } + + private void showGiantPtt() { + if (giantPtt == null || !giantPtt.isDisplayable()) { + giantPtt = new GiantPttWindow(this, sessions::setForceTransmit, () -> { + ServerSession owner = sessions.microphoneOwner(); + SelfState state = owner == null ? null : owner.selfState(); + return state == SelfState.TALKING || state == SelfState.COMMANDER_TALKING; + }); + } + giantPtt.setVisible(true); + giantPtt.toFront(); + } + + void moveMicrophoneToSelectedTab() { + if (selected != null && selected.session().isConnected()) sessions.giveMicrophoneTo(selected.session()); + updateToolbar(); + } + + /** Connects to the bookmark with this label; no label means the first one. */ + void connectBookmark(String label, boolean newTab) { + Bookmark match = null; + for (Bookmark b : bookmarks.all()) { + if (label == null || label.isBlank() || label.equalsIgnoreCase(b.label)) { + match = b; + break; + } + } + if (match == null) return; + if (newTab) selectTab(newTab()); + connectToBookmark(match); + } + + /** Selects the tab with this 1-based number, as the "Select Server Tab" action names it. */ + void selectTabNumber(int number) { + if (number >= 1 && number <= tabs.size()) selectTab(tabs.get(number - 1)); + } + + void stepTab(int delta) { + if (tabs.isEmpty()) return; + int index = Math.max(0, tabs.indexOf(selected)); + selectTab(tabs.get(Math.floorMod(index + delta, tabs.size()))); + } + + void setSoundsMuted(boolean muted) { + sounds.setMuted(muted); + } + + boolean areSoundsMuted() { + return sounds.isMuted(); + } + + void adjustMasterVolume(double delta) { + settings.outputVolume = Math.max(0, Math.min(2.0, settings.outputVolume + delta)); + settings.save(); + applyOutputSettingsToAllTabs(); + updateStatusLabel(); + } + + /** Applies a new nickname, or asks for one when the hotkey carries none. */ + void changeNickname(String nickname) { + if (nickname == null || nickname.isBlank()) { + changeNickname(); + return; + } + settings.nickname = nickname.trim(); + settings.save(); + sessions.setNickname(settings.nickname); + } + + void browseCurrentChannel() { + if (selected == null || !selected.session().isConnected()) return; + ChannelNode channel = selected.session().currentChannel(); + if (channel != null) selected.browseFiles(channel); + } + + void reloadSkin() { + IconTheme.get().reload(settings); + } + + /** Brings the window back from the tray, the taskbar or behind other windows. */ + void bringToFront() { + TrayController current = tray; + if (current != null) { + // The tray can ask the window manager in a way it honours for a window without focus. + current.show(); + return; + } + setVisible(true); + setExtendedState(getExtendedState() & ~JFrame.ICONIFIED); + toFront(); + requestFocus(); + } + + void sendToBack() { + setExtendedState(getExtendedState() | JFrame.ICONIFIED); + } + + /** + * The values a parameterised hotkey action can take, for the tree in the hotkey + * dialog: the saved bookmarks, the installed sound packs and the channels of the + * server on screen. + */ + private List hotkeyArgumentChoices(eu.lixko.ts3j.client.hotkey.HotkeyAction action) { + List out = new ArrayList<>(); + switch (action.argument()) { + case BOOKMARK -> { + for (Bookmark b : bookmarks.all()) { + if (b.label != null && !b.label.isBlank()) out.add(b.label); + } + } + case PROFILE -> { + if (action == eu.lixko.ts3j.client.hotkey.HotkeyAction.SOUNDPACK_ACTIVATE) { + for (eu.lixko.ts3j.client.sound.SoundPack pack : sounds.availablePacks()) out.add(pack.name()); + } + } + case CHANNEL -> { + if (selected != null && selected.session().isConnected()) { + out.addAll(selected.session().channelPaths()); + } + } + default -> { + } + } + return out; + } + + /** Repaints the chrome after a hotkey changed the local client's state. */ + void refreshAfterHotkey() { + updateToolbar(); + updateTray(); + refreshTabs(); + } + + // ---- actions ---- + + private void showConnectDialog() { + ConnectDialog dlg = new ConnectDialog(this, settings, identities); + dlg.setVisible(true); + if (!dlg.isConfirmed()) return; + startConnection(dlg.getAddress(), dlg.getPort(), dlg.getNickname(), dlg.getPassword(), + dlg.getIdentityId(), "", ""); + } + + /** + * Opens a connection in the current tab when it is free, otherwise in a new one. + * + * @param identityId identity to use, or empty for the default one + * @param channel channel path to join on connect, or empty for the default channel + * @param channelPassword password for that channel, if any + */ + private void startConnection(String address, int port, String nickname, String password, String identityId, + String channel, String channelPassword) { + startConnection(address, port, nickname, password, identityId, channel, channelPassword, false); + } + + /** + * @param replaceCurrent connect on the current tab, leaving the server it is on, instead of + * moving to a free tab + */ + private void startConnection(String address, int port, String nickname, String password, String identityId, + String channel, String channelPassword, boolean replaceCurrent) { + settings.lastAddress = address + ":" + port; + if (!nickname.isBlank()) settings.nickname = nickname; + settings.serverPassword = password; + settings.save(); + + ServerTab tab = (replaceCurrent && selected != null) ? selected : tabForNewConnection(); + // The first connection to come up takes the microphone; later ones are muted + // until the user activates them. + if (sessions.microphoneOwner() == null) sessions.giveMicrophoneTo(tab.session()); + tab.session().switchTo(address, port, nickname, password, identityId, channel, channelPassword); + } + + /** Opens a {@code ts3server://} link handed over by the system or a later launch. */ + public void openLink(String href) { + ServerLink link = ServerLink.parse(href); + if (link == null) return; + bringToFront(); + openServerLink(link); + } + + /** Goes where a link leads: on a server we are on already, to its channel; else connects there. */ + private void openServerLink(ServerLink link) { + if (!link.bookmarkLabel.isEmpty()) { + bookmarks.add(link.toBookmark()); + bookmarks.save(); + menuBar.rebuildBookmarks(); + } + for (ServerTab tab : tabs) { + if (tab.session().isOn(link)) { + selectTab(tab); + tab.session().follow(link); + return; + } + } + ServerTab tab = tabForNewConnection(); + if (sessions.microphoneOwner() == null) sessions.giveMicrophoneTo(tab.session()); + tab.session().open(link, ""); + } + + /** Connects on the current tab, leaving whatever server it is on. */ + private void connectToBookmark(Bookmark b) { + startConnection(b.address, b.port, b.nickname == null ? "" : b.nickname, b.password, b.identityId, b.channel, b.channelPassword, true); + } + + private void addCurrentServerBookmark() { + if (selected == null || !selected.session().isConnected()) { + JOptionPane.showMessageDialog(this, "Connect to a server first.", + "Add bookmark", JOptionPane.INFORMATION_MESSAGE); + return; + } + String channelPath = selected.session().currentChannelPath(); + + JTextField labelField = new JTextField(selected.session().title()); + JCheckBox joinChannel = new JCheckBox("Join \"" + channelPath + "\" on connect", !channelPath.isEmpty()); + JPanel form = new JPanel(new GridLayout(0, 1, 0, UIScale.scale(2))); + form.add(new JLabel("Bookmark label:")); + form.add(labelField); + if (!channelPath.isEmpty()) form.add(joinChannel); + if (JOptionPane.showConfirmDialog(this, form, "Add bookmark", + JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) != JOptionPane.OK_OPTION) { + return; + } + Bookmark bookmark = selected.session().toBookmark(joinChannel.isSelected() ? channelPath : ""); + bookmark.label = labelField.getText().trim(); + bookmarks.add(bookmark); + bookmarks.save(); + menuBar.rebuildBookmarks(); + } + + /** The away button's drop-down: the global actions, the presets and their editor. */ + private JPopupMenu buildAwayMenu() { + JPopupMenu menu = new JPopupMenu(); + boolean anyConnected = sessions.anyConnected(); + + JCheckBoxMenuItem globally = new JCheckBoxMenuItem("Set Globally Away", Icons.of("AWAY"), + sessions.isAwayEverywhere()); + globally.setEnabled(anyConnected); + globally.addActionListener(e -> setAwayEverywhere(globally.isSelected(), null)); + + JMenuItem globalStatus = new JMenuItem("Set Globally Away Status…", Icons.of("EDIT")); + globalStatus.setEnabled(anyConnected); + globalStatus.addActionListener(e -> { + String message = askAwayMessage(sessions.awayMessage(selected == null ? null : selected.session())); + if (message != null) setAwayEverywhere(true, message); + }); + + menu.add(globally); + menu.add(globalStatus); + menu.addSeparator(); + + for (String preset : awayMessages.all()) { + JMenuItem item = new JMenuItem(preset); + item.setEnabled(anyConnected); + item.addActionListener(e -> setAwayEverywhere(true, preset)); + menu.add(item); + } + if (!awayMessages.all().isEmpty()) menu.addSeparator(); + + JMenuItem manage = new JMenuItem("Manage away messages…", Icons.of("EDIT")); + manage.addActionListener(e -> new AwayMessagesDialog(this, awayMessages, null).setVisible(true)); + menu.add(manage); + return menu; + } + + private void toggleAway(boolean away) { + if (selected == null) return; + selected.session().setAway(away, ""); + updateToolbar(); + } + + /** Sets the away message on the selected server only. */ + private void setAwayStatus() { + if (selected == null) return; + String message = askAwayMessage(selected.session().awayMessage()); + if (message == null) return; + selected.session().setAway(true, message); + updateToolbar(); + } + + private void setAwayEverywhere(boolean away, String message) { + sessions.setAwayEverywhere(away, message); + updateToolbar(); + } + + /** @return the entered message (possibly empty), or null when cancelled */ + private String askAwayMessage(String initial) { + return (String) JOptionPane.showInputDialog(this, "Away message (optional):", "Away status", + JOptionPane.PLAIN_MESSAGE, Icons.of("AWAY"), null, initial); + } + + private void doDisconnect() { + if (selected != null) selected.session().disconnect(); + } + + /** + * Tear everything down before the process exits: disconnect from every server + * synchronously (so the "Leaving" notification actually reaches them) and stop + * background timers. Idempotent and safe to call from any thread — the window + * close handler, the Quit menu and the JVM shutdown hook may all invoke it. + */ + private void shutdown() { + if (!shuttingDown.compareAndSet(false, true)) return; + if (statusTimer != null) statusTimer.stop(); + settings.save(); // keeps the layout the user left behind (info panel height, …) + try { + Runtime.getRuntime().removeShutdownHook(shutdownHook); + } catch (IllegalStateException ignored) { + // Already shutting down (hook itself is running); nothing to remove. + } + sessions.shutdown(); + contacts.flush(); + soundPlayer.shutdown(); + hotkeys.dispose(); + if (tray != null) tray.dispose(); + notifier.shutdown(); + // Ends the sharing session if myTeamSpeak answers soon; it expires on its own otherwise. + try { + Thread.ofVirtual().start(attachments::close).join(2000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + /** Leaves every server and ends the process. */ + private void quit() { + shutdown(); + System.exit(0); + } + + /** Loaded the first time a ban dialog needs them, and shared by every tab from then on. */ + private BanReasonPresets banReasonPresets() { + if (banReasonPresets == null) banReasonPresets = BanReasonPresets.load(); + return banReasonPresets; + } + + private void showIdentities() { + new IdentitiesDialog(this, identities, settings, bookmarks, null).setVisible(true); + } + + Settings settings() { + return settings; + } + + /** The one contacts window, kept so a second request brings it forward instead of doubling it. */ + private ContactsDialog contactsDialog; + + /** + * Opens the contact list, or brings it forward. + * + * @param uniqueId the contact to select, or {@code null} to keep the current selection + */ + void showContacts(String uniqueId) { + if (contactsDialog == null || !contactsDialog.isDisplayable()) { + contactsDialog = new ContactsDialog(this, contacts, settings); + } + if (uniqueId != null) contactsDialog.select(uniqueId); + contactsDialog.setVisible(true); + contactsDialog.toFront(); + } + + /** The contact list changed somewhere: every open server follows. */ + private void contactsChanged() { + for (ServerTab tab : tabs) tab.contactsChanged(); + } + + private void showSettings() { + // Device and voice-gating changes apply to the capturing connection and the + // playback of the visible one; the rest pick the new settings up on connect. + SettingsDialog dlg = new SettingsDialog(this, settings, audio, + sessions.microphoneOwner() == null ? null : sessions.microphoneOwner().connection().getMicrophone(), + selected == null ? null : selected.connection().getPlayback(), + sounds, hotkeys, + new MyTeamSpeakPanel(myTeamSpeak, new TeamSpeakImporter(identities, bookmarks, settings), + menuBar::rebuildBookmarks, this::myTeamSpeakChanged), + () -> { + applyOutputSettingsToAllTabs(); + contactsChanged(); + }); + dlg.setVisible(true); + } + + /** Signed in to or out of myTeamSpeak: sharing in chat follows. */ + private void myTeamSpeakChanged() { + boolean signedIn = myTeamSpeak.isSignedIn(); + for (ServerTab tab : tabs) tab.chat().setSharingAvailable(signedIn); + if (signedIn) { + pictures.retryFailed(); + } else { + Thread.ofVirtual().name("myteamspeak-sign-out").start(attachments::close); + } + } + + ChatAttachments attachments() { + return attachments; + } + + /** Whether files can be shared in chat: that needs a myTeamSpeak account. */ + boolean canShareFiles() { + return myTeamSpeak.isSignedIn(); + } + + /** Master volume, output device and receive buffer are global, so push them to every open connection. */ + private void applyOutputSettingsToAllTabs() { + soundPlayer.setOutputDevice(settings.outputDevice); + for (ServerTab tab : tabs) { + if (tab.connection().getPlayback() == null) continue; + tab.connection().getPlayback().setMasterVolume(settings.effectiveOutputVolume()); + tab.connection().getPlayback().setOutputDevice(settings.outputDevice); + tab.connection().getPlayback().setReceiveBuffer(settings.receiveBuffer); + } + } + + private void changeNickname() { + String n = JOptionPane.showInputDialog(this, "New nickname:", settings.nickname); + if (n != null && !n.trim().isEmpty()) { + settings.nickname = n.trim(); + settings.save(); + for (ServerTab tab : tabs) tab.session().setNickname(settings.nickname); + } + } + + /** Asks for a reason and requests talk power, or withdraws the pending request. */ + private void requestTalkPower() { + if (selected == null) return; + if (selected.session().isTalkRequested()) { + selected.session().cancelTalkRequest(); + return; + } + String message = (String) JOptionPane.showInputDialog(this, "Reason:", "Request Talk Power", + JOptionPane.PLAIN_MESSAGE, Icons.of("TALK_POWER_REQUEST"), null, ""); + if (message != null) selected.session().requestTalkPower(message.trim()); + } + + private void setPhoneticNickname() { + if (selected == null) return; + String phonetic = (String) JOptionPane.showInputDialog(this, "Phonetic nickname:", "Set Phonetic Nickname", + JOptionPane.PLAIN_MESSAGE, Icons.of("PHONETICSNICKNAME"), null, + selected.session().phoneticNickname()); + if (phonetic != null) selected.session().setPhoneticNickname(phonetic.trim()); + } + + private void showAbout() { + JOptionPane.showMessageDialog(this, + "TeamSpook TS3j\n\n" + + "An open-source TeamSpeak 3 desktop client built on the ts3j\n" + + "reverse-engineered protocol library, with native Opus voice,\n" + + "voice-activation detection and push-to-talk.\n\n" + + statusBar.codecText(), + "About TeamSpook TS3j", JOptionPane.INFORMATION_MESSAGE); + } + + // ---- toolbar / status ---- + + private void updateToolbar() { + boolean connected = selected != null && selected.session().isConnected(); + boolean anyConnected = sessions.anyConnected(); + + boolean micMuted = connected && selected.session().isMicMuted(); + boolean deaf = connected && selected.session().isDeafened(); + boolean active = selected != null && selected == micTab(); + boolean away = connected && selected.session().isAway(); + boolean commander = connected && selected.session().isCommander(); + toolbar.refresh(connected, anyConnected, micMuted, deaf, active, away); + toolbar.showHostButton(hostButtonOf(selected)); + menuBar.refresh(connected, anyConnected, micMuted, deaf, active, away, commander); + statusBar.showRecording(connected && selected.session().isRecording()); + statusBar.showUnreadMessages(connected ? selected.connection().unreadOfflineMessages() : 0); + updateTray(); + } + + private static HostButton hostButtonOf(ServerTab tab) { + return tab != null && tab.session().isConnected() ? tab.connection().getModel().hostButton() : null; + } + + /** + * The server the tray icon speaks for: the one holding the microphone, or the + * visible one when nobody is capturing. + */ + private ServerTab trayTab() { + ServerTab micTab = micTab(); + if (micTab != null && micTab.session().isConnected()) return micTab; + return selected != null && selected.session().isConnected() ? selected : null; + } + + private void installTray() { + if (shuttingDown.get()) return; + tray = new TrayController(this, this::quit); + updateTray(); + } + + private void updateTray() { + if (tray == null) return; + ServerTab tab = trayTab(); + if (tab == null) { + tray.update(SelfState.DISCONNECTED, null); + } else { + tray.update(tab.session().selfState(), tab.session().title()); + } + } + + private void updateStatusLabel() { + statusBar.setStatus(selected == null ? "Not connected" : selected.session().status()); + } + + private void updateConnectionStatus() { + ServerTab tab = selected; + if (tab == null || !tab.session().isConnected()) return; + int users = tab.connection().getModel().clientCount(); + StringBuilder s = new StringBuilder("Connected to ") + .append(tab.connection().getModel().getServerName()) + .append(" | ").append(users).append(users == 1 ? " user" : " users"); + double ping = tab.connection().getPingMillis(); + if (ping >= 0) s.append(" | ping ").append(Math.round(ping)).append(" ms"); + if (tab != micTab()) s.append(" | microphone on another tab"); + statusBar.setStatus(s.toString()); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainMenuBar.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainMenuBar.java new file mode 100644 index 0000000..f0bf986 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainMenuBar.java @@ -0,0 +1,449 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.config.Bookmark; +import eu.lixko.ts3j.client.config.Bookmarks; + +import javax.swing.ImageIcon; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JPopupMenu; +import javax.swing.KeyStroke; +import javax.swing.MenuSelectionManager; +import javax.swing.SwingUtilities; +import javax.swing.event.MenuEvent; +import javax.swing.event.MenuListener; +import java.awt.Component; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +/** + * The main window's menu bar: Connections, Bookmarks, Self, Permissions, Tools and Help. + * Talks to {@link MainFrame} only through {@link Listener}; the away/commander + * item states are pushed in by {@link #refresh}, mirroring how {@link MainToolbar} + * is kept in sync. + */ +final class MainMenuBar extends JMenuBar { + + interface Listener { + void onConnect(); + + void onDisconnect(); + + void onCloseTab(); + + void onQuit(); + + /** Moves the microphone to the tab on screen. */ + void onActivate(); + + void onToggleMic(); + + void onToggleSpeaker(); + + /** The plain toggle carries no message; "Set away status…" is where messages are chosen. */ + void onAwayToggle(boolean away); + + void onAwayStatus(); + + /** The away button's drop-down, which the "Set Away" submenu mirrors. */ + JPopupMenu buildAwayMenu(); + + void onCommanderToggle(boolean commander); + + void onChangeNickname(); + + /** Whether our talk power request is pending; asked as the Self menu opens. */ + boolean isTalkPowerRequested(); + + /** Requests talk power, or withdraws a pending request. */ + void onRequestTalkPower(); + + void onSetPhoneticNickname(); + + /** Whether the current server lets us upload an avatar; asked as the Self menu opens. */ + boolean canSetAvatar(); + + void onSetAvatar(); + + /** Whether we have an avatar on the current server to delete; asked as the Self menu opens. */ + boolean hasAvatar(); + + void onDeleteAvatar(); + + void onGiantPtt(); + + void onShowIdentities(); + + void onShowContacts(); + + void onShowOfflineMessages(); + + /** Whether the current tab is recording; asked as the Tools menu opens. */ + boolean isRecording(); + + void onStartRecording(boolean multitrack); + + void onStopRecording(); + + /** Whether the current server lets us read its ban list; asked as the Tools menu opens. */ + boolean canViewBanList(); + + void onShowBanList(); + + /** Whether the current server lets us read its complaints; asked as the Tools menu opens. */ + boolean canViewComplaints(); + + void onShowComplaints(); + + /** Whether the current server lets us read its log; asked as the Tools menu opens. */ + boolean canViewServerLog(); + + void onShowServerLog(); + + /** Whether the current server lets us list its privilege keys; asked as the Permissions menu opens. */ + boolean canListPrivilegeKeys(); + + void onShowPrivilegeKeys(); + + void onUsePrivilegeKey(); + + void onShowSettings(); + + void onShowAbout(); + + /** @param newTab open the server in a new tab instead of replacing the current one */ + void onConnectBookmark(Bookmark bookmark, boolean newTab); + + void onAddCurrentServerBookmark(); + + void onManageBookmarks(); + } + + private final Bookmarks bookmarks; + private final Listener listener; + + private JMenu bookmarksMenu; + private JMenu awayMenu; + private JMenuItem activateItem; + private JMenuItem muteItem; + private JMenuItem deafItem; + private JCheckBoxMenuItem awayItem; + private JMenuItem awayStatusItem; + private JCheckBoxMenuItem commanderItem; + private JMenuItem talkPowerItem; + private JMenuItem phoneticItem; + private JMenuItem avatarItem; + private JMenuItem deleteAvatarItem; + private JMenuItem startRecordingItem; + private JMenuItem startMultitrackItem; + private JMenuItem stopRecordingItem; + private JMenuItem offlineMessagesItem; + private JMenuItem banListItem; + private JMenuItem complaintsItem; + private JMenuItem serverLogItem; + private JMenuItem privilegeKeysItem; + private JMenuItem usePrivilegeKeyItem; + + MainMenuBar(Bookmarks bookmarks, Listener listener) { + this.bookmarks = bookmarks; + this.listener = listener; + + JMenu connections = new JMenu("Connections"); + JMenuItem connect = new JMenuItem("Connect…", Icons.of("CONNECT")); + connect.setAccelerator(KeyStroke.getKeyStroke("control S")); + connect.addActionListener(e -> listener.onConnect()); + JMenuItem disconnect = new JMenuItem("Disconnect", Icons.of("DISCONNECT")); + disconnect.setAccelerator(KeyStroke.getKeyStroke("control D")); + disconnect.addActionListener(e -> listener.onDisconnect()); + JMenuItem closeTab = new JMenuItem("Close tab", Icons.of("CLOSE_BUTTON")); + closeTab.setAccelerator(KeyStroke.getKeyStroke("control W")); + closeTab.addActionListener(e -> listener.onCloseTab()); + JMenuItem quit = new JMenuItem("Quit", Icons.of("QUIT")); + quit.setAccelerator(KeyStroke.getKeyStroke("control Q")); + quit.addActionListener(e -> listener.onQuit()); + connections.add(connect); + connections.add(disconnect); + connections.add(closeTab); + connections.addSeparator(); + connections.add(quit); + + bookmarksMenu = new JMenu("Bookmarks"); + rebuildBookmarks(); + // A server's icon may have finished downloading since the menu was built. + bookmarksMenu.addMenuListener(new MenuListener() { + @Override + public void menuSelected(MenuEvent e) { + rebuildBookmarks(); + } + + @Override + public void menuDeselected(MenuEvent e) { + } + + @Override + public void menuCanceled(MenuEvent e) { + } + }); + + JMenu self = new JMenu("Self"); + awayMenu = new JMenu("Set Away"); + awayMenu.setIcon(Icons.of("AWAY")); + awayMenu.addMenuListener(new MenuListener() { + @Override + public void menuSelected(MenuEvent e) { + rebuildAwayMenu(); + } + + @Override + public void menuDeselected(MenuEvent e) { + } + + @Override + public void menuCanceled(MenuEvent e) { + } + }); + activateItem = new JMenuItem("Activate Microphone", Icons.of("ACTIVATE_MICROPHONE")); + activateItem.addActionListener(e -> listener.onActivate()); + muteItem = new JMenuItem(); + muteItem.addActionListener(e -> listener.onToggleMic()); + deafItem = new JMenuItem(); + deafItem.addActionListener(e -> listener.onToggleSpeaker()); + showMuted(false, false); + awayItem = new JCheckBoxMenuItem("Away", Icons.of("AWAY"), false); + awayItem.addActionListener(e -> listener.onAwayToggle(awayItem.isSelected())); + awayStatusItem = new JMenuItem("Set away status…", Icons.of("EDIT")); + awayStatusItem.addActionListener(e -> listener.onAwayStatus()); + commanderItem = new JCheckBoxMenuItem("Channel commander", Icons.of("CHANNEL_COMMANDER"), false); + commanderItem.addActionListener(e -> listener.onCommanderToggle(commanderItem.isSelected())); + JMenuItem nick = new JMenuItem("Change nickname…", Icons.of("CHANGE_NICKNAME")); + nick.addActionListener(e -> listener.onChangeNickname()); + talkPowerItem = new JMenuItem(); + talkPowerItem.addActionListener(e -> listener.onRequestTalkPower()); + showTalkPowerRequested(false); + phoneticItem = new JMenuItem("Set Phonetic Nickname…", Icons.of("PHONETICSNICKNAME")); + phoneticItem.addActionListener(e -> listener.onSetPhoneticNickname()); + avatarItem = new JMenuItem("Set avatar…", Icons.of("UPLOAD_AVATAR")); + avatarItem.addActionListener(e -> listener.onSetAvatar()); + deleteAvatarItem = new JMenuItem("Delete avatar", Icons.of("DELETE_AVATAR")); + deleteAvatarItem.addActionListener(e -> listener.onDeleteAvatar()); + JMenuItem giantPtt = new JMenuItem("Giant PTT", Icons.of("CAPTURE")); + giantPtt.addActionListener(e -> listener.onGiantPtt()); + self.add(awayMenu); + self.add(activateItem); + self.add(muteItem); + self.add(deafItem); + self.add(giantPtt); + self.addSeparator(); + self.add(commanderItem); + self.addSeparator(); + self.add(nick); + self.add(talkPowerItem); + self.add(phoneticItem); + self.add(avatarItem); + self.add(deleteAvatarItem); + self.addMenuListener(new MenuListener() { + @Override + public void menuSelected(MenuEvent e) { + showTalkPowerRequested(listener.isTalkPowerRequested()); + avatarItem.setVisible(!avatarItem.isEnabled() || listener.canSetAvatar()); + deleteAvatarItem.setVisible(listener.hasAvatar()); + } + + @Override + public void menuDeselected(MenuEvent e) { + } + + @Override + public void menuCanceled(MenuEvent e) { + } + }); + + JMenu permissions = new JMenu("Permissions"); + privilegeKeysItem = new JMenuItem("Privilege Keys", Icons.of("TOKEN")); + privilegeKeysItem.addActionListener(e -> listener.onShowPrivilegeKeys()); + usePrivilegeKeyItem = new JMenuItem("Use Privilege Key", Icons.of("TOKEN_USE")); + usePrivilegeKeyItem.addActionListener(e -> listener.onUsePrivilegeKey()); + permissions.add(privilegeKeysItem); + permissions.add(usePrivilegeKeyItem); + permissions.addMenuListener(new MenuListener() { + @Override + public void menuSelected(MenuEvent e) { + privilegeKeysItem.setVisible(!privilegeKeysItem.isEnabled() || listener.canListPrivilegeKeys()); + } + + @Override + public void menuDeselected(MenuEvent e) { + } + + @Override + public void menuCanceled(MenuEvent e) { + } + }); + + JMenu tools = new JMenu("Tools"); + JMenuItem identitiesItem = new JMenuItem("Identities…", Icons.of("IDENTITY_MANAGER")); + identitiesItem.setAccelerator(KeyStroke.getKeyStroke("control I")); + identitiesItem.addActionListener(e -> listener.onShowIdentities()); + JMenuItem contactsItem = new JMenuItem("Contacts…", Icons.ofAny("CONTACT", "EDIT_FRIEND_FOE_STATUS")); + contactsItem.setAccelerator(KeyStroke.getKeyStroke("control shift O")); + contactsItem.addActionListener(e -> listener.onShowContacts()); + offlineMessagesItem = new JMenuItem("Offline Messages", Icons.of("OFFLINE_MESSAGES")); + offlineMessagesItem.setAccelerator(KeyStroke.getKeyStroke("control O")); + offlineMessagesItem.addActionListener(e -> listener.onShowOfflineMessages()); + startRecordingItem = new JMenuItem("Start Recording", Icons.of("RECORDING_START")); + startRecordingItem.addActionListener(e -> listener.onStartRecording(false)); + startMultitrackItem = new JMenuItem("Start Multitrack Recording", Icons.of("RECORDING_START")); + startMultitrackItem.addActionListener(e -> listener.onStartRecording(true)); + stopRecordingItem = new JMenuItem("Stop Recording", Icons.of("RECORDING_STOP")); + stopRecordingItem.addActionListener(e -> listener.onStopRecording()); + banListItem = new JMenuItem("Ban List", Icons.of("BAN_LIST")); + banListItem.setAccelerator(KeyStroke.getKeyStroke("control shift B")); + // The shortcut works while the item is hidden, so it asks for itself. + banListItem.addActionListener(e -> { + if (listener.canViewBanList()) listener.onShowBanList(); + }); + complaintsItem = new JMenuItem("Complaints List", Icons.of("COMPLAINT_LIST")); + complaintsItem.setAccelerator(KeyStroke.getKeyStroke("control shift C")); + complaintsItem.addActionListener(e -> { + if (listener.canViewComplaints()) listener.onShowComplaints(); + }); + serverLogItem = new JMenuItem("Server Log", Icons.of("SERVER_LOG")); + serverLogItem.setAccelerator(KeyStroke.getKeyStroke("control shift L")); + serverLogItem.addActionListener(e -> { + if (listener.canViewServerLog()) listener.onShowServerLog(); + }); + JMenuItem options = new JMenuItem("Options…", Icons.of("SETTINGS")); + options.setAccelerator(KeyStroke.getKeyStroke("alt P")); + options.addActionListener(e -> listener.onShowSettings()); + JPopupMenu.Separator adminSeparator = new JPopupMenu.Separator(); + tools.add(identitiesItem); + tools.add(contactsItem); + tools.add(offlineMessagesItem); + tools.addSeparator(); + tools.add(startRecordingItem); + tools.add(startMultitrackItem); + tools.add(stopRecordingItem); + tools.addSeparator(); + tools.add(banListItem); + tools.add(complaintsItem); + tools.add(serverLogItem); + tools.add(adminSeparator); + tools.add(options); + // Permissions arrive after the connection does, so the item is judged as the menu opens + // rather than on a fixed refresh. + tools.addMenuListener(new MenuListener() { + @Override + public void menuSelected(MenuEvent e) { + boolean bans = banListItem.isEnabled() && listener.canViewBanList(); + boolean complaints = complaintsItem.isEnabled() && listener.canViewComplaints(); + boolean serverLog = serverLogItem.isEnabled() && listener.canViewServerLog(); + banListItem.setVisible(bans); + complaintsItem.setVisible(complaints); + serverLogItem.setVisible(serverLog); + adminSeparator.setVisible(bans || complaints || serverLog); + boolean recording = listener.isRecording(); + startRecordingItem.setVisible(!recording); + startMultitrackItem.setVisible(!recording); + stopRecordingItem.setVisible(recording); + } + + @Override + public void menuDeselected(MenuEvent e) { + } + + @Override + public void menuCanceled(MenuEvent e) { + } + }); + + JMenu help = new JMenu("Help"); + JMenuItem about = new JMenuItem("About", Icons.of("ABOUT")); + about.addActionListener(e -> listener.onShowAbout()); + help.add(about); + + add(connections); + add(bookmarksMenu); + add(self); + add(permissions); + add(tools); + add(help); + } + + /** Reflects the current tab's state on the menu items. */ + void refresh(boolean connected, boolean anyConnected, boolean micMuted, boolean deafened, + boolean active, boolean away, boolean commander) { + awayMenu.setEnabled(anyConnected); + activateItem.setEnabled(connected && !active); + muteItem.setEnabled(connected); + deafItem.setEnabled(connected); + showMuted(micMuted, deafened); + awayItem.setEnabled(connected); + awayStatusItem.setEnabled(connected); + commanderItem.setEnabled(connected); + talkPowerItem.setEnabled(connected); + phoneticItem.setEnabled(connected); + avatarItem.setEnabled(connected); + deleteAvatarItem.setEnabled(connected); + startRecordingItem.setEnabled(connected); + startMultitrackItem.setEnabled(connected); + offlineMessagesItem.setEnabled(connected); + banListItem.setEnabled(connected); + complaintsItem.setEnabled(connected); + serverLogItem.setEnabled(connected); + privilegeKeysItem.setEnabled(connected); + usePrivilegeKeyItem.setEnabled(connected); + awayItem.setSelected(away); + commanderItem.setSelected(commander); + } + + private void showTalkPowerRequested(boolean requested) { + talkPowerItem.setText(requested ? "Cancel Talk Power Request" : "Request Talk Power…"); + talkPowerItem.setIcon(Icons.of(requested ? "TALK_POWER_CANCEL_REQUEST" : "TALK_POWER_REQUEST")); + } + + private void showMuted(boolean micMuted, boolean deafened) { + muteItem.setText(micMuted ? "Unmute Microphone" : "Mute Microphone"); + muteItem.setIcon(Icons.of(micMuted ? "CAPTURE" : "INPUT_MUTED")); + deafItem.setText(deafened ? "Unmute Speakers/Headphones" : "Mute Speakers/Headphones"); + deafItem.setIcon(Icons.of(deafened ? "PLAYBACK" : "OUTPUT_MUTED")); + } + + /** The toolbar button's toggle and status for this server, then its drop-down's global items. */ + private void rebuildAwayMenu() { + awayMenu.removeAll(); + awayMenu.add(awayItem); + awayMenu.add(awayStatusItem); + awayMenu.addSeparator(); + for (Component c : listener.buildAwayMenu().getComponents()) awayMenu.getPopupMenu().add(c); + } + + /** Re-lists the saved bookmarks; called after they change (add, remove, manage…). */ + void rebuildBookmarks() { + bookmarksMenu.removeAll(); + JMenuItem addCurrent = new JMenuItem("Add to Bookmarks…", Icons.of("BOOKMARK_ADD")); + addCurrent.addActionListener(e -> listener.onAddCurrentServerBookmark()); + JMenuItem manage = new JMenuItem("Manage Bookmarks…", Icons.of("BOOKMARK_MANAGER")); + manage.setAccelerator(KeyStroke.getKeyStroke("control B")); + manage.addActionListener(e -> listener.onManageBookmarks()); + bookmarksMenu.add(addCurrent); + bookmarksMenu.add(manage); + if (!bookmarks.all().isEmpty()) bookmarksMenu.addSeparator(); + for (Bookmark b : bookmarks.all()) { + ImageIcon serverIcon = GroupIcons.cached(b.iconId); + JMenuItem item = new JMenuItem(b.displayName(), serverIcon != null ? serverIcon : Icons.of("SERVER_GREEN")); + item.setToolTipText("Connect here (middle-click to open a new tab)"); + item.addActionListener(e -> listener.onConnectBookmark(b, false)); + item.addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + if (!SwingUtilities.isMiddleMouseButton(e)) return; + MenuSelectionManager.defaultManager().clearSelectedPath(); + listener.onConnectBookmark(b, true); + } + }); + bookmarksMenu.add(item); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainToolbar.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainToolbar.java new file mode 100644 index 0000000..e5c3295 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainToolbar.java @@ -0,0 +1,237 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.net.HostButton; +import eu.lixko.ts3j.client.net.PictureDownloads; + +import javax.swing.Box; +import javax.swing.JButton; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.JSlider; +import javax.swing.JToggleButton; +import javax.swing.JToolBar; +import javax.swing.event.PopupMenuEvent; +import javax.swing.event.PopupMenuListener; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.FlowLayout; + +/** + * The main window's toolbar: connect/disconnect, the per-tab mic/speaker/away + * controls, and the Master Volume slider and the server's host button on the + * right. A right-click anywhere on the bar opens a customization menu for the + * window's optional chrome (this toolbar has no say over the status bar's own + * visibility beyond reporting the toggle). + * + *

    Talks to {@link MainFrame} only through {@link Listener}, so it owns no + * connection/tab state itself — {@link #refresh} is handed everything it + * needs to redraw each time the selection changes. + */ +final class MainToolbar extends JToolBar { + + interface Listener { + void onConnect(); + + void onDisconnect(); + + /** Moves the microphone to the tab on screen. */ + void onActivate(); + + void onMicMuteToggle(boolean muted); + + void onDeafenToggle(boolean deafened); + + /** The plain toggle carries no message; the drop-down arrow is where messages are chosen. */ + void onAwayToggle(boolean away); + + JPopupMenu buildAwayMenu(); + + void onSettings(); + + /** The slider changed; push the new master volume to every open connection. */ + void onMasterVolumeChanged(); + + void onStatusBarVisibilityChanged(boolean visible); + } + + private final Settings settings; + private final Listener listener; + + private final JButton connectButton; + private final JButton disconnectButton; + private final JToggleButton activeButton; + private final JToggleButton micButton; + private final JToggleButton speakerButton; + private final DropDownToggleButton awayButton; + private final JComponent masterVolumePanel; + private final HostButtonView hostButton; + + MainToolbar(Settings settings, Listener listener, PictureDownloads pictures) { + this.settings = settings; + this.listener = listener; + + setFloatable(false); + setBackground(Theme.toolbarBg()); + setBorder(new ScaledEmptyBorder(4, 6, 4, 6)); + setComponentPopupMenu(buildContextMenu()); + + connectButton = new JButton(Icons.connect()); + connectButton.setToolTipText("Connect to a server"); + connectButton.addActionListener(e -> listener.onConnect()); + + disconnectButton = new JButton(Icons.disconnect()); + disconnectButton.setToolTipText("Disconnect"); + disconnectButton.addActionListener(e -> listener.onDisconnect()); + + activeButton = new JToggleButton(Icons.micActive()); + activeButton.setToolTipText("Speak on this server (moves the microphone to this tab)"); + activeButton.addActionListener(e -> listener.onActivate()); + + micButton = new JToggleButton(Icons.mic()); + micButton.setToolTipText("Mute / unmute microphone on this server"); + micButton.addActionListener(e -> listener.onMicMuteToggle(micButton.isSelected())); + + speakerButton = new JToggleButton(Icons.speaker()); + speakerButton.setToolTipText("Deafen / undeafen (mute speakers) on this server"); + speakerButton.addActionListener(e -> listener.onDeafenToggle(speakerButton.isSelected())); + + awayButton = new DropDownToggleButton(Icons.away(), + "Away on this server (the arrow offers the global actions and presets)", + listener::buildAwayMenu); + awayButton.addActionListener(e -> listener.onAwayToggle(awayButton.isSelected())); + + JButton settingsButton = new JButton(Icons.settings()); + settingsButton.setToolTipText("Options"); + settingsButton.addActionListener(e -> listener.onSettings()); + + add(connectButton); + add(disconnectButton); + addSeparator(); + add(activeButton); + add(micButton); + add(speakerButton); + add(awayButton); + addSeparator(); + add(settingsButton); + add(Box.createHorizontalGlue()); + masterVolumePanel = buildMasterVolumeControl(); + masterVolumePanel.setVisible(settings.showMasterVolumeSlider); + add(masterVolumePanel); + hostButton = new HostButtonView(pictures); + add(hostButton); + } + + /** Shows the selected server's host button; {@code null} hides it. */ + void showHostButton(HostButton button) { + hostButton.show(button); + } + + /** Reflects the current tab's state on the buttons. */ + void refresh(boolean connected, boolean anyConnected, boolean micMuted, boolean deafened, + boolean active, boolean away) { + disconnectButton.setEnabled(connected); + micButton.setEnabled(connected); + speakerButton.setEnabled(connected); + activeButton.setEnabled(connected); + // The away menu's actions are global, so the arrow stays live while any server is up. + awayButton.setEnabled(anyConnected); + awayButton.setToggleEnabled(connected); + + micButton.setSelected(micMuted); + micButton.setIcon(micMuted ? Icons.micMutedLarge() : Icons.mic()); + speakerButton.setSelected(deafened); + speakerButton.setIcon(deafened ? Icons.speakerMutedLarge() : Icons.speaker()); + activeButton.setSelected(active); + awayButton.setSelected(away); + } + + /** Simulates a click, for the "Mute Microphone" menu item. */ + void clickMic() { + micButton.doClick(); + } + + /** Simulates a click, for the "Mute Speakers/Headphones" menu item. */ + void clickSpeaker() { + speakerButton.doClick(); + } + + /** The Master Volume slider: multiplies both voice and notification volume. */ + private JComponent buildMasterVolumeControl() { + JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT, UIScale.scale(4), 0)); + panel.setOpaque(false); + panel.setAlignmentY(Component.CENTER_ALIGNMENT); + + JLabel icon = new JLabel(Icons.speaker()); + icon.setToolTipText("Master volume (voice + notifications)"); + icon.setAlignmentY(Component.CENTER_ALIGNMENT); + + JSlider slider = new JSlider(0, 200, (int) Math.round(settings.masterVolume * 100)); + slider.setOpaque(false); + slider.setToolTipText("Master volume (voice + notifications) — scroll to adjust"); + slider.setAlignmentY(Component.CENTER_ALIGNMENT); + slider.setPreferredSize(new Dimension(UIScale.scale(135), slider.getPreferredSize().height)); + slider.addChangeListener(e -> { + settings.masterVolume = slider.getValue() / 100.0; + listener.onMasterVolumeChanged(); + // Only touch the disk once the drag (or a wheel step) has settled. + if (!slider.getValueIsAdjusting()) settings.save(); + }); + slider.addMouseWheelListener(e -> { + int step = e.getWheelRotation() < 0 ? 5 : -5; + slider.setValue(slider.getValue() + step); + e.consume(); + }); + + panel.add(icon); + panel.add(slider); + return panel; + } + + /** Right-click on the toolbar: toggles for the window's optional chrome. */ + private JPopupMenu buildContextMenu() { + JPopupMenu menu = new JPopupMenu(); + + JCheckBoxMenuItem statusBarItem = new JCheckBoxMenuItem("Show Status Bar", settings.showStatusBar); + statusBarItem.addActionListener(e -> { + settings.showStatusBar = statusBarItem.isSelected(); + settings.save(); + listener.onStatusBarVisibilityChanged(settings.showStatusBar); + }); + + JCheckBoxMenuItem volumeItem = new JCheckBoxMenuItem("Show Master Volume Slider", settings.showMasterVolumeSlider); + volumeItem.addActionListener(e -> { + settings.showMasterVolumeSlider = volumeItem.isSelected(); + settings.save(); + masterVolumePanel.setVisible(settings.showMasterVolumeSlider); + revalidate(); + repaint(); + }); + + menu.add(statusBarItem); + menu.add(volumeItem); + // Either toggle can also be flipped elsewhere (or via settings.properties), so + // re-sync the ticks each time the menu is about to be shown. + menu.addPopupMenuListener(new PopupMenuListener() { + @Override + public void popupMenuWillBecomeVisible(PopupMenuEvent e) { + statusBarItem.setSelected(settings.showStatusBar); + volumeItem.setSelected(settings.showMasterVolumeSlider); + } + + @Override + public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { + } + + @Override + public void popupMenuCanceled(PopupMenuEvent e) { + } + }); + return menu; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MicrophoneTest.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MicrophoneTest.java new file mode 100644 index 0000000..4eab36c --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MicrophoneTest.java @@ -0,0 +1,182 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.audio.AudioBackend; +import eu.lixko.ts3j.client.audio.AudioPlayback; +import eu.lixko.ts3j.client.audio.VoiceInput; +import eu.lixko.ts3j.client.config.Settings; + +import javax.swing.SwingUtilities; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.function.Consumer; + +/** + * Drives the settings dialog's microphone test from a real capture chain. + * + *

    The dialog runs its own {@link VoiceInput} rather than borrowing the connected + * one, whose listeners belong to the connection. Because it is the same class that feeds + * the server, the level and the gate shown here are exactly what would be transmitted — + * pre-processing, voice detection, hangover and pre-roll included. + * + *

    Loopback is optional: when enabled, the frames that would be sent are played back + * locally so you can hear precisely what the other side would. + */ +final class MicrophoneTest { + + /** Frames buffered for loopback before the oldest is dropped (~100 ms). */ + private static final int LOOPBACK_QUEUE_FRAMES = 5; + + private final Consumer onLevel; + private final Consumer onTransmitting; + + private final AudioBackend audio; + private VoiceInput mic; + + private final ArrayBlockingQueue loopbackQueue = + new ArrayBlockingQueue<>(LOOPBACK_QUEUE_FRAMES); + private volatile boolean loopbackEnabled; + private volatile boolean loopbackRunning; + private Thread loopbackThread; + private String outputDevice = ""; + + MicrophoneTest(AudioBackend audio, Consumer onLevel, Consumer onTransmitting) { + this.audio = audio; + this.onLevel = onLevel; + this.onTransmitting = onTransmitting; + } + + /** Whether a capture chain is currently running. */ + boolean isRunning() { + return mic != null; + } + + /** + * (Re)starts the test chain against {@code settings}' devices and voice options. + * + * @return false if the capture device could not be opened + */ + boolean start(Settings settings) { + stop(); + VoiceInput input = audio.createInput(settings); + input.setLevelListener(db -> SwingUtilities.invokeLater(() -> onLevel.accept(db))); + input.setTalkListener(talking -> SwingUtilities.invokeLater(() -> onTransmitting.accept(talking))); + input.setMonitorListener(this::enqueueForLoopback); + this.outputDevice = settings.outputDevice; + try { + input.start(); + } catch (RuntimeException e) { + return false; // Device busy or gone; leave the test switched off. + } + this.mic = input; + return true; + } + + /** + * Stops the capture chain. The caller owns the UI reset: doing it here would race with + * a restart, whose own state has already been put on screen. + */ + void stop() { + setLoopback(false); + if (mic != null) { + mic.stop(); + mic = null; + } + } + + /** Applies a change to the test chain, if it is running. */ + void configure(Consumer change) { + VoiceInput m = mic; + if (m != null) change.accept(m); + } + + /** The playback device to loop back through; takes effect on the next enable. */ + void setOutputDevice(String deviceId) { + this.outputDevice = deviceId == null ? "" : deviceId; + } + + void setLoopback(boolean enabled) { + if (enabled == loopbackEnabled) { + return; + } + loopbackEnabled = enabled; + if (enabled) { + loopbackRunning = true; + loopbackThread = new Thread(this::loopbackLoop, "settings-loopback"); + loopbackThread.setDaemon(true); + loopbackThread.start(); + } else { + loopbackRunning = false; + if (loopbackThread != null) { + loopbackThread.interrupt(); + loopbackThread = null; + } + loopbackQueue.clear(); + } + } + + /** + * Converts a transmitted frame to 16-bit PCM and queues it. Runs on the capture thread, + * so it must not block: a full queue means playback has fallen behind and the oldest + * frame is dropped instead. + */ + private void enqueueForLoopback(float[] interleaved, int channels) { + if (!loopbackEnabled) { + return; + } + byte[] pcm = toPcm16(interleaved); + if (!loopbackQueue.offer(pcm)) { + loopbackQueue.poll(); + loopbackQueue.offer(pcm); + } + } + + private void loopbackLoop() { + AudioPlayback line = null; + try { + // The monitored frames are mono for voice; ask for a matching line so no + // channel juggling is needed, and up-mix only if the device insists on stereo. + line = audio.io().openPlayback(outputDevice, 1); + line.start(); + int channels = line.channels(); + while (loopbackRunning) { + byte[] frame = loopbackQueue.poll(100, java.util.concurrent.TimeUnit.MILLISECONDS); + if (frame == null) { + continue; + } + byte[] out = (channels == 1) ? frame : upmix(frame, channels); + line.write(out, 0, out.length); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (Exception ignored) { + // The device may be busy or gone; the test simply runs without loopback. + } finally { + if (line != null) line.close(); + } + } + + /** Converts float samples in [-1, 1] to 16-bit little-endian PCM. */ + static byte[] toPcm16(float[] samples) { + byte[] pcm = new byte[samples.length * 2]; + for (int i = 0; i < samples.length; i++) { + float f = samples[i]; + if (f > 1f) f = 1f; + else if (f < -1f) f = -1f; + int s = Math.round(f * 32767f); + pcm[2 * i] = (byte) (s & 0xFF); + pcm[2 * i + 1] = (byte) ((s >> 8) & 0xFF); + } + return pcm; + } + + /** Copies a mono frame across {@code channels} interleaved channels. */ + static byte[] upmix(byte[] mono, int channels) { + byte[] out = new byte[mono.length * channels]; + for (int i = 0, frames = mono.length / 2; i < frames; i++) { + for (int c = 0; c < channels; c++) { + out[2 * (i * channels + c)] = mono[2 * i]; + out[2 * (i * channels + c) + 1] = mono[2 * i + 1]; + } + } + return out; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MyTeamSpeakPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MyTeamSpeakPanel.java new file mode 100644 index 0000000..b1941dc --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MyTeamSpeakPanel.java @@ -0,0 +1,394 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.myts.AccountInfo; +import eu.lixko.ts3j.client.myts.MyTeamSpeak; +import eu.lixko.ts3j.client.myts.MyTeamSpeakLogin; +import eu.lixko.ts3j.client.myts.MyTsException; +import eu.lixko.ts3j.client.teamspeak.SyncItem; +import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JPasswordField; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.JTextField; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.table.AbstractTableModel; +import java.awt.BorderLayout; +import java.awt.CardLayout; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.io.IOException; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.time.format.FormatStyle; +import java.util.ArrayList; +import java.util.List; + +/** + * Options page for the myTeamSpeak account: sign in and out, and see what the + * account synchronises and import it. Everything here takes effect at once rather + * than on OK, as signing in is not a setting to be cancelled. + */ +final class MyTeamSpeakPanel extends JPanel { + + private static final String SIGNED_OUT = "out"; + private static final String SIGNED_IN = "in"; + + private final MyTeamSpeakLogin login; + private final TeamSpeakImporter importer; + private final Runnable onImported; + /** Runs when the client signs in or out, the saved sign-in being turned away included. */ + private final Runnable onSignInChanged; + + private final CardLayout cards = new CardLayout(); + + private final JTextField email = new JTextField(24); + private final JPasswordField password = new JPasswordField(24); + private final JButton signIn = new JButton("Sign in"); + private final JLabel signInStatus = new JLabel(" "); + + private final JLabel account = new JLabel(); + private final JPanel details = new JPanel(new GridBagLayout()); + private final ItemTable items = new ItemTable(); + private final JButton refresh = new JButton("Refresh"); + private final JButton importButton = new JButton("Import selected"); + private final JLabel dataStatus = new JLabel(" "); + + private List accountItems = List.of(); + private boolean fetched; + + MyTeamSpeakPanel(MyTeamSpeakLogin login, TeamSpeakImporter importer, Runnable onImported, + Runnable onSignInChanged) { + this.login = login; + this.importer = importer; + this.onImported = onImported; + this.onSignInChanged = onSignInChanged; + setLayout(cards); + add(buildSignedOut(), SIGNED_OUT); + add(buildSignedIn(), SIGNED_IN); + showState(); + // Reads the account the first time the page is looked at, not with every Options dialog. + addHierarchyListener(e -> { + if (isShowing() && login.isSignedIn() && !fetched) fetch(); + }); + } + + private JPanel buildSignedOut() { + JPanel form = new JPanel(new GridBagLayout()); + form.setBorder(new ScaledEmptyBorder(12, 12, 12, 12)); + GridBagConstraints c = FormPanel.gbc(); + c.gridwidth = 2; + c.gridy = 0; + form.add(new JLabel("Sign in to your myTeamSpeak account to bring over the bookmarks and " + + "identities it synchronises. The client stays signed in; your password itself is not kept."), c); + c.gridwidth = 1; + FormPanel.addRow(form, c, 1, new JLabel("Email:"), email); + FormPanel.addRow(form, c, 2, new JLabel("Password:"), password); + c.gridx = 1; + c.gridy = 3; + c.fill = GridBagConstraints.NONE; + c.anchor = GridBagConstraints.EAST; + form.add(signIn, c); + c.gridx = 0; + c.gridy = 4; + c.gridwidth = 2; + c.fill = GridBagConstraints.HORIZONTAL; + form.add(signInStatus, c); + c.gridy = 5; + c.weighty = 1; + form.add(Box.createVerticalGlue(), c); + + signIn.addActionListener(e -> signIn()); + password.addActionListener(e -> signIn()); + return form; + } + + private JPanel buildSignedIn() { + JPanel header = new JPanel(new BorderLayout()); + JButton signOut = new JButton("Sign out"); + signOut.addActionListener(e -> signOut()); + header.add(account, BorderLayout.CENTER); + header.add(signOut, BorderLayout.EAST); + JPanel top = new JPanel(new BorderLayout(0, UIScale.scale(8))); + top.add(header, BorderLayout.NORTH); + top.add(details, BorderLayout.CENTER); + + JPanel buttons = new JPanel(); + buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS)); + buttons.add(dataStatus); + buttons.add(Box.createHorizontalGlue()); + buttons.add(refresh); + buttons.add(Box.createHorizontalStrut(UIScale.scale(4))); + buttons.add(importButton); + refresh.addActionListener(e -> fetch()); + importButton.addActionListener(e -> importSelected()); + + JPanel data = new JPanel(new BorderLayout(0, UIScale.scale(4))); + data.add(new JLabel("Synchronised by the account:"), BorderLayout.NORTH); + data.add(new JScrollPane(items.table), BorderLayout.CENTER); + data.add(buttons, BorderLayout.SOUTH); + + JPanel panel = new JPanel(new BorderLayout(0, UIScale.scale(12))); + panel.setBorder(new ScaledEmptyBorder(12, 12, 12, 12)); + panel.add(top, BorderLayout.NORTH); + panel.add(data, BorderLayout.CENTER); + return panel; + } + + private void showState() { + if (login.isSignedIn()) { + account.setText("Signed in as " + escape(login.username()) + "
    " + + escape(login.email()) + ""); + cards.show(this, SIGNED_IN); + } else { + password.setText(""); + cards.show(this, SIGNED_OUT); + } + } + + private void signIn() { + String address = email.getText().trim(); + String secret = new String(password.getPassword()); + if (address.isEmpty() || secret.isEmpty() || !signIn.isEnabled()) return; + setSignInBusy(true); + status(signInStatus, "Signing in…", false); + background(() -> { + MyTeamSpeak.Account result = login.signIn(address, secret); + SwingUtilities.invokeLater(() -> { + setSignInBusy(false); + status(signInStatus, " ", false); + showState(); + showItems(result); + onSignInChanged.run(); + }); + }, message -> { + setSignInBusy(false); + status(signInStatus, message, true); + password.selectAll(); + password.requestFocusInWindow(); + }); + } + + private void signOut() { + login.signOut(); + accountItems = List.of(); + details.removeAll(); + items.set(List.of()); + fetched = false; + email.setText(""); + showState(); + onSignInChanged.run(); + } + + private void fetch() { + fetched = true; + setDataBusy(true); + status(dataStatus, "Reading the account…", false); + background(() -> { + MyTeamSpeak.Account result = login.fetch(); + SwingUtilities.invokeLater(() -> { + setDataBusy(false); + showState(); + showItems(result); + }); + }, message -> { + setDataBusy(false); + status(dataStatus, message, true); + // A rejected sign-in has signed out. + showState(); + if (!login.isSignedIn()) { + status(signInStatus, message, true); + onSignInChanged.run(); + } + }); + } + + private void showDetails(AccountInfo info) { + details.removeAll(); + GridBagConstraints c = FormPanel.gbc(); + int row = 0; + if (!info.userId().isEmpty()) FormPanel.addRow(details, c, row++, new JLabel("ID:"), selectable(info.userId())); + if (!info.uuid().isEmpty()) FormPanel.addRow(details, c, row++, new JLabel("UUID:"), selectable(info.uuid())); + if (info.created() != null) { + String date = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM) + .format(info.created().atZone(ZoneId.systemDefault())); + FormPanel.addRow(details, c, row, new JLabel("Created:"), selectable(date)); + } + details.revalidate(); + details.repaint(); + } + + /** A value that can be selected and copied but not edited. */ + private static JTextField selectable(String value) { + JTextField field = new JTextField(value); + field.setEditable(false); + field.setCaretPosition(0); + return field; + } + + private void showItems(MyTeamSpeak.Account result) { + fetched = true; + showDetails(result.info()); + accountItems = result.items(); + List rows = new ArrayList<>(); + for (SyncItem item : accountItems) { + if (item instanceof SyncItem.Folder) continue; + boolean present = importer.isPresent(item); + rows.add(new Row(item, present, !present)); + } + items.set(rows); + status(dataStatus, rows.isEmpty() ? "The account holds no bookmarks or identities." : " ", false); + updateImportButton(); + } + + private void importSelected() { + List chosen = items.rows.stream().filter(Row::selected).map(Row::item).toList(); + if (chosen.isEmpty()) return; + try { + TeamSpeakImporter.Result r = importer.importSelected(accountItems, chosen); + status(dataStatus, "Imported " + count(r.identitiesAdded(), "identity", "identities") + " and " + + count(r.bookmarksAdded(), "bookmark", "bookmarks") + ".", false); + if (onImported != null) onImported.run(); + } catch (IOException e) { + status(dataStatus, "Could not import: " + e.getMessage(), true); + } + List rows = new ArrayList<>(); + for (Row row : items.rows) rows.add(new Row(row.item(), importer.isPresent(row.item()), false)); + items.set(rows); + updateImportButton(); + } + + private interface Work { + void run() throws IOException, MyTsException; + } + + /** Runs account work off the event thread; a failure's message reaches {@code onError} on it. */ + private static void background(Work work, java.util.function.Consumer onError) { + Thread.ofVirtual().name("myteamspeak").start(() -> { + try { + work.run(); + } catch (MyTsException e) { + SwingUtilities.invokeLater(() -> onError.accept(e.getMessage())); + } catch (IOException e) { + SwingUtilities.invokeLater(() -> onError.accept("Could not reach myTeamSpeak: " + e.getMessage())); + } + }); + } + + private void setSignInBusy(boolean busy) { + email.setEnabled(!busy); + password.setEnabled(!busy); + signIn.setEnabled(!busy); + } + + private void setDataBusy(boolean busy) { + refresh.setEnabled(!busy); + importButton.setEnabled(!busy); + if (!busy) updateImportButton(); + } + + private void updateImportButton() { + importButton.setEnabled(refresh.isEnabled() && items.rows.stream().anyMatch(Row::selected)); + } + + private static void status(JLabel label, String text, boolean error) { + label.setText(text.isBlank() ? " " : "" + escape(text) + ""); + label.setForeground(UIManager.getColor(error ? "Actions.Red" : "Label.foreground")); + } + + private static String escape(String s) { + return s.replace("&", "&").replace("<", "<"); + } + + private static String count(long n, String one, String many) { + return n + " " + (n == 1 ? one : many); + } + + private record Row(SyncItem item, boolean present, boolean selected) { + } + + /** The account's items, each with a box to pick it for importing and whether it is here already. */ + private final class ItemTable extends AbstractTableModel { + + private static final String[] COLUMNS = {"", "Type", "Name", "Details", "Imported"}; + + final JTable table = new JTable(this); + List rows = List.of(); + + ItemTable() { + table.setFillsViewportHeight(true); + table.getTableHeader().setReorderingAllowed(false); + table.getColumnModel().getColumn(0).setMaxWidth(UIScale.scale(28)); + table.getColumnModel().getColumn(1).setPreferredWidth(UIScale.scale(60)); + table.getColumnModel().getColumn(4).setPreferredWidth(UIScale.scale(60)); + } + + void set(List rows) { + this.rows = rows; + fireTableDataChanged(); + } + + @Override + public int getRowCount() { + return rows.size(); + } + + @Override + public int getColumnCount() { + return COLUMNS.length; + } + + @Override + public String getColumnName(int column) { + return COLUMNS[column]; + } + + @Override + public Class getColumnClass(int column) { + return column == 0 ? Boolean.class : String.class; + } + + @Override + public boolean isCellEditable(int row, int column) { + return column == 0; + } + + @Override + public Object getValueAt(int row, int column) { + Row r = rows.get(row); + return switch (column) { + case 0 -> r.selected(); + case 1 -> r.item() instanceof SyncItem.Bookmark ? "Bookmark" : "Identity"; + case 2 -> switch (r.item()) { + case SyncItem.Bookmark b -> b.name(); + case SyncItem.Identity i -> i.name(); + default -> ""; + }; + case 3 -> switch (r.item()) { + case SyncItem.Bookmark b -> b.address() + ":" + b.port(); + case SyncItem.Identity i -> i.nickname(); + default -> ""; + }; + default -> r.present() ? "Yes" : ""; + }; + } + + @Override + public void setValueAt(Object value, int row, int column) { + Row r = rows.get(row); + List updated = new ArrayList<>(rows); + updated.set(row, new Row(r.item(), r.present(), Boolean.TRUE.equals(value))); + rows = updated; + fireTableRowsUpdated(row, row); + updateImportButton(); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/NetworkPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/NetworkPanel.java new file mode 100644 index 0000000..27c5c43 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/NetworkPanel.java @@ -0,0 +1,150 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.audio.VoiceInput; +import eu.lixko.ts3j.client.config.Settings; + +import javax.swing.JCheckBox; +import javax.swing.JLabel; +import javax.swing.JSlider; +import java.awt.GridBagConstraints; + +/** + * Options page for what voice costs and survives on the wire: the encoder, duplicate voice + * packets, and how long incoming voice is buffered. Transmit changes preview live on the + * connected microphone. + */ +final class NetworkPanel extends FormPanel { + + private static final int MIN_BITRATE_KBITS = 8; + private static final int MAX_BITRATE_KBITS = 160; + + private final VoiceInput liveMic; + + private final JSlider bitrateSlider; + private final JCheckBox vbrCheck; + private final JCheckBox fecCheck; + private final JSlider complexitySlider; + private final JCheckBox musicCheck; + private final JSlider delaySlider; + private final JSlider copiesSlider; + private final JSlider receiveBufferSlider; + + /** @param pushEncoder puts the encoder settings on screen, across pages, into effect */ + NetworkPanel(Settings settings, VoiceInput liveMic, Runnable pushEncoder) { + this.liveMic = liveMic; + GridBagConstraints c = gbc(); + + int kbits = Math.max(MIN_BITRATE_KBITS, Math.min(MAX_BITRATE_KBITS, settings.bitrate / 1000)); + bitrateSlider = new JSlider(MIN_BITRATE_KBITS, MAX_BITRATE_KBITS, kbits); + JLabel bitrateLabel = new JLabel(kbits + " kbit/s"); + bitrateSlider.addChangeListener(e -> { + bitrateLabel.setText(bitrateSlider.getValue() + " kbit/s"); + pushEncoder.run(); + }); + + vbrCheck = new JCheckBox("Variable bitrate (VBR)", settings.vbr); + fecCheck = new JCheckBox("Forward error correction (FEC)", settings.fec); + vbrCheck.addActionListener(e -> pushEncoder.run()); + fecCheck.addActionListener(e -> pushEncoder.run()); + + complexitySlider = new JSlider(0, 10, settings.complexity); + JLabel complexityLabel = new JLabel(String.valueOf(settings.complexity)); + complexitySlider.addChangeListener(e -> { + complexityLabel.setText(String.valueOf(complexitySlider.getValue())); + pushEncoder.run(); + }); + + musicCheck = new JCheckBox("Music codec (stereo, higher fidelity)", settings.music); + musicCheck.setToolTipText("Transmits OPUS_MUSIC: stereo when the capture " + + "device has two channels, and without the voice pre-processing " + + "(noise removal, typing attenuation, AGC).
    " + + "Voice mode (OPUS_VOICE) is mono, as in the official client."); + musicCheck.addActionListener(e -> pushEncoder.run()); + + delaySlider = choiceSlider(Settings.REDUNDANCY_DELAYS, settings.redundancyDelay); + JLabel delayLabel = new JLabel(delayLabel(selectedDelay())); + int copies = Math.max(1, Math.min(Settings.MAX_REDUNDANCY_COPIES, settings.redundancyCopies)); + copiesSlider = new JSlider(1, Settings.MAX_REDUNDANCY_COPIES, copies); + copiesSlider.setMajorTickSpacing(1); + copiesSlider.setPaintTicks(true); + copiesSlider.setSnapToTicks(true); + JLabel copiesLabel = new JLabel(String.valueOf(copies)); + Runnable syncCopies = () -> { + copiesSlider.setEnabled(selectedDelay() > 0); + copiesLabel.setEnabled(selectedDelay() > 0); + }; + syncCopies.run(); + delaySlider.addChangeListener(e -> { + delayLabel.setText(delayLabel(selectedDelay())); + syncCopies.run(); + pushRedundancy(); + }); + copiesSlider.addChangeListener(e -> { + copiesLabel.setText(String.valueOf(copiesSlider.getValue())); + pushRedundancy(); + }); + + receiveBufferSlider = choiceSlider(Settings.RECEIVE_BUFFERS, settings.receiveBuffer); + JLabel receiveBufferLabel = new JLabel(delayLabel(selectedReceiveBuffer())); + receiveBufferSlider.addChangeListener(e -> receiveBufferLabel.setText(delayLabel(selectedReceiveBuffer()))); + + int row = 0; + addSection(this, c, row++, "Encoder"); + addRow(this, c, row++, new JLabel("Bitrate:"), sliderWithLabel(bitrateSlider, bitrateLabel, 70)); + addWide(this, c, row++, vbrCheck); + addWide(this, c, row++, fecCheck); + addRow(this, c, row++, new JLabel("Complexity:"), sliderWithLabel(complexitySlider, complexityLabel, 70)); + addWide(this, c, row++, musicCheck); + addSection(this, c, row++, "Redundancy"); + addRow(this, c, row++, new JLabel("Delay:"), sliderWithLabel(delaySlider, delayLabel, 70)); + addRow(this, c, row++, new JLabel("Copies:"), sliderWithLabel(copiesSlider, copiesLabel, 70)); + addSection(this, c, row++, "Receive"); + addRow(this, c, row++, new JLabel("Extra buffering:"), sliderWithLabel(receiveBufferSlider, receiveBufferLabel, 70)); + addFiller(this, c, row); + } + + /** A slider over the indices of {@code choices}, starting at the one nearest {@code ms}. */ + private static JSlider choiceSlider(int[] choices, int ms) { + JSlider slider = new JSlider(0, choices.length - 1, nearest(choices, ms)); + slider.setMajorTickSpacing(1); + slider.setPaintTicks(true); + slider.setSnapToTicks(true); + return slider; + } + + private void pushRedundancy() { + if (liveMic != null) liveMic.setRedundancy(selectedDelay(), copiesSlider.getValue()); + } + + private static String delayLabel(int ms) { + return ms == 0 ? "Off" : ms + " ms"; + } + + private static int nearest(int[] choices, int ms) { + int best = 0; + for (int i = 1; i < choices.length; i++) { + if (Math.abs(choices[i] - ms) < Math.abs(choices[best] - ms)) best = i; + } + return best; + } + + private int selectedDelay() { + return Settings.REDUNDANCY_DELAYS[delaySlider.getValue()]; + } + + private int selectedReceiveBuffer() { + return Settings.RECEIVE_BUFFERS[receiveBufferSlider.getValue()]; + } + + /** Copies the page into {@code target}, without touching anything else. */ + void writeInto(Settings target) { + target.bitrate = bitrateSlider.getValue() * 1000; + target.vbr = vbrCheck.isSelected(); + target.fec = fecCheck.isSelected(); + target.complexity = complexitySlider.getValue(); + target.music = musicCheck.isSelected(); + target.redundancyDelay = selectedDelay(); + target.redundancyCopies = copiesSlider.getValue(); + target.receiveBuffer = selectedReceiveBuffer(); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/NicknameCellEditor.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/NicknameCellEditor.java new file mode 100644 index 0000000..35de03a --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/NicknameCellEditor.java @@ -0,0 +1,125 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.net.ClientEntry; + +import javax.swing.DefaultCellEditor; +import javax.swing.JLabel; +import javax.swing.JTextField; +import javax.swing.JTree; +import javax.swing.SwingUtilities; +import javax.swing.Timer; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeCellEditor; +import javax.swing.tree.DefaultTreeCellRenderer; +import javax.swing.tree.TreePath; +import java.awt.Component; +import java.awt.event.MouseEvent; +import java.util.EventObject; +import java.util.function.IntPredicate; + +/** + * Turns our own row in the server tree into a text field on a double click, the way + * TeamSpeak renames a client in place. Only that one row is editable; every other + * double click keeps its usual meaning (joining a channel, opening a chat). + * + *

    The field opens on the current nickname with it selected, so typing replaces it, + * Enter commits and Escape leaves the name alone. + */ +final class NicknameCellEditor extends DefaultTreeCellEditor { + + /** Pulls the field left by its own border, so the text sits where the label did. */ + private static final int FIELD_NUDGE = 2; + + /** Long enough for the click's own release to have been handled first. */ + private static final int SELECT_DELAY_MS = 80; + + private final JTextField field; + /** Whether a client id is our own — the tree learns ours only once connected. */ + private final IntPredicate isSelf; + + private NicknameCellEditor(JTree tree, DefaultTreeCellRenderer renderer, JTextField field, + IntPredicate isSelf) { + super(tree, renderer, new DefaultCellEditor(field)); + this.field = field; + this.isSelf = isSelf; + } + + static NicknameCellEditor create(JTree tree, DefaultTreeCellRenderer renderer, IntPredicate isSelf) { + JTextField field = new JTextField(); + // Only our own row is edited, and that name is bold in the tree. + field.setFont(Theme.uiBold()); + return new NicknameCellEditor(tree, renderer, field, isSelf); + } + + /** Whether a path is the row this editor works on. */ + boolean editsPath(TreePath path) { + ClientEntry client = clientOf(path); + return client != null && isSelf.test(client.id); + } + + /** + * Editing is started by the tree's own double-click handling, which works a row by + * its whole line; Swing's would only see clicks that land on the label, and its + * click-pause-click timer would rename on clicks meant as a selection. + */ + @Override + public boolean isCellEditable(EventObject event) { + return !(event instanceof MouseEvent); + } + + @Override + public Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected, + boolean expanded, boolean leaf, int row) { + // The node itself has to reach super, whose renderer measures the row from it; + // the text it derives is the node's toString, so the nickname is filled in after. + Component c = super.getTreeCellEditorComponent(tree, value, isSelected, expanded, leaf, row); + ClientEntry client = clientOf(value); + if (client != null) { + field.setText(client.nickname); + field.selectAll(); + } + SwingUtilities.invokeLater(field::requestFocusInWindow); + // The double click that opened the field ends in a release, which a text + // component turns into a caret placement — undoing any selection made before + // it. Selecting after that has been delivered is what leaves the whole name + // selected, ready to be typed over. + Timer select = new Timer(SELECT_DELAY_MS, e -> field.selectAll()); + select.setRepeats(false); + select.start(); + return c; + } + + /** + * Keeps the row's own icon while it is being edited. The inherited version knows + * only the renderer's default leaf/branch icons, which would swap a client's state + * icon for a blank page for as long as the field is open. + */ + @Override + protected void determineOffset(JTree tree, Object value, boolean isSelected, boolean expanded, + boolean leaf, int row) { + super.determineOffset(tree, value, isSelected, expanded, leaf, row); + Component c = renderer.getTreeCellRendererComponent(tree, value, isSelected, expanded, leaf, + row, false); + if (!(c instanceof JLabel)) return; + editingIcon = ((JLabel) c).getIcon(); + offset = editingIcon == null ? 0 + : editingIcon.getIconWidth() + renderer.getIconTextGap() - UIScale.scale(FIELD_NUDGE); + } + + /** The edited nickname, trimmed; empty when nothing usable was typed. */ + String editedNickname() { + String text = field.getText(); + return text == null ? "" : text.trim(); + } + + private static ClientEntry clientOf(TreePath path) { + return path == null ? null : clientOf(path.getLastPathComponent()); + } + + private static ClientEntry clientOf(Object node) { + if (!(node instanceof DefaultMutableTreeNode)) return null; + Object obj = ((DefaultMutableTreeNode) node).getUserObject(); + return obj instanceof ClientEntry ? (ClientEntry) obj : null; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/NotificationsPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/NotificationsPanel.java new file mode 100644 index 0000000..4193b1d --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/NotificationsPanel.java @@ -0,0 +1,412 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.sound.NotificationSettings; +import eu.lixko.ts3j.client.sound.SoundEvent; +import eu.lixko.ts3j.client.sound.SoundNotifier; +import eu.lixko.ts3j.client.sound.SoundPack; + +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JFileChooser; +import javax.swing.JLabel; +import javax.swing.JMenuItem; +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.JScrollPane; +import javax.swing.JSlider; +import javax.swing.JTable; +import javax.swing.JTextField; +import javax.swing.ListSelectionModel; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.DefaultTableCellRenderer; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +/** + * Options page for sound packs: which pack is active, how loud it is, and what + * each action does. + * + *

    An action can be switched off entirely, or marked important (shown in + * bold) — important actions are the only ones still played while the speakers are + * muted, which is how the official client behaves. Actions the active pack has no + * sound for are greyed out. + */ +final class NotificationsPanel extends JPanel { + + private static final int TOGGLE_COLUMN_WIDTH = 34; + + /** A table row: either a category heading or one action. */ + private static final class Row { + final SoundEvent.Category heading; + final SoundEvent event; + + Row(SoundEvent.Category heading, SoundEvent event) { + this.heading = heading; + this.event = event; + } + + boolean isHeading() { + return event == null; + } + } + + private final Settings settings; + private final SoundNotifier sounds; + /** Edited copy, applied to the settings only when the dialog is confirmed. */ + private final NotificationSettings working; + private final List rows = new ArrayList<>(); + /** What {@link #revert()} goes back to: as the dialog opened, or as last applied. */ + private String originalPackId; + private String originalPackDir; + + private final JComboBox packCombo = new JComboBox<>(); + private final JLabel packInfo = new JLabel(); + private final JSlider volume; + private final JTextField packDirField; + private final JCheckBox desktopNotifications = + new JCheckBox("Show pokes and private messages as desktop notifications while in the background"); + private final JTable table; + private final EventTableModel tableModel = new EventTableModel(); + + NotificationsPanel(Settings settings, SoundNotifier sounds) { + super(new BorderLayout(0, UIScale.scale(8))); + this.settings = settings; + this.sounds = sounds; + this.working = settings.notifications.copy(); + this.originalPackId = settings.soundPack; + this.originalPackDir = settings.soundPackDir; + this.volume = new JSlider(0, 100, (int) Math.round(settings.soundVolume * 100)); + this.packDirField = new JTextField(settings.soundPackDir, 18); + + buildRows(); + this.table = buildTable(); + + setBorder(new ScaledEmptyBorder(12, 12, 12, 12)); + add(buildHeader(), BorderLayout.NORTH); + add(new JScrollPane(table), BorderLayout.CENTER); + add(buildFooter(), BorderLayout.SOUTH); + + reloadPacks(); + } + + /** Copies the edited state into the settings; the caller saves them. */ + void apply() { + settings.notifications.copyFrom(working); + settings.soundVolume = volume.getValue() / 100.0; + String directory = packDirField.getText().trim(); + boolean rescan = !directory.equals(settings.soundPackDir); + settings.soundPackDir = directory; + settings.desktopNotifications = desktopNotifications.isSelected(); + sounds.setPack((SoundPack) packCombo.getSelectedItem()); + if (rescan) sounds.reload(); + originalPackId = settings.soundPack; + originalPackDir = settings.soundPackDir; + } + + /** Puts back the pack (and folder) last applied, for a cancelled edit. */ + void revert() { + settings.soundPackDir = originalPackDir; + settings.soundPack = originalPackId; + sounds.reload(); + } + + // ---- layout ---- + + private JComponent buildHeader() { + JPanel p = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + c.insets = UIScale.scale(new Insets(2, 2, 2, 2)); + c.anchor = GridBagConstraints.WEST; + c.fill = GridBagConstraints.HORIZONTAL; + + packCombo.setToolTipText("Sound packs installed here or in a TeamSpeak 3 client"); + packCombo.addActionListener(e -> onPackSelected()); + JButton test = new JButton("Test"); + test.setToolTipText("Play this pack's test sound"); + test.addActionListener(e -> sounds.preview(SoundEvent.SPECIAL_SOUND_TEST)); + + JPanel packRow = new JPanel(new BorderLayout(UIScale.scale(6), 0)); + packRow.add(packCombo, BorderLayout.CENTER); + packRow.add(test, BorderLayout.EAST); + + int row = 0; + addRow(p, c, row++, new JLabel("Sound pack:"), packRow); + c.gridx = 1; + c.gridy = row++; + packInfo.setEnabled(false); + p.add(packInfo, c); + + volume.setToolTipText("Volume of the notification sounds"); + addRow(p, c, row++, new JLabel("Sound volume:"), volume); + + JPanel dirRow = new JPanel(new BorderLayout(UIScale.scale(6), 0)); + JButton browse = new JButton("Browse…"); + browse.addActionListener(e -> browseForPackFolder()); + dirRow.add(packDirField, BorderLayout.CENTER); + dirRow.add(browse, BorderLayout.EAST); + packDirField.setToolTipText("Extra folder to look for sound packs in"); + addRow(p, c, row++, new JLabel("Extra pack folder:"), dirRow); + + desktopNotifications.setSelected(settings.desktopNotifications); + c.gridx = 0; + c.gridy = row; + c.gridwidth = 2; + p.add(desktopNotifications, c); + c.gridwidth = 1; + return p; + } + + private JComponent buildFooter() { + JPanel p = new JPanel(new BorderLayout(UIScale.scale(6), 0)); + JLabel hint = new JLabel("Bold actions are important: they are still played " + + "while your speakers are muted."); + hint.setBorder(new ScaledEmptyBorder(4, 0, 0, 0)); + + JPanel buttons = new JPanel(); + JButton important = new JButton("Toggle important"); + important.addActionListener(e -> toggleImportant()); + JButton play = new JButton("Play"); + play.addActionListener(e -> previewSelected()); + JButton defaults = new JButton("Reset"); + defaults.setToolTipText("Restore the default notification settings"); + defaults.addActionListener(e -> { + working.resetToDefaults(); + tableModel.fireTableDataChanged(); + }); + buttons.add(play); + buttons.add(important); + buttons.add(defaults); + + p.add(hint, BorderLayout.CENTER); + p.add(buttons, BorderLayout.EAST); + return p; + } + + private JTable buildTable() { + JTable t = new JTable(tableModel); + t.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + t.setShowGrid(false); + t.setTableHeader(null); + t.setRowHeight(Math.max(t.getRowHeight(), t.getFontMetrics(t.getFont()).getHeight() + UIScale.scale(6))); + t.getColumnModel().getColumn(0).setMaxWidth(UIScale.scale(TOGGLE_COLUMN_WIDTH)); + t.getColumnModel().getColumn(0).setMinWidth(UIScale.scale(TOGGLE_COLUMN_WIDTH)); + t.getColumnModel().getColumn(0).setCellRenderer(new ToggleRenderer(t.getDefaultRenderer(Boolean.class))); + t.getColumnModel().getColumn(1).setCellRenderer(new ActionRenderer()); + t.setPreferredScrollableViewportSize(UIScale.scale(new Dimension(360, 260))); + + t.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() == 2 && e.getButton() == MouseEvent.BUTTON1) previewSelected(); + } + + @Override + public void mousePressed(MouseEvent e) { + showMenu(e); + } + + @Override + public void mouseReleased(MouseEvent e) { + showMenu(e); + } + + private void showMenu(MouseEvent e) { + if (!e.isPopupTrigger()) return; + int row = t.rowAtPoint(e.getPoint()); + if (row < 0 || rows.get(row).isHeading()) return; + t.setRowSelectionInterval(row, row); + contextMenu(rows.get(row).event).show(t, e.getX(), e.getY()); + } + }); + return t; + } + + private JPopupMenu contextMenu(SoundEvent event) { + JPopupMenu menu = new JPopupMenu(); + JMenuItem important = new JMenuItem(working.isImportant(event) ? "Mark as Unimportant" : "Mark as Important"); + important.addActionListener(e -> toggleImportant()); + JMenuItem enabled = new JMenuItem(working.isEnabled(event) ? "Turn sound off" : "Turn sound on"); + enabled.addActionListener(e -> { + working.setEnabled(event, !working.isEnabled(event)); + tableModel.fireTableRowsUpdated(0, rows.size() - 1); + }); + JMenuItem play = new JMenuItem("Play sound"); + play.addActionListener(e -> sounds.preview(event)); + menu.add(play); + menu.addSeparator(); + menu.add(enabled); + menu.add(important); + return menu; + } + + // ---- actions ---- + + private void onPackSelected() { + SoundPack pack = (SoundPack) packCombo.getSelectedItem(); + sounds.setPack(pack); + packInfo.setText(pack == null ? "No sound packs found" + : "by " + (pack.author().isEmpty() ? "unknown" : pack.author()) + + (pack.version().isEmpty() ? "" : ", version " + pack.version())); + tableModel.fireTableDataChanged(); + } + + private void reloadPacks() { + sounds.reload(); + packCombo.removeAllItems(); + for (SoundPack pack : sounds.availablePacks()) { + packCombo.addItem(pack); + } + packCombo.setSelectedItem(sounds.pack()); + onPackSelected(); + } + + private void browseForPackFolder() { + JFileChooser chooser = new JFileChooser(); + chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + chooser.setDialogTitle("Folder containing sound packs"); + String current = packDirField.getText().trim(); + if (!current.isEmpty()) chooser.setCurrentDirectory(new File(current)); + if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return; + packDirField.setText(chooser.getSelectedFile().getAbsolutePath()); + settings.soundPackDir = packDirField.getText(); + reloadPacks(); + } + + private SoundEvent selectedEvent() { + int row = table.getSelectedRow(); + return row < 0 || rows.get(row).isHeading() ? null : rows.get(row).event; + } + + private void previewSelected() { + SoundEvent event = selectedEvent(); + if (event != null) sounds.preview(event); + } + + private void toggleImportant() { + SoundEvent event = selectedEvent(); + if (event == null) return; + working.setImportant(event, !working.isImportant(event)); + tableModel.fireTableRowsUpdated(table.getSelectedRow(), table.getSelectedRow()); + } + + private void buildRows() { + for (SoundEvent.Category category : SoundEvent.Category.values()) { + rows.add(new Row(category, null)); + for (SoundEvent event : SoundEvent.values()) { + if (event.category() == category) rows.add(new Row(category, event)); + } + } + } + + private static void addRow(JPanel p, GridBagConstraints c, int row, JLabel label, Component field) { + c.gridx = 0; + c.gridy = row; + c.weightx = 0; + p.add(label, c); + c.gridx = 1; + c.weightx = 1; + p.add(field, c); + } + + // ---- table plumbing ---- + + private final class EventTableModel extends AbstractTableModel { + + @Override + public int getRowCount() { + return rows.size(); + } + + @Override + public int getColumnCount() { + return 2; + } + + @Override + public Class getColumnClass(int column) { + return column == 0 ? Boolean.class : String.class; + } + + @Override + public Object getValueAt(int rowIndex, int column) { + Row row = rows.get(rowIndex); + if (column == 0) return row.isHeading() ? Boolean.FALSE : working.isEnabled(row.event); + return row.isHeading() ? row.heading.label() : row.event.label(); + } + + @Override + public boolean isCellEditable(int rowIndex, int column) { + return column == 0 && !rows.get(rowIndex).isHeading(); + } + + @Override + public void setValueAt(Object value, int rowIndex, int column) { + Row row = rows.get(rowIndex); + if (column == 0 && !row.isHeading()) { + working.setEnabled(row.event, Boolean.TRUE.equals(value)); + } + } + } + + /** Only actions get a checkbox; a category heading spans an empty cell. */ + private final class ToggleRenderer implements javax.swing.table.TableCellRenderer { + + private final javax.swing.table.TableCellRenderer checkBox; + private final DefaultTableCellRenderer blank = new DefaultTableCellRenderer(); + + ToggleRenderer(javax.swing.table.TableCellRenderer checkBox) { + this.checkBox = checkBox; + } + + @Override + public Component getTableCellRendererComponent(JTable table, Object value, boolean selected, + boolean focused, int rowIndex, int column) { + javax.swing.table.TableCellRenderer delegate = rows.get(rowIndex).isHeading() ? blank : checkBox; + return delegate.getTableCellRendererComponent(table, + delegate == blank ? "" : value, selected, focused, rowIndex, column); + } + } + + /** Headings stand out, important actions are bold, unmapped ones are greyed. */ + private final class ActionRenderer extends DefaultTableCellRenderer { + + @Override + public Component getTableCellRendererComponent(JTable table, Object value, boolean selected, + boolean focused, int rowIndex, int column) { + super.getTableCellRendererComponent(table, value, selected, focused, rowIndex, column); + Row row = rows.get(rowIndex); + Font base = table.getFont(); + // The foreground is set on every row: this renderer remembers the last + // unselected colour it was given, so a greyed row would tint the rest. + if (row.isHeading()) { + setFont(base.deriveFont(Font.BOLD)); + setForeground(selected ? table.getSelectionForeground() : table.getForeground()); + setBorder(new ScaledEmptyBorder(2, 2, 2, 2)); + setToolTipText(null); + return this; + } + setBorder(new ScaledEmptyBorder(2, 18, 2, 2)); + setFont(base.deriveFont(working.isImportant(row.event) ? Font.BOLD : Font.PLAIN)); + boolean silent = !sounds.hasSound(row.event); + setForeground(selected ? table.getSelectionForeground() + : silent ? java.awt.Color.GRAY : table.getForeground()); + setToolTipText(silent ? "This sound pack has no sound for this action" : null); + return this; + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessageComposeDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessageComposeDialog.java new file mode 100644 index 0000000..7000e9b --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessageComposeDialog.java @@ -0,0 +1,457 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.FlatClientProperties; +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.contacts.Contact; +import eu.lixko.ts3j.client.contacts.ContactStore; +import eu.lixko.ts3j.client.contacts.ContactType; +import eu.lixko.ts3j.client.net.DatabaseClient; +import eu.lixko.ts3j.client.net.OfflineMessage; +import eu.lixko.ts3j.client.net.TeamspeakConnection; +import eu.lixko.ts3j.client.text.BBCode; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.DefaultListCellRenderer; +import javax.swing.DefaultListModel; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.ListSelectionModel; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.text.AbstractDocument; +import javax.swing.text.AttributeSet; +import javax.swing.text.BadLocationException; +import javax.swing.text.DocumentFilter; +import javax.swing.text.JTextComponent; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Window; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +/** + * Writing an offline message, as the official client's New / Reply Offline Message window: + * recipients, subject and text on the left, the clients one may pick from on the right. + * + *

    A recipient is typed as a unique id or a nickname. Unlike the official client, which + * only searches the server's database, a unique id is looked up directly, which needs no + * permission; a nickname needs {@code b_virtualserver_client_dbsearch}. + */ +final class OfflineMessageComposeDialog extends JDialog { + + private static final Pattern UNIQUE_ID = Pattern.compile("[A-Za-z0-9+/]{27}="); + /** The client property naming the recipient a chip stands for. */ + private static final String CHIP_UID = "ts3.recipientUid"; + + private final TeamspeakConnection conn; + + /** Recipients by unique id, in the order they were added. */ + private final Map recipients = new LinkedHashMap<>(); + private final JPanel recipientChips = new JPanel(new FlowLayout(FlowLayout.LEADING, UIScale.scale(4), UIScale.scale(2))); + private final JTextField recipientField = new JTextField(); + private final JLabel recipientError = new JLabel(); + private final JTextField subjectField = new JTextField(); + private final JTextArea bodyArea = new JTextArea(); + private final JLabel limitLabel = new JLabel(" "); + private final DefaultListModel available = new DefaultListModel<>(); + private final JList availableList = new JList<>(available); + private final JButton sendButton = new JButton("Send"); + private boolean sending; + + static OfflineMessageComposeDialog compose(Window owner, TeamspeakConnection conn, ContactStore contacts) { + return new OfflineMessageComposeDialog(owner, "New Offline Message", conn, contacts); + } + + /** A reply to {@code message}, quoting {@code body}. */ + static OfflineMessageComposeDialog reply(Window owner, TeamspeakConnection conn, ContactStore contacts, + OfflineMessage message, String body) { + OfflineMessageComposeDialog d = new OfflineMessageComposeDialog(owner, "Reply Offline Message", conn, contacts); + d.addRecipient(new DatabaseClient(message.senderUid(), 0, message.senderName())); + String subject = message.subject().regionMatches(true, 0, "Re:", 0, 3) + ? message.subject() : "Re: " + message.subject(); + d.subjectField.setText(subject.length() > TeamspeakConnection.OFFLINE_MESSAGE_SUBJECT_LIMIT + ? subject.substring(0, TeamspeakConnection.OFFLINE_MESSAGE_SUBJECT_LIMIT) : subject); + d.bodyArea.setText(quote(message.senderName(), body)); + d.bodyArea.setCaretPosition(d.bodyArea.getDocument().getLength()); + return d; + } + + /** The reply's opening, as the official client writes it: who wrote, then their text marked with "> ". */ + private static String quote(String sender, String body) { + StringBuilder out = new StringBuilder("\"").append(sender).append("\" wrote:\n"); + for (String line : body.split("\n", -1)) out.append("> ").append(line).append('\n'); + return out.toString(); + } + + private OfflineMessageComposeDialog(Window owner, String title, TeamspeakConnection conn, ContactStore contacts) { + super(owner, title, ModalityType.MODELESS); + this.conn = conn; + + limit(subjectField, TeamspeakConnection.OFFLINE_MESSAGE_SUBJECT_LIMIT); + limit(bodyArea, TeamspeakConnection.OFFLINE_MESSAGE_LIMIT); + for (Contact c : contacts.all()) { + if (c.type != ContactType.BLOCKED) { + available.addElement(new DatabaseClient(c.uniqueId, 0, c.nickname.isEmpty() ? c.uniqueId : c.nickname)); + } + } + sortAvailable(); + + JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, buildMessage(), buildAvailable()); + split.setResizeWeight(1); + split.setBorder(null); + split.setOpaque(false); + + JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(8))); + content.setBackground(Theme.windowBg()); + content.setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); + content.add(split, BorderLayout.CENTER); + content.add(buildButtons(), BorderLayout.SOUTH); + setContentPane(content); + + setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + cancel(); + } + }); + Dialogs.closeOnEscape(this, this::cancel); + setPreferredSize(UIScale.scale(new Dimension(620, 460))); + pack(); + setLocationRelativeTo(owner); + updateSendButton(); + } + + // ---- construction ---- + + private JPanel buildMessage() { + recipientChips.setOpaque(false); + recipientField.putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, "Nickname or unique ID"); + recipientField.addActionListener(e -> resolveTyped()); + recipientField.addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE && recipientField.getText().isEmpty() + && !recipients.isEmpty()) { + removeRecipient(new ArrayList<>(recipients.keySet()).get(recipients.size() - 1)); + } + } + }); + recipientField.getDocument().addDocumentListener(onChange(() -> recipientError.setVisible(false))); + recipientError.setForeground(UIManager.getColor("Actions.Red")); + recipientError.setVisible(false); + + JPanel recipientBox = new JPanel(); + recipientBox.setLayout(new BoxLayout(recipientBox, BoxLayout.Y_AXIS)); + recipientBox.setOpaque(false); + recipientBox.add(left(recipientChips)); + recipientBox.add(left(recipientField)); + recipientBox.add(left(recipientError)); + + JPanel subjectRow = new JPanel(new BorderLayout(UIScale.scale(6), 0)); + subjectRow.setOpaque(false); + JLabel subjectLabel = new JLabel("Subject:"); + subjectLabel.setDisplayedMnemonic(KeyEvent.VK_S); + subjectLabel.setLabelFor(subjectField); + subjectRow.add(subjectLabel, BorderLayout.WEST); + subjectRow.add(subjectField, BorderLayout.CENTER); + + JPanel top = new JPanel(); + top.setLayout(new BoxLayout(top, BoxLayout.Y_AXIS)); + top.setOpaque(false); + top.add(left(new JLabel("Recipients:"))); + top.add(left(recipientBox)); + top.add(Box.createVerticalStrut(UIScale.scale(8))); + top.add(left(subjectRow)); + + bodyArea.setLineWrap(true); + bodyArea.setWrapStyleWord(true); + bodyArea.setFont(Theme.uiFont()); + bodyArea.getDocument().addDocumentListener(onChange(this::updateSendButton)); + limitLabel.setForeground(UIManager.getColor("Actions.Red")); + + JPanel panel = new JPanel(new BorderLayout(0, UIScale.scale(6))); + panel.setOpaque(false); + panel.setBorder(new ScaledEmptyBorder(0, 0, 0, 6)); + panel.add(top, BorderLayout.NORTH); + panel.add(new JScrollPane(bodyArea), BorderLayout.CENTER); + panel.add(limitLabel, BorderLayout.SOUTH); + return panel; + } + + private JPanel buildAvailable() { + availableList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + availableList.setCellRenderer(new DefaultListCellRenderer() { + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, + boolean selected, boolean focused) { + DatabaseClient c = (DatabaseClient) value; + String text = c.databaseId() > 0 ? c.nickname() + " (" + c.databaseId() + ")" : c.nickname(); + super.getListCellRendererComponent(list, text, index, selected, focused); + setToolTipText(c.uniqueId()); + return this; + } + }); + availableList.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e)) addChosen(); + } + }); + availableList.addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ENTER) addChosen(); + } + }); + + JPanel panel = new JPanel(new BorderLayout(0, UIScale.scale(4))); + panel.setOpaque(false); + panel.setBorder(new ScaledEmptyBorder(0, 6, 0, 0)); + panel.add(new JLabel("Available Contacts:"), BorderLayout.NORTH); + panel.add(new JScrollPane(availableList), BorderLayout.CENTER); + panel.setPreferredSize(UIScale.scale(new Dimension(170, 0))); + return panel; + } + + private JPanel buildButtons() { + sendButton.addActionListener(e -> send()); + JButton cancel = new JButton("Cancel"); + cancel.addActionListener(e -> cancel()); + JPanel row = new JPanel(new BorderLayout()); + row.setOpaque(false); + row.add(sendButton, BorderLayout.WEST); + row.add(cancel, BorderLayout.EAST); + return row; + } + + /** Lines a component up on the left of a vertical box; a text field keeps its height. */ + private static Component left(JComponent c) { + c.setAlignmentX(LEFT_ALIGNMENT); + if (c instanceof JTextField) c.setMaximumSize(new Dimension(Integer.MAX_VALUE, c.getPreferredSize().height)); + return c; + } + + private static DocumentListener onChange(Runnable action) { + return new DocumentListener() { + @Override + public void insertUpdate(DocumentEvent e) { + action.run(); + } + + @Override + public void removeUpdate(DocumentEvent e) { + action.run(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + action.run(); + } + }; + } + + /** Caps a field at what the server accepts, saying so when typing runs into it. */ + private void limit(JTextComponent field, int max) { + ((AbstractDocument) field.getDocument()).setDocumentFilter(new DocumentFilter() { + @Override + public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr) + throws BadLocationException { + replace(fb, offset, 0, text, attr); + } + + @Override + public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) + throws BadLocationException { + String added = text == null ? "" : text; + int room = max - (fb.getDocument().getLength() - length); + if (added.length() > room) { + added = added.substring(0, Math.max(0, room)); + limitLabel.setText("Character limit reached (" + max + ")"); + } + super.replace(fb, offset, length, added, attrs); + } + + @Override + public void remove(FilterBypass fb, int offset, int length) throws BadLocationException { + super.remove(fb, offset, length); + limitLabel.setText(" "); + } + }); + } + + // ---- recipients ---- + + private void addRecipient(DatabaseClient client) { + if (client.uniqueId().isEmpty() || recipients.containsKey(client.uniqueId())) return; + recipients.put(client.uniqueId(), client); + recipientChips.add(chip(client)); + recipientChips.revalidate(); + recipientChips.repaint(); + updateSendButton(); + } + + private void removeRecipient(String uniqueId) { + if (recipients.remove(uniqueId) == null) return; + for (Component c : recipientChips.getComponents()) { + if (uniqueId.equals(((JPanel) c).getClientProperty(CHIP_UID))) recipientChips.remove(c); + } + recipientChips.revalidate(); + recipientChips.repaint(); + updateSendButton(); + } + + /** A recipient's name with a cross that takes them off again. */ + private JPanel chip(DatabaseClient client) { + JLabel name = new JLabel(client.nickname().isEmpty() ? client.uniqueId() : client.nickname()); + name.setToolTipText(client.uniqueId()); + JLabel remove = new JLabel("×"); + remove.setToolTipText("Remove"); + remove.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + remove.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + removeRecipient(client.uniqueId()); + } + }); + JPanel chip = new JPanel(new FlowLayout(FlowLayout.LEADING, UIScale.scale(4), 0)); + chip.putClientProperty(CHIP_UID, client.uniqueId()); + chip.setBackground(Theme.treeBg()); + chip.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Theme.border()), + new ScaledEmptyBorder(1, 2, 1, 2))); + chip.add(name); + chip.add(remove); + return chip; + } + + private void addChosen() { + DatabaseClient chosen = availableList.getSelectedValue(); + if (chosen != null) addRecipient(chosen); + } + + /** Turns what was typed into a recipient: a unique id directly, a nickname by contacts or a server search. */ + private void resolveTyped() { + String typed = recipientField.getText().trim(); + if (typed.isEmpty()) return; + if (UNIQUE_ID.matcher(typed).matches()) { + conn.lookupDatabaseClient(typed, (client, error) -> SwingUtilities.invokeLater(() -> { + if (error != null) showRecipientError(error); + else if (client == null) showRecipientError("The unique ID is unknown on this server."); + else accept(client); + })); + return; + } + for (int i = 0; i < available.size(); i++) { + if (available.get(i).nickname().equalsIgnoreCase(typed)) { + accept(available.get(i)); + return; + } + } + conn.searchDatabaseClients(typed, (found, error) -> SwingUtilities.invokeLater(() -> { + if (error != null) { + showRecipientError(error); + } else if (found.isEmpty()) { + showRecipientError("The nickname is unknown on this server."); + } else { + offer(found); + DatabaseClient exact = found.stream().filter(c -> c.nickname().equalsIgnoreCase(typed)) + .findFirst().orElse(found.size() == 1 ? found.get(0) : null); + if (exact != null) accept(exact); + } + })); + } + + private void accept(DatabaseClient client) { + addRecipient(client); + recipientField.setText(""); + } + + /** Lists search results among the contacts, so a match can be picked from them. */ + private void offer(List found) { + for (DatabaseClient c : found) { + boolean listed = false; + for (int i = 0; i < available.size() && !listed; i++) { + listed = available.get(i).uniqueId().equals(c.uniqueId()); + } + if (!listed) available.addElement(c); + } + sortAvailable(); + availableList.setSelectedValue(found.get(0), true); + } + + private void sortAvailable() { + List sorted = new ArrayList<>(); + for (int i = 0; i < available.size(); i++) sorted.add(available.get(i)); + sorted.sort(Comparator.comparing(DatabaseClient::nickname, String.CASE_INSENSITIVE_ORDER)); + available.clear(); + sorted.forEach(available::addElement); + } + + private void showRecipientError(String message) { + if (!isDisplayable()) return; + recipientError.setText("" + BBCode.escape(message) + ""); + recipientError.setVisible(true); + recipientError.getParent().revalidate(); + } + + // ---- sending ---- + + private void updateSendButton() { + sendButton.setEnabled(!sending && !recipients.isEmpty() && !bodyArea.getText().isBlank()); + } + + private void send() { + if (!sendButton.isEnabled()) return; + sending = true; + updateSendButton(); + conn.sendOfflineMessage(new ArrayList<>(recipients.keySet()), subjectField.getText(), bodyArea.getText(), + error -> SwingUtilities.invokeLater(() -> { + sending = false; + if (!isDisplayable()) return; + if (error == null) { + dispose(); + return; + } + updateSendButton(); + JOptionPane.showMessageDialog(this, "Failed to send offline message: " + error, getTitle(), + JOptionPane.ERROR_MESSAGE); + })); + } + + private void cancel() { + if (!recipients.isEmpty()) { + int answer = JOptionPane.showConfirmDialog(this, + "The list of recipients is not empty and the message has not yet been sent.\nDo you want to cancel?", + "Please Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); + if (answer != JOptionPane.YES_OPTION) return; + } + dispose(); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessagesDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessagesDialog.java new file mode 100644 index 0000000..e5d22c7 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessagesDialog.java @@ -0,0 +1,573 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.net.OfflineMessage; +import eu.lixko.ts3j.client.net.TeamspeakConnection; +import eu.lixko.ts3j.client.text.BBCode; + +import javax.swing.AbstractAction; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JEditorPane; +import javax.swing.JLabel; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.JTable; +import javax.swing.JTextField; +import javax.swing.KeyStroke; +import javax.swing.ListSelectionModel; +import javax.swing.RowSorter; +import javax.swing.SortOrder; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.event.HyperlinkEvent; +import javax.swing.event.PopupMenuEvent; +import javax.swing.event.PopupMenuListener; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.TableRowSorter; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Frame; +import java.awt.Point; +import java.awt.event.ActionEvent; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Our offline message inbox on one server, as the official client's Tools > Offline Messages + * window: the messages above, the selected one's subject and text below. Viewing a message + * marks it read. + * + *

    One per server tab and modeless; the tab closes it when the connection goes away. + */ +final class OfflineMessagesDialog extends JDialog { + + private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + /** Where Compose and Reply lead: the tab opens the compose window. */ + interface Composer { + void compose(); + + void reply(OfflineMessage message, String body); + } + + private enum Column { + STATE("", 24), + SUBJECT("Subject", 200), + SENDER("Sender", 110), + DATE("Date", 150); + + final String title; + final int width; + + Column(String title, int width) { + this.title = title; + this.width = width; + } + } + + private final TeamspeakConnection conn; + private final Composer composer; + + private final MessageTableModel tableModel = new MessageTableModel(); + private final JTable table = new JTable(tableModel) { + /** + * The popup acts on what was clicked; Swing asks here before showing it. As in the + * official client, that selects the row without opening it in the reader. + */ + @Override + public Point getPopupLocation(MouseEvent e) { + int row = e == null ? -1 : rowAtPoint(e.getPoint()); + if (row >= 0 && !isRowSelected(row)) { + selectingForPopup = true; + try { + setRowSelectionInterval(row, row); + } finally { + selectingForPopup = false; + } + } + return super.getPopupLocation(e); + } + }; + private final JButton composeButton = new JButton("Compose"); + private final JButton replyButton = new JButton("Reply"); + private final JButton deleteButton = new JButton("Delete"); + private final JTextField subjectField = new JTextField(); + private final JEditorPane bodyPane = HtmlStyles.pane("font-family:sans-serif; font-size:11px;"); + private final JLabel status = new JLabel(" "); + + /** Bodies already read, by message id; each costs a {@code messageget}. */ + private final Map bodies = new HashMap<>(); + /** The message the reader shows or is loading, or -1. */ + private int shownId = -1; + /** Set while a right-click selects its row, which leaves the reader alone. */ + private boolean selectingForPopup; + private boolean loading; + + OfflineMessagesDialog(Frame owner, TeamspeakConnection conn, Composer composer) { + super(owner, "Offline Messages", false); + this.conn = conn; + this.composer = composer; + + JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, buildTable(), buildReader()); + split.setResizeWeight(0.45); + split.setBorder(null); + split.setOpaque(false); + + JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(6))); + content.setBackground(Theme.windowBg()); + content.setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); + content.add(buildToolbar(), BorderLayout.NORTH); + content.add(split, BorderLayout.CENTER); + content.add(buildBottom(), BorderLayout.SOUTH); + setContentPane(content); + bindKeys(); + + serverNameChanged(); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + setPreferredSize(UIScale.scale(new Dimension(600, 560))); + pack(); + setLocationRelativeTo(owner); + updateButtons(); + reload(); + } + + // ---- construction ---- + + private JPanel buildToolbar() { + composeButton.setMnemonic(KeyEvent.VK_C); + composeButton.setToolTipText("Compose a new message
    (Ctrl+N)"); + composeButton.addActionListener(e -> compose()); + replyButton.setMnemonic(KeyEvent.VK_R); + replyButton.setToolTipText("Reply to message"); + replyButton.addActionListener(e -> replySelected()); + deleteButton.setMnemonic(KeyEvent.VK_D); + deleteButton.setToolTipText("Delete selected messages
    (Del)"); + deleteButton.addActionListener(e -> deleteSelected()); + + JPanel bar = new JPanel(); + bar.setLayout(new BoxLayout(bar, BoxLayout.X_AXIS)); + bar.setOpaque(false); + bar.add(composeButton); + bar.add(Box.createHorizontalStrut(UIScale.scale(6))); + bar.add(replyButton); + bar.add(Box.createHorizontalGlue()); + bar.add(deleteButton); + return bar; + } + + private JScrollPane buildTable() { + table.setFont(Theme.uiFont()); + table.setRowHeight(UIScale.scale(20)); + table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); + table.setFillsViewportHeight(true); + table.setShowGrid(false); + table.getTableHeader().setReorderingAllowed(false); + table.setComponentPopupMenu(tablePopup()); + table.getSelectionModel().addListSelectionListener(e -> { + if (e.getValueIsAdjusting()) return; + updateButtons(); + if (!selectingForPopup) showSelected(); + }); + MessageCellRenderer renderer = new MessageCellRenderer(); + for (Column c : Column.values()) { + table.getColumnModel().getColumn(c.ordinal()).setPreferredWidth(UIScale.scale(c.width)); + table.getColumnModel().getColumn(c.ordinal()).setCellRenderer(renderer); + } + table.getColumnModel().getColumn(Column.STATE.ordinal()).setMaxWidth(UIScale.scale(Column.STATE.width)); + + TableRowSorter sorter = new TableRowSorter<>(tableModel); + sorter.setComparator(Column.SUBJECT.ordinal(), String.CASE_INSENSITIVE_ORDER); + sorter.setComparator(Column.SENDER.ordinal(), String.CASE_INSENSITIVE_ORDER); + sorter.setSortKeys(List.of(new RowSorter.SortKey(Column.DATE.ordinal(), SortOrder.ASCENDING))); + table.setRowSorter(sorter); + + JScrollPane scroll = new JScrollPane(table); + scroll.getViewport().setBackground(Theme.treeBg()); + scroll.setMinimumSize(UIScale.scale(new Dimension(0, 80))); + return scroll; + } + + private JPanel buildReader() { + subjectField.setEditable(false); + bodyPane.addHyperlinkListener(e -> { + if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) Links.open(e.getDescription(), this); + }); + + JPanel subjectRow = new JPanel(new BorderLayout(UIScale.scale(6), 0)); + subjectRow.setOpaque(false); + subjectRow.add(new JLabel("Subject:"), BorderLayout.WEST); + subjectRow.add(subjectField, BorderLayout.CENTER); + + JScrollPane bodyScroll = new JScrollPane(bodyPane); + HtmlStyles.fillViewport(bodyPane); + + JPanel reader = new JPanel(new BorderLayout(0, UIScale.scale(6))); + reader.setOpaque(false); + reader.setBorder(new ScaledEmptyBorder(6, 0, 0, 0)); + reader.add(subjectRow, BorderLayout.NORTH); + reader.add(bodyScroll, BorderLayout.CENTER); + reader.setMinimumSize(UIScale.scale(new Dimension(0, 100))); + return reader; + } + + private JPanel buildBottom() { + JButton reload = new JButton("Reload", Icons.of("REFRESH")); + reload.setToolTipText("Reload messages
    (F5)"); + reload.addActionListener(e -> reload()); + JButton close = new JButton("Close"); + close.addActionListener(e -> dispose()); + + JPanel row = new JPanel(new BorderLayout()); + row.setOpaque(false); + row.add(reload, BorderLayout.WEST); + row.add(close, BorderLayout.EAST); + + JPanel bottom = new JPanel(new BorderLayout(0, UIScale.scale(8))); + bottom.setOpaque(false); + bottom.add(status, BorderLayout.NORTH); + bottom.add(row, BorderLayout.SOUTH); + status.setForeground(Theme.chatEvent()); + return bottom; + } + + private JPopupMenu tablePopup() { + JMenuItem reply = item("Reply to message", this::replySelected); + JMenuItem delete = item("Delete message", this::deleteSelected); + JMenuItem markRead = item("Mark as Read", () -> markSelected(true)); + JMenuItem markUnread = item("Mark as Unread", () -> markSelected(false)); + JPopupMenu menu = new JPopupMenu(); + menu.add(reply); + menu.add(delete); + menu.addSeparator(); + menu.add(item("Reload messages", this::reload)); + menu.addSeparator(); + menu.add(markRead); + menu.add(markUnread); + menu.addPopupMenuListener(new PopupMenuListener() { + @Override + public void popupMenuWillBecomeVisible(PopupMenuEvent e) { + List selected = selectedMessages(); + reply.setEnabled(replyButton.isEnabled()); + delete.setEnabled(!selected.isEmpty()); + markRead.setEnabled(selected.stream().anyMatch(m -> !m.read())); + markUnread.setEnabled(selected.stream().anyMatch(OfflineMessage::read)); + } + + @Override + public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { + } + + @Override + public void popupMenuCanceled(PopupMenuEvent e) { + } + }); + return menu; + } + + private static JMenuItem item(String text, Runnable action) { + JMenuItem item = new JMenuItem(text); + item.addActionListener(e -> action.run()); + return item; + } + + private void bindKeys() { + bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("F5"), this::reload); + bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control N"), this::compose); + bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control W"), this::dispose); + bind(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), + this::deleteSelected); + Dialogs.closeOnEscape(this); + } + + private static void bind(JComponent target, int condition, KeyStroke key, Runnable action) { + String name = "ts3-offline-messages-" + key; + target.getInputMap(condition).put(key, name); + target.getActionMap().put(name, new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + action.run(); + } + }); + } + + // ---- data ---- + + void serverNameChanged() { + String name = conn.getModel().getServerName(); + setTitle(name == null || name.isBlank() ? "Offline Messages" : "Offline Messages on " + name); + } + + void connectionLost() { + dispose(); + } + + /** Reads the inbox again, keeping the selection where the messages are still there. */ + void reload() { + if (loading) return; + loading = true; + status.setText("Loading…"); + conn.requestOfflineMessages((messages, error) -> SwingUtilities.invokeLater(() -> { + loading = false; + if (!isDisplayable()) return; + if (error != null) { + status.setText("Failed to list offline messages: " + error); + return; + } + setMessages(messages); + status.setText(messages.isEmpty() ? "No messages" : " "); + })); + } + + private void setMessages(List messages) { + Set selected = new HashSet<>(); + for (OfflineMessage m : selectedMessages()) selected.add(m.id()); + tableModel.setMessages(messages); + for (int i = 0; i < messages.size(); i++) { + if (!selected.contains(messages.get(i).id())) continue; + int view = table.convertRowIndexToView(i); + if (view >= 0) table.addRowSelectionInterval(view, view); + } + updateButtons(); + showSelected(); + } + + private List selectedMessages() { + List out = new ArrayList<>(); + for (int view : table.getSelectedRows()) out.add(tableModel.get(table.convertRowIndexToModel(view))); + return out; + } + + private OfflineMessage singleSelected() { + List selected = selectedMessages(); + return selected.size() == 1 ? selected.get(0) : null; + } + + private void updateButtons() { + boolean canSend = conn.canSendOfflineMessages(); + composeButton.setEnabled(canSend); + replyButton.setEnabled(canSend && singleSelected() != null); + deleteButton.setEnabled(table.getSelectedRowCount() > 0); + } + + /** Shows the selected message in the reader, reading its body first if need be, and marks it read. */ + private void showSelected() { + OfflineMessage message = singleSelected(); + if (message == null) { + shownId = -1; + subjectField.setText(""); + bodyPane.setText(""); + return; + } + if (message.id() == shownId) return; + shownId = message.id(); + subjectField.setText(message.subject()); + subjectField.setCaretPosition(0); + String body = bodies.get(message.id()); + if (body != null) { + showBody(message, body); + return; + } + bodyPane.setText(""); + conn.requestOfflineMessageBody(message.id(), (text, error) -> SwingUtilities.invokeLater(() -> { + if (!isDisplayable()) return; + if (error != null) { + if (shownId == message.id()) status.setText("Failed to get offline message: " + error); + return; + } + bodies.put(message.id(), text); + if (shownId == message.id()) showBody(message, text); + })); + } + + private void showBody(OfflineMessage message, String body) { + bodyPane.setText("" + BBCode.toHtml(body) + ""); + bodyPane.setCaretPosition(0); + if (!message.read()) mark(List.of(message), true); + } + + // ---- actions ---- + + private void compose() { + if (composeButton.isEnabled()) composer.compose(); + } + + private void replySelected() { + OfflineMessage message = singleSelected(); + if (message == null || !replyButton.isEnabled()) return; + String body = bodies.get(message.id()); + if (body != null) { + composer.reply(message, body); + return; + } + conn.requestOfflineMessageBody(message.id(), (text, error) -> SwingUtilities.invokeLater(() -> { + if (!isDisplayable()) return; + if (error != null) { + status.setText("Failed to get offline message: " + error); + return; + } + bodies.put(message.id(), text); + composer.reply(message, text); + })); + } + + private void markSelected(boolean read) { + mark(selectedMessages().stream().filter(m -> m.read() != read).toList(), read); + } + + /** Flags messages read or unread, showing the change straight away. */ + private void mark(List messages, boolean read) { + if (messages.isEmpty()) return; + for (OfflineMessage m : messages) tableModel.replace(m.withRead(read)); + conn.markOfflineMessages(messages.stream().map(OfflineMessage::id).toList(), read, + error -> SwingUtilities.invokeLater(() -> { + if (error == null || !isDisplayable()) return; + status.setText("Failed to update offline message: " + error); + reload(); + })); + } + + private void deleteSelected() { + List selected = selectedMessages(); + if (selected.isEmpty()) return; + List unread = selected.stream().filter(m -> !m.read()).toList(); + if (!unread.isEmpty()) { + String question = unread.size() == 1 + ? "Do you really want to delete the unread message
    with subject: \"" + + BBCode.escape(subjectOrPlaceholder(unread.get(0))) + "\"?" + : "Do you really want to delete " + unread.size() + " unread messages?"; + int answer = JOptionPane.showConfirmDialog(this, question, "Delete Offline Message", + JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); + if (answer != JOptionPane.YES_OPTION) return; + } + conn.deleteOfflineMessages(selected.stream().map(OfflineMessage::id).toList(), + error -> SwingUtilities.invokeLater(() -> { + if (!isDisplayable()) return; + if (error != null) { + JOptionPane.showMessageDialog(this, "Failed to delete offline message: " + error, + getTitle(), JOptionPane.ERROR_MESSAGE); + } + for (OfflineMessage m : selected) bodies.remove(m.id()); + reload(); + })); + } + + private static String subjectOrPlaceholder(OfflineMessage m) { + return m.subject().isEmpty() ? "" : m.subject(); + } + + // ---- table ---- + + private static final class MessageTableModel extends AbstractTableModel { + + private List messages = List.of(); + + void setMessages(List messages) { + this.messages = new ArrayList<>(messages); + fireTableDataChanged(); + } + + OfflineMessage get(int row) { + return messages.get(row); + } + + void replace(OfflineMessage message) { + for (int i = 0; i < messages.size(); i++) { + if (messages.get(i).id() != message.id()) continue; + messages.set(i, message); + fireTableRowsUpdated(i, i); + return; + } + } + + @Override + public int getRowCount() { + return messages.size(); + } + + @Override + public int getColumnCount() { + return Column.values().length; + } + + @Override + public String getColumnName(int column) { + return Column.values()[column].title; + } + + @Override + public Class getColumnClass(int column) { + return switch (Column.values()[column]) { + case STATE -> Boolean.class; + case DATE -> Long.class; + default -> String.class; + }; + } + + @Override + public Object getValueAt(int row, int column) { + OfflineMessage m = messages.get(row); + return switch (Column.values()[column]) { + case STATE -> m.read(); + case SUBJECT -> m.subject(); + case SENDER -> m.senderName(); + case DATE -> m.timestampEpochSeconds(); + }; + } + } + + /** Unread messages in bold, as the official client shows them; a missing subject greyed out. */ + private final class MessageCellRenderer extends DefaultTableCellRenderer { + @Override + public Component getTableCellRendererComponent(JTable t, Object value, boolean selected, + boolean focused, int row, int column) { + // setForeground sticks as the renderer's unselected colour; clear it so the + // table's own colour applies again after a greyed cell. + setForeground(null); + OfflineMessage m = tableModel.get(t.convertRowIndexToModel(row)); + Column c = Column.values()[column]; + Object shown = switch (c) { + case STATE -> ""; + case SUBJECT -> subjectOrPlaceholder(m); + case DATE -> m.timestampEpochSeconds() <= 0 ? "" : DATE.format( + Instant.ofEpochSecond(m.timestampEpochSeconds()).atZone(ZoneId.systemDefault())); + default -> value; + }; + super.getTableCellRendererComponent(t, shown, selected, focused, row, column); + setFont(m.read() ? t.getFont() : t.getFont().deriveFont(Font.BOLD)); + setBorder(new ScaledEmptyBorder(0, 2, 0, 2)); + setHorizontalAlignment(c == Column.STATE ? CENTER : LEADING); + setIcon(c == Column.STATE ? stateIcon(m.read()) : null); + setToolTipText(c == Column.SENDER && !m.senderUid().equals(m.senderName()) ? m.senderUid() : null); + if (c == Column.SUBJECT && m.subject().isEmpty() && !selected) { + setForeground(UIManager.getColor("Label.disabledForeground")); + } + return this; + } + } + + private static Icon stateIcon(boolean read) { + return read ? Icons.of("MESSAGES") : Icons.of("OFFLINE_MESSAGES"); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OptionsPage.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OptionsPage.java new file mode 100644 index 0000000..5406f27 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OptionsPage.java @@ -0,0 +1,26 @@ +package eu.lixko.ts3j.client.ui; + +import javax.swing.ImageIcon; +import javax.swing.JComponent; +import java.util.List; + +/** + * One page of the Options dialog, as the sidebar lists it. + * + * @param iconKeys TeamSpeak icon keys to try in turn, since packs differ in what they ship + */ +record OptionsPage(String title, List iconKeys, JComponent content) { + + OptionsPage(String title, JComponent content, String... iconKeys) { + this(title, List.of(iconKeys), content); + } + + /** @return the page's icon at {@code size} pixels, or {@code null} when the pack has none */ + ImageIcon icon(int size) { + for (String key : iconKeys) { + ImageIcon icon = IconTheme.icon(key, size); + if (icon != null) return icon; + } + return null; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OptionsSidebar.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OptionsSidebar.java new file mode 100644 index 0000000..1df0598 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OptionsSidebar.java @@ -0,0 +1,109 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; + +import javax.swing.DefaultListModel; +import javax.swing.Icon; +import javax.swing.ImageIcon; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.ListCellRenderer; +import javax.swing.ListSelectionModel; +import javax.swing.UIManager; +import java.awt.Color; +import java.awt.Component; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.util.List; + +/** The Options dialog's page list: large icons with their titles, one page per row, as in TS3. */ +final class OptionsSidebar extends JList { + + static final int ICON_SIZE = 32; + + OptionsSidebar(List pages) { + super(model(pages)); + setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + setCellRenderer(new Renderer()); + setBorder(new ScaledEmptyBorder(4, 4, 4, 4)); + } + + private static DefaultListModel model(List pages) { + DefaultListModel model = new DefaultListModel<>(); + pages.forEach(model::addElement); + return model; + } + + /** + * Paints its own rounded selection in the accent colour: the list's selection would turn + * grey whenever focus moves into the page, and the sidebar should always show where you are. + */ + private static final class Renderer extends JLabel implements ListCellRenderer { + + private boolean selected; + + Renderer() { + setOpaque(false); + setBorder(new ScaledEmptyBorder(6, 8, 6, 16)); + } + + @Override + public Component getListCellRendererComponent(JList list, OptionsPage page, + int index, boolean isSelected, boolean focus) { + int size = UIScale.scale(ICON_SIZE); + ImageIcon icon = page.icon(size); + setIcon(icon != null ? icon : new BlankIcon(size)); + setIconTextGap(UIScale.scale(10)); + setText(page.title()); + setFont(list.getFont()); + selected = isSelected; + setForeground(isSelected ? selectionForeground() : list.getForeground()); + return this; + } + + @Override + protected void paintComponent(Graphics g) { + if (selected) { + Graphics2D g2 = (Graphics2D) g.create(); + try { + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g2.setColor(accent()); + int arc = UIScale.scale(8); + g2.fillRoundRect(0, 0, getWidth(), getHeight(), arc, arc); + } finally { + g2.dispose(); + } + } + super.paintComponent(g); + } + + private static Color accent() { + Color c = UIManager.getColor("Component.accentColor"); + return c != null ? c : UIManager.getColor("List.selectionBackground"); + } + + private static Color selectionForeground() { + Color c = UIManager.getColor("List.selectionForeground"); + return c != null ? c : Color.WHITE; + } + } + + /** Keeps the titles lined up for a page whose icon the pack lacks. */ + private record BlankIcon(int size) implements Icon { + @Override + public void paintIcon(Component c, Graphics g, int x, int y) { + } + + @Override + public int getIconWidth() { + return size; + } + + @Override + public int getIconHeight() { + return size; + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PictureViewer.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PictureViewer.java new file mode 100644 index 0000000..7932ff5 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PictureViewer.java @@ -0,0 +1,78 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; + +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.KeyStroke; +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.GraphicsConfiguration; +import java.awt.Image; +import java.awt.Rectangle; +import java.awt.Window; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.image.BufferedImage; + +/** A picture at full size, or as large as the screen allows, with a way to save it. */ +final class PictureViewer extends JDialog { + + private static final int MIN_WIDTH = 360; + private static final int MIN_HEIGHT = 240; + + PictureViewer(Window owner, String title, BufferedImage picture, Runnable onSave) { + super(owner, title, ModalityType.MODELESS); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + + JLabel view = new JLabel(new ImageIcon(fitted(picture, owner))); + view.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + dispose(); + } + }); + JScrollPane scroll = new JScrollPane(view); + scroll.setBorder(null); + + JButton save = new JButton("Save…"); + save.addActionListener(e -> onSave.run()); + JButton close = new JButton("Close"); + close.addActionListener(e -> dispose()); + JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT, UIScale.scale(4), 0)); + buttons.setBorder(new ScaledEmptyBorder(6, 6, 6, 6)); + buttons.add(save); + buttons.add(close); + + add(scroll, BorderLayout.CENTER); + add(buttons, BorderLayout.SOUTH); + getRootPane().registerKeyboardAction(e -> dispose(), KeyStroke.getKeyStroke("ESCAPE"), + JComponent.WHEN_IN_FOCUSED_WINDOW); + getRootPane().setDefaultButton(close); + pack(); + // A small picture still gets a window its title and buttons fit in. + setSize(Math.max(getWidth(), UIScale.scale(MIN_WIDTH)), Math.max(getHeight(), UIScale.scale(MIN_HEIGHT))); + setLocationRelativeTo(owner); + } + + /** The picture narrowed to most of the owner's screen; small ones are left as they are. */ + private static Image fitted(BufferedImage picture, Window owner) { + GraphicsConfiguration gc = owner != null ? owner.getGraphicsConfiguration() : null; + Rectangle screen = gc != null ? gc.getBounds() : new Rectangle(new Dimension(1280, 800)); + int maxWidth = screen.width * 85 / 100; + int maxHeight = screen.height * 75 / 100; + int width = picture.getWidth(); + int height = picture.getHeight(); + double scale = Math.min(1, Math.min(maxWidth / (double) width, maxHeight / (double) height)); + if (scale >= 1) return picture; + return picture.getScaledInstance(Math.max(1, (int) (width * scale)), Math.max(1, (int) (height * scale)), + Image.SCALE_SMOOTH); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PlaybackPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PlaybackPanel.java new file mode 100644 index 0000000..ac332b4 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PlaybackPanel.java @@ -0,0 +1,62 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.audio.AudioDevice; +import eu.lixko.ts3j.client.audio.AudioIo; +import eu.lixko.ts3j.client.audio.VoiceOutput; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.sound.SoundEvent; +import eu.lixko.ts3j.client.sound.SoundNotifier; + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JSlider; +import java.awt.FlowLayout; +import java.awt.GridBagConstraints; +import java.util.function.Consumer; + +/** + * Options page for the playback device and voice volume. The volume previews live on the + * visible connection; a device change is handed to the microphone test's loopback. + */ +final class PlaybackPanel extends FormPanel { + + private final JComboBox outputCombo; + private final JSlider outputVol; + + PlaybackPanel(Settings settings, AudioIo io, VoiceOutput livePlayback, SoundNotifier sounds, + Consumer onOutputDeviceChanged) { + GridBagConstraints c = gbc(); + + outputCombo = AudioDevices.combo(io.outputDevices(), settings.outputDevice); + limitWidth(outputCombo, FIELD_WIDTH); + outputCombo.addActionListener(e -> onOutputDeviceChanged.accept(AudioDevices.selectedId(outputCombo))); + + outputVol = new JSlider(0, 200, (int) Math.round(settings.outputVolume * 100)); + JLabel volumeLabel = new JLabel(outputVol.getValue() + "%"); + outputVol.addChangeListener(e -> { + volumeLabel.setText(outputVol.getValue() + "%"); + if (livePlayback != null) livePlayback.setMasterVolume(outputVol.getValue() / 100.0); + }); + + JButton testSound = new JButton("Play Test Sound"); + testSound.addActionListener(e -> sounds.preview(SoundEvent.SPECIAL_SOUND_TEST)); + JPanel testRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); + testRow.add(testSound); + + int row = 0; + addSection(this, c, row++, "Device"); + addRow(this, c, row++, new JLabel("Playback device:"), outputCombo); + addSection(this, c, row++, "Volume"); + addRow(this, c, row++, new JLabel("Voice volume:"), sliderWithLabel(outputVol, volumeLabel)); + addWide(this, c, row++, testRow); + addFiller(this, c, row); + } + + /** Copies the form into {@code target}, without touching anything else. */ + void writeInto(Settings target) { + target.outputDevice = AudioDevices.selectedId(outputCombo); + target.outputVolume = outputVol.getValue() / 100.0; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeyCreateDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeyCreateDialog.java new file mode 100644 index 0000000..adeba13 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeyCreateDialog.java @@ -0,0 +1,168 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.net.ChannelNode; +import eu.lixko.ts3j.client.net.Group; +import eu.lixko.ts3j.client.net.ServerModel; +import eu.lixko.ts3j.client.net.TeamspeakConnection; + +import javax.swing.Box; +import javax.swing.ButtonGroup; +import javax.swing.DefaultListCellRenderer; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JTextField; +import javax.swing.SwingUtilities; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.FlowLayout; +import java.awt.GridBagConstraints; +import java.awt.Toolkit; +import java.awt.Window; +import java.awt.datatransfer.StringSelection; + +/** + * Creates privilege keys, as the official client's "Create Privilege Key" dialog: a server + * group, or a channel group in a chosen channel, and an optional description. Each key + * created is shown for copying, and the dialog stays open for the next one. + */ +final class PrivilegeKeyCreateDialog extends JDialog { + + private final TeamspeakConnection conn; + private final Runnable onCreated; + + private final JRadioButton serverGroup = new JRadioButton("Server Group", true); + private final JRadioButton channelGroup = new JRadioButton("Channel Group"); + private final JComboBox groupBox = new JComboBox<>(); + private final JComboBox channelBox = new JComboBox<>(); + private final JTextField descriptionField = new JTextField(28); + private final JTextField keyField = new JTextField(28); + private final JButton copy = new JButton("Copy", Icons.of("COPY")); + private final JButton create = new JButton("Create"); + + /** @param onCreated runs on the UI thread after each key is created */ + PrivilegeKeyCreateDialog(Window owner, TeamspeakConnection conn, GroupIcons groupIcons, Runnable onCreated) { + super(owner, "Create Privilege Key", ModalityType.APPLICATION_MODAL); + this.conn = conn; + this.onCreated = onCreated; + + ButtonGroup type = new ButtonGroup(); + type.add(serverGroup); + type.add(channelGroup); + serverGroup.addActionListener(e -> typeChanged()); + channelGroup.addActionListener(e -> typeChanged()); + JPanel typeRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); + typeRow.add(serverGroup); + typeRow.add(Box.createHorizontalStrut(UIScale.scale(12))); + typeRow.add(channelGroup); + + groupBox.setRenderer(new DefaultListCellRenderer() { + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, + boolean selected, boolean focused) { + super.getListCellRendererComponent(list, value, index, selected, focused); + if (value instanceof Group g) { + setText(g.name); + setIcon(groupIcons.iconOf(g)); + } + return this; + } + }); + groupBox.addActionListener(e -> updateCreate()); + ServerModel model = conn.getModel(); + channelBox.setRenderer(new DefaultListCellRenderer() { + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, + boolean selected, boolean focused) { + super.getListCellRendererComponent(list, value, index, selected, focused); + if (value instanceof ChannelNode c) setText(model.channelPath(c.id)); + return this; + } + }); + for (ChannelNode c : model.channelsInTreeOrder()) channelBox.addItem(c); + channelBox.setToolTipText("When creating a privilege key for a channel group, specify the channel here"); + descriptionField.setToolTipText("Optional description for this privilege key"); + descriptionField.addActionListener(e -> create()); + + keyField.setEditable(false); + copy.setEnabled(false); + copy.addActionListener(e -> Toolkit.getDefaultToolkit().getSystemClipboard() + .setContents(new StringSelection(keyField.getText()), null)); + JPanel keyRow = new JPanel(new BorderLayout(4, 0)); + keyRow.add(keyField, BorderLayout.CENTER); + keyRow.add(copy, BorderLayout.EAST); + + FormPanel form = new FormPanel(); + GridBagConstraints c = FormPanel.gbc(); + FormPanel.addRow(form, c, 0, new JLabel("Group Type:"), typeRow); + FormPanel.addRow(form, c, 1, new JLabel("Group:"), groupBox); + FormPanel.addRow(form, c, 2, new JLabel("Channel:"), channelBox); + FormPanel.addRow(form, c, 3, new JLabel("Description:"), descriptionField); + FormPanel.addRow(form, c, 4, new JLabel("Privilege Key:"), keyRow); + + create.addActionListener(e -> create()); + JButton close = new JButton("Close"); + close.addActionListener(e -> dispose()); + JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT)); + buttons.setBorder(new ScaledEmptyBorder(0, 8, 4, 8)); + buttons.add(create); + buttons.add(close); + getRootPane().setDefaultButton(create); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(form, BorderLayout.CENTER); + getContentPane().add(buttons, BorderLayout.SOUTH); + + typeChanged(); + Dialogs.closeOnEscape(this); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + pack(); + setResizable(false); + setLocationRelativeTo(owner); + } + + private boolean forChannelGroup() { + return channelGroup.isSelected(); + } + + private void typeChanged() { + groupBox.removeAllItems(); + for (Group g : conn.getModel().privilegeKeyGroups(forChannelGroup())) groupBox.addItem(g); + channelBox.setEnabled(forChannelGroup()); + updateCreate(); + } + + private void updateCreate() { + create.setEnabled(groupBox.getSelectedItem() != null + && (!forChannelGroup() || channelBox.getSelectedItem() != null)); + } + + private void create() { + if (!create.isEnabled()) return; + Group group = (Group) groupBox.getSelectedItem(); + ChannelNode channel = (ChannelNode) channelBox.getSelectedItem(); + create.setEnabled(false); + conn.addPrivilegeKey(forChannelGroup(), group.id, channel == null ? 0 : channel.id, + descriptionField.getText().trim(), (key, error) -> SwingUtilities.invokeLater(() -> { + if (!isDisplayable()) return; + updateCreate(); + if (error != null) { + JOptionPane.showMessageDialog(this, "Failed to add Privilege Key: " + error, + getTitle(), JOptionPane.ERROR_MESSAGE); + return; + } + keyField.setText(key); + keyField.selectAll(); + keyField.requestFocusInWindow(); + copy.setEnabled(true); + onCreated.run(); + })); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeysDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeysDialog.java new file mode 100644 index 0000000..5768d36 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeysDialog.java @@ -0,0 +1,355 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.net.Group; +import eu.lixko.ts3j.client.net.PrivilegeKey; +import eu.lixko.ts3j.client.net.ServerModel; +import eu.lixko.ts3j.client.net.TeamspeakConnection; + +import javax.swing.AbstractAction; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.KeyStroke; +import javax.swing.ListSelectionModel; +import javax.swing.SwingUtilities; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.TableRowSorter; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.Toolkit; +import java.awt.datatransfer.StringSelection; +import java.awt.event.ActionEvent; +import java.awt.event.KeyEvent; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +/** + * The server's privilege keys, as the official client's Permissions > Privilege Keys + * window: Create and Remove above the list, Reload below it. + * + *

    One per server tab and modeless, like the ban list; the tab closes it when the + * connection goes away. + */ +final class PrivilegeKeysDialog extends JDialog { + + private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + private enum Column { + KEY("Privilege Key", 320), + TYPE("Type", 110), + GROUP("Group", 140), + CHANNEL("Channel", 140), + CREATED("Created", 150), + DESCRIPTION("Description", 180); + + final String title; + final int width; + + Column(String title, int width) { + this.title = title; + this.width = width; + } + } + + private final TeamspeakConnection conn; + private final GroupIcons groupIcons; + + private final KeyTableModel tableModel = new KeyTableModel(); + private final JTable table = new JTable(tableModel); + private final JButton createButton = new JButton("Create", Icons.of("ADD")); + private final JButton removeButton = new JButton("Remove", Icons.of("DELETE")); + private final JLabel status = new JLabel(" "); + + private boolean loading; + + PrivilegeKeysDialog(Frame owner, TeamspeakConnection conn, GroupIcons groupIcons) { + super(owner, "Privilege Keys", false); + this.conn = conn; + this.groupIcons = groupIcons; + + JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(6))); + content.setBackground(Theme.windowBg()); + content.setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); + content.add(buildToolbar(), BorderLayout.NORTH); + content.add(buildTable(), BorderLayout.CENTER); + content.add(buildBottom(), BorderLayout.SOUTH); + setContentPane(content); + bindKeys(); + + serverNameChanged(); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + setPreferredSize(UIScale.scale(new Dimension(1040, 400))); + pack(); + setLocationRelativeTo(owner); + reload(); + } + + // ---- construction ---- + + private JPanel buildToolbar() { + createButton.setToolTipText("Create new privilege key
    (Ctrl+N)"); + removeButton.setToolTipText("Remove selected privilege keys
    (Delete)"); + createButton.addActionListener(e -> createKey()); + removeButton.addActionListener(e -> removeKeys()); + + JPanel bar = new JPanel(); + bar.setLayout(new BoxLayout(bar, BoxLayout.X_AXIS)); + bar.setOpaque(false); + bar.add(createButton); + bar.add(Box.createHorizontalStrut(UIScale.scale(6))); + bar.add(removeButton); + bar.add(Box.createHorizontalGlue()); + return bar; + } + + private JScrollPane buildTable() { + table.setFont(Theme.uiFont()); + table.setRowHeight(UIScale.scale(20)); + table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); + table.setFillsViewportHeight(true); + table.setRowSorter(new TableRowSorter<>(tableModel)); + table.getSelectionModel().addListSelectionListener(e -> updateButtons()); + table.setComponentPopupMenu(tablePopup()); + table.getTableHeader().setReorderingAllowed(true); + KeyCellRenderer renderer = new KeyCellRenderer(); + for (Column c : Column.values()) { + table.getColumnModel().getColumn(c.ordinal()).setPreferredWidth(UIScale.scale(c.width)); + table.getColumnModel().getColumn(c.ordinal()).setCellRenderer(renderer); + } + + JScrollPane scroll = new JScrollPane(table); + scroll.getViewport().setBackground(Theme.treeBg()); + return scroll; + } + + private JPanel buildBottom() { + JButton reload = new JButton("Reload", Icons.of("REFRESH")); + reload.setToolTipText("Reload privilege keys
    (F5)"); + reload.addActionListener(e -> reload()); + JButton close = new JButton("Close"); + close.addActionListener(e -> dispose()); + + JPanel row = new JPanel(new BorderLayout()); + row.setOpaque(false); + row.add(reload, BorderLayout.WEST); + row.add(close, BorderLayout.EAST); + + JPanel bottom = new JPanel(new BorderLayout(0, UIScale.scale(8))); + bottom.setOpaque(false); + bottom.add(status, BorderLayout.NORTH); + bottom.add(row, BorderLayout.SOUTH); + status.setForeground(Theme.chatEvent()); + return bottom; + } + + private JPopupMenu tablePopup() { + JPopupMenu menu = new JPopupMenu(); + menu.add(item("Create", "ADD", this::createKey)); + menu.add(item("Remove", "DELETE", this::removeKeys)); + menu.add(item("Copy", "COPY", this::copyKeys)); + menu.addSeparator(); + menu.add(item("Reload", "REFRESH", this::reload)); + return menu; + } + + private static JMenuItem item(String text, String icon, Runnable action) { + JMenuItem item = new JMenuItem(text, Icons.of(icon)); + item.addActionListener(e -> action.run()); + return item; + } + + private void bindKeys() { + bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control N"), this::createKey); + bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("F5"), this::reload); + bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control W"), this::dispose); + bind(table, JComponent.WHEN_FOCUSED, KeyStroke.getKeyStroke("control C"), this::copyKeys); + bind(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), + this::removeKeys); + Dialogs.closeOnEscape(this); + } + + private static void bind(JComponent target, int condition, KeyStroke key, Runnable action) { + String name = "ts3-privilegekeys-" + key; + target.getInputMap(condition).put(key, name); + target.getActionMap().put(name, new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + action.run(); + } + }); + } + + // ---- data ---- + + /** Follows the server's name, as the ban list's title does. */ + void serverNameChanged() { + String name = conn.getModel().getServerName(); + setTitle(name == null || name.isBlank() ? "Privilege Keys" : "Privilege Keys - " + name); + } + + void connectionLost() { + dispose(); + } + + private void reload() { + if (loading) return; + loading = true; + status.setText("Loading…"); + conn.requestPrivilegeKeys((keys, error) -> SwingUtilities.invokeLater(() -> { + loading = false; + if (!isDisplayable()) return; + if (error != null) { + tableModel.setKeys(List.of()); + status.setText("Failed to request Privilege Key list: " + error); + } else { + tableModel.setKeys(keys); + status.setText(keys.size() == 1 ? "1 privilege key" : keys.size() + " privilege keys"); + } + updateButtons(); + })); + } + + private List selectedKeys() { + List selected = new ArrayList<>(); + for (int row : table.getSelectedRows()) selected.add(tableModel.get(table.convertRowIndexToModel(row))); + return selected; + } + + private void updateButtons() { + ServerModel model = conn.getModel(); + createButton.setEnabled(model.permits("b_virtualserver_token_add")); + removeButton.setEnabled(!selectedKeys().isEmpty() && model.permits("b_virtualserver_token_delete")); + } + + // ---- actions ---- + + private void createKey() { + if (!createButton.isEnabled()) return; + new PrivilegeKeyCreateDialog(this, conn, groupIcons, this::reload).setVisible(true); + } + + private void removeKeys() { + if (!removeButton.isEnabled()) return; + int answer = JOptionPane.showConfirmDialog(this, "Do you really want to delete the selected privilege key(s)?", + "Delete Privilege Keys", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); + if (answer != JOptionPane.YES_OPTION) return; + List tokens = selectedKeys().stream().map(PrivilegeKey::token).collect(Collectors.toList()); + conn.deletePrivilegeKeys(tokens, error -> SwingUtilities.invokeLater(() -> { + if (!isDisplayable()) return; + if (error != null) { + JOptionPane.showMessageDialog(this, "Failed to delete Privilege Key: " + error, getTitle(), + JOptionPane.ERROR_MESSAGE); + } + reload(); + })); + } + + private void copyKeys() { + List keys = selectedKeys(); + if (keys.isEmpty()) return; + String text = keys.stream().map(PrivilegeKey::token).collect(Collectors.joining("\n")); + Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(text), null); + } + + // ---- table ---- + + private Group groupOf(PrivilegeKey key) { + ServerModel model = conn.getModel(); + return key.channelGroup() ? model.channelGroup(key.groupId()) : model.serverGroup(key.groupId()); + } + + private final class KeyTableModel extends AbstractTableModel { + + private List keys = List.of(); + + void setKeys(List keys) { + this.keys = new ArrayList<>(keys); + fireTableDataChanged(); + } + + PrivilegeKey get(int row) { + return keys.get(row); + } + + @Override + public int getRowCount() { + return keys.size(); + } + + @Override + public int getColumnCount() { + return Column.values().length; + } + + @Override + public String getColumnName(int column) { + return Column.values()[column].title; + } + + @Override + public Class getColumnClass(int column) { + return Column.values()[column] == Column.CREATED ? Long.class : String.class; + } + + @Override + public Object getValueAt(int row, int column) { + PrivilegeKey key = keys.get(row); + if (Column.values()[column] == Column.CREATED) return key.createdEpochSeconds(); + return text(key, Column.values()[column]); + } + + String text(PrivilegeKey key, Column column) { + switch (column) { + case KEY: + return key.token(); + case TYPE: + return key.channelGroup() ? "Channel Group" : "Server Group"; + case GROUP: + Group group = groupOf(key); + return group != null ? group.name : Integer.toString(key.groupId()); + case CHANNEL: + if (!key.channelGroup()) return ""; + String path = conn.getModel().channelPath(key.channelId()); + return path.isEmpty() ? Integer.toString(key.channelId()) : path; + case CREATED: + return key.createdEpochSeconds() <= 0 ? "" : DATE.format( + Instant.ofEpochSecond(key.createdEpochSeconds()).atZone(ZoneId.systemDefault())); + case DESCRIPTION: + return key.description(); + default: + return ""; + } + } + } + + /** Shows each column's text, with the group's icon beside its name. */ + private final class KeyCellRenderer extends DefaultTableCellRenderer { + @Override + public Component getTableCellRendererComponent(JTable t, Object value, boolean selected, + boolean focused, int row, int column) { + PrivilegeKey key = tableModel.get(t.convertRowIndexToModel(row)); + Column c = Column.values()[t.convertColumnIndexToModel(column)]; + super.getTableCellRendererComponent(t, tableModel.text(key, c), selected, focused, row, column); + setIcon(c == Column.GROUP ? groupIcons.iconOf(groupOf(key)) : null); + return this; + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ReasonDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ReasonDialog.java new file mode 100644 index 0000000..565adde --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ReasonDialog.java @@ -0,0 +1,99 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; + +import javax.swing.BoxLayout; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.event.AncestorEvent; +import javax.swing.event.AncestorListener; +import javax.swing.text.AttributeSet; +import javax.swing.text.BadLocationException; +import javax.swing.text.PlainDocument; +import java.awt.Component; +import java.awt.Dimension; + +/** + * Asks for the reason text that goes with a moderation action. The server caps + * such messages, so the field refuses anything longer. + */ +final class ReasonDialog { + + private ReasonDialog() { + } + + /** @return the reason (possibly empty), or {@code null} when the dialog was cancelled */ + static String prompt(Component owner, String title, String message, int maxLength) { + JTextField field = reasonField(maxLength); + focusWhenShown(field); + + JPanel panel = new JPanel(); + panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); + panel.add(label(message)); + panel.add(field); + + int result = JOptionPane.showConfirmDialog(owner, panel, title, + JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); + return result == JOptionPane.OK_OPTION ? field.getText().trim() : null; + } + + static JTextField reasonField(int maxLength) { + JTextField field = new JTextField(24); + field.setDocument(new LimitedDocument(maxLength)); + field.setAlignmentX(Component.LEFT_ALIGNMENT); + fixHeight(field); + return field; + } + + /** A left-aligned label with a little air below it, for use in a box layout. */ + static JLabel label(String text) { + JLabel label = new JLabel(text); + label.setAlignmentX(Component.LEFT_ALIGNMENT); + label.setBorder(new ScaledEmptyBorder(0, 0, 4, 0)); + return label; + } + + /** Keeps a component from stretching taller than it needs in a box layout. */ + static void fixHeight(Component c) { + c.setMaximumSize(new Dimension(Integer.MAX_VALUE, c.getPreferredSize().height)); + } + + /** Puts the caret in a field as soon as its dialog appears. */ + static void focusWhenShown(JComponent field) { + field.addAncestorListener(new AncestorListener() { + @Override + public void ancestorAdded(AncestorEvent event) { + field.requestFocusInWindow(); + } + + @Override + public void ancestorRemoved(AncestorEvent event) { + } + + @Override + public void ancestorMoved(AncestorEvent event) { + } + }); + } + + /** A document that silently drops anything past its length limit. */ + private static final class LimitedDocument extends PlainDocument { + + private final int limit; + + LimitedDocument(int limit) { + this.limit = limit; + } + + @Override + public void insertString(int offset, String text, AttributeSet attrs) throws BadLocationException { + if (text == null) return; + int room = limit - getLength(); + if (room <= 0) return; + super.insertString(offset, text.length() > room ? text.substring(0, room) : text, attrs); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/RecordingActions.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/RecordingActions.java new file mode 100644 index 0000000..e790326 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/RecordingActions.java @@ -0,0 +1,51 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.recording.VoiceRecorder; +import eu.lixko.ts3j.client.session.ServerSession; + +import javax.swing.JFileChooser; +import javax.swing.filechooser.FileNameExtensionFilter; +import java.awt.Component; +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** Starts recordings, into a file the user picks or, from a hotkey, the folder last used. */ +final class RecordingActions { + + private final Component owner; + private final Settings settings; + + RecordingActions(Component owner, Settings settings) { + this.owner = owner; + this.settings = settings; + } + + /** Asks where to save, then starts recording. */ + void choose(ServerSession session, boolean multitrack) { + if (!session.isConnected() || session.isRecording()) return; + Path dir = settings.recordingFolder(); + if (!Files.isDirectory(dir)) dir = Paths.get(System.getProperty("user.home", ".")); + JFileChooser chooser = new JFileChooser(dir.toFile()); + chooser.setDialogTitle(multitrack ? "Start Multitrack Recording" : "Start Recording"); + chooser.setFileFilter(new FileNameExtensionFilter("Ogg Opus (*.ogg)", "ogg")); + chooser.setSelectedFile(session.recordingFile(dir).toFile()); + if (chooser.showSaveDialog(owner) != JFileChooser.APPROVE_OPTION) return; + File file = chooser.getSelectedFile(); + if (!file.getName().toLowerCase().endsWith(".ogg")) file = new File(file.getParentFile(), file.getName() + ".ogg"); + settings.recordingDir = file.getParentFile().getAbsolutePath(); + settings.save(); + session.startRecording(mode(multitrack), file.toPath()); + } + + void startNow(ServerSession session, boolean multitrack) { + if (!session.isConnected() || session.isRecording()) return; + session.startRecording(mode(multitrack), session.recordingFile(settings.recordingFolder())); + } + + private static VoiceRecorder.Mode mode(boolean multitrack) { + return multitrack ? VoiceRecorder.Mode.MULTITRACK : VoiceRecorder.Mode.MIXED; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/RowColorCombo.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/RowColorCombo.java new file mode 100644 index 0000000..81b59fb --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/RowColorCombo.java @@ -0,0 +1,123 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.config.ClientRowColors; + +import javax.swing.DefaultListCellRenderer; +import javax.swing.Icon; +import javax.swing.JColorChooser; +import javax.swing.JComboBox; +import javax.swing.JList; +import javax.swing.UIManager; +import java.awt.Color; +import java.awt.Component; +import java.awt.Graphics; + +/** + * Picks a row background: none, one of {@link ClientRowColors#PRESETS}, or a custom + * colour from a colour chooser. The value is ARGB, 0 for none. + */ +final class RowColorCombo extends JComboBox { + + record Option(String name, int argb, boolean custom) { + } + + private static final Option NONE = new Option("None", 0, false); + + /** The last item, holding whichever custom colour was chosen. */ + private Option custom; + private Option previous; + private boolean choosing; + + RowColorCombo(int argb) { + addItem(NONE); + for (ClientRowColors.Preset p : ClientRowColors.PRESETS) addItem(new Option(p.name(), p.argb(), false)); + boolean isCustom = argb != 0 && ClientRowColors.presetOf(argb) == null; + custom = new Option("Custom…", isCustom ? argb : 0, true); + addItem(custom); + setValue(argb); + previous = (Option) getSelectedItem(); + + setMaximumRowCount(getItemCount()); + setRenderer(new DefaultListCellRenderer() { + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, + boolean selected, boolean focus) { + super.getListCellRendererComponent(list, value, index, selected, focus); + Option o = (Option) value; + setText(o == null ? "" : o.name()); + setIcon(o == null ? null : new Swatch(o.argb())); + return this; + } + }); + addActionListener(e -> onSelected()); + } + + int value() { + Option o = (Option) getSelectedItem(); + return o == null ? 0 : o.argb(); + } + + private void setValue(int argb) { + for (int i = 0; i < getItemCount(); i++) { + Option o = getItemAt(i); + if (o.argb() == argb && (argb != 0 || o == NONE)) { + setSelectedIndex(i); + return; + } + } + setSelectedItem(NONE); + } + + private void onSelected() { + Option o = (Option) getSelectedItem(); + if (o == null || choosing) return; + if (!o.custom()) { + previous = o; + return; + } + choosing = true; + try { + int start = custom.argb() != 0 ? custom.argb() : previous.argb() != 0 ? previous.argb() : 0x59808080; + Color picked = JColorChooser.showDialog(this, "Row Colour", new Color(start, true), true); + if (picked == null || picked.getRGB() == 0) { + setSelectedItem(previous); + return; + } + Option chosen = new Option("Custom…", picked.getRGB(), true); + removeItem(custom); + custom = chosen; + addItem(custom); + setSelectedItem(custom); + previous = custom; + } finally { + choosing = false; + } + } + + /** A small square of the colour over the tree's background, as a row shows it. */ + private record Swatch(int argb) implements Icon { + @Override + public void paintIcon(Component c, Graphics g, int x, int y) { + int size = getIconWidth(); + g.setColor(UIManager.getColor("Tree.background")); + g.fillRect(x, y, size, size); + if (argb != 0) { + g.setColor(new Color(argb, true)); + g.fillRect(x, y, size, size); + } + g.setColor(UIManager.getColor("Component.borderColor")); + g.drawRect(x, y, size - 1, size - 1); + } + + @Override + public int getIconWidth() { + return UIScale.scale(14); + } + + @Override + public int getIconHeight() { + return getIconWidth(); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerGroupsDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerGroupsDialog.java new file mode 100644 index 0000000..a870050 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerGroupsDialog.java @@ -0,0 +1,107 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.net.ClientEntry; +import eu.lixko.ts3j.client.net.Group; +import eu.lixko.ts3j.client.net.GroupChoice; +import eu.lixko.ts3j.client.net.TeamspeakConnection; + +import javax.swing.BoxLayout; +import javax.swing.GrayFilter; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.SwingConstants; +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.util.HashMap; +import java.util.Map; + +/** + * Every regular server group on the server, as a scrollable checkbox list. Groups + * the local client has no power to (un)assign are shown too, so the client's full + * membership is visible, but greyed out and disabled. + */ +final class ServerGroupsDialog extends JDialog { + + private final TeamspeakConnection conn; + private final GroupIcons groupIcons; + private final int clientId; + private final ServerTreePanel.Actions actions; + + private final JPanel list = new JPanel(); + private final JLabel header = new JLabel(); + /** Cached grayscale icons, keyed by the source icon's identity. */ + private final Map grayscale = new HashMap<>(); + + ServerGroupsDialog(MainFrame owner, TeamspeakConnection conn, GroupIcons groupIcons, + ClientEntry client, ServerTreePanel.Actions actions) { + super(owner, "Server Groups", true); + this.conn = conn; + this.groupIcons = groupIcons; + this.clientId = client.id; + this.actions = actions; + + list.setLayout(new BoxLayout(list, BoxLayout.Y_AXIS)); + JScrollPane scroll = new JScrollPane(list); + scroll.setPreferredSize(UIScale.scale(new Dimension(280, 360))); + scroll.getVerticalScrollBar().setUnitIncrement(16); + + header.setBorder(new ScaledEmptyBorder(8, 10, 4, 10)); + header.setHorizontalAlignment(SwingConstants.LEFT); + + JButton close = new JButton("Close"); + close.addActionListener(a -> dispose()); + JPanel buttons = new JPanel(); + buttons.add(close); + getRootPane().setDefaultButton(close); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(header, BorderLayout.NORTH); + getContentPane().add(scroll, BorderLayout.CENTER); + getContentPane().add(buttons, BorderLayout.SOUTH); + + Dialogs.closeOnEscape(this); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + refresh(); + pack(); + setLocationRelativeTo(owner); + } + + /** Rebuilds the list from the current model state; closes the dialog if the client left. */ + void refresh() { + ClientEntry client = conn.getModel().getClient(clientId); + if (client == null) { + dispose(); + return; + } + header.setText(client.nickname); + + list.removeAll(); + for (GroupChoice choice : conn.getModel().serverGroupChoices(client)) { + Group g = choice.group(); + ImageIcon icon = groupIcons.iconOf(g); + JCheckBox box = new JCheckBox(g.name, choice.allowed() ? icon : grayscale(icon)); + box.setSelected(choice.assigned()); + box.setEnabled(choice.allowed()); + box.setAlignmentX(0f); + if (choice.allowed()) { + box.addActionListener(a -> actions.setClientServerGroup(client, g, box.isSelected())); + } + list.add(box); + } + list.revalidate(); + list.repaint(); + } + + private ImageIcon grayscale(ImageIcon icon) { + if (icon == null) return null; + return grayscale.computeIfAbsent(icon, + i -> new ImageIcon(GrayFilter.createDisabledImage(i.getImage()))); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerLogDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerLogDialog.java new file mode 100644 index 0000000..26ef921 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerLogDialog.java @@ -0,0 +1,364 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.config.ServerLogSettings; +import eu.lixko.ts3j.client.config.ServerLogSettings.Highlight; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.net.ServerLogEntry; +import eu.lixko.ts3j.client.net.ServerLogEntry.Level; +import eu.lixko.ts3j.client.net.ServerLogPage; +import eu.lixko.ts3j.client.net.TeamspeakConnection; +import eu.lixko.ts3j.client.text.TextQuery; + +import javax.swing.AbstractAction; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JEditorPane; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextPane; +import javax.swing.KeyStroke; +import javax.swing.SwingUtilities; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultStyledDocument; +import javax.swing.text.SimpleAttributeSet; +import javax.swing.text.StyleConstants; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Frame; +import java.awt.Rectangle; +import java.awt.event.ActionEvent; +import java.awt.event.KeyEvent; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +/** + * The virtual server's log, as the official client's Tools > Server Log window: the newest + * hundred lines, more on Show Older, narrowed down by level and exclude terms and coloured + * by keyword. Find (with "show only matches") stands in for TS3's separate search and + * include-filter fields. + * + *

    One per server tab and modeless, like the ban list; the tab closes it when the + * connection goes away. + */ +final class ServerLogDialog extends JDialog { + + private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + private static final String TITLE = "Server Log"; + private static final int LEVEL_WIDTH = "Critical".length(); + + private final TeamspeakConnection conn; + private final Settings settings; + private final ServerLogSettings view; + + private final JTextPane log = new JTextPane() { + /** Long lines scroll sideways rather than wrap, keeping the columns lined up. */ + @Override + public boolean getScrollableTracksViewportWidth() { + return getParent() == null || getUI().getPreferredSize(this).width <= getParent().getWidth(); + } + }; + private final DefaultStyledDocument doc = new DefaultStyledDocument(); + private final ChatSearch search = new ChatSearch(new ChatSearch.Host() { + @Override + public JEditorPane selectedLog() { + return log; + } + + @Override + public void showMatching(TextQuery filter) { + onlyMatching = filter; + render(false); + } + }, "Show only matching lines"); + private final Map levelBoxes = new EnumMap<>(Level.class); + private final JComboBox timeZone = new JComboBox<>(new String[]{"UTC time", "Local time"}); + private final JButton olderButton = new JButton("Show Older"); + /** Loading, failures and an empty log; hidden otherwise. */ + private final JLabel status = new JLabel(); + + /** Everything read so far, oldest first. */ + private final List entries = new ArrayList<>(); + private long olderFrom; + private TextQuery onlyMatching; + private boolean loading; + + ServerLogDialog(Frame owner, TeamspeakConnection conn, Settings settings) { + super(owner, TITLE, false); + this.conn = conn; + this.settings = settings; + this.view = settings.serverLog; + + JPanel center = new JPanel(new BorderLayout()); + center.setOpaque(false); + center.add(buildLog(), BorderLayout.CENTER); + center.add(search.bar(), BorderLayout.SOUTH); + + JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(6))); + content.setBackground(Theme.windowBg()); + content.setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); + content.add(buildToolbar(), BorderLayout.NORTH); + content.add(center, BorderLayout.CENTER); + content.add(buildBottom(), BorderLayout.SOUTH); + setContentPane(content); + bindKeys(); + + serverNameChanged(); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + setPreferredSize(UIScale.scale(new Dimension(900, 520))); + pack(); + setLocationRelativeTo(owner); + search.open(); + reload(); + } + + // ---- construction ---- + + private JPanel buildToolbar() { + JPanel bar = new JPanel(); + bar.setLayout(new BoxLayout(bar, BoxLayout.X_AXIS)); + bar.setOpaque(false); + String[] labels = {"Critical", "Errors", "Warnings", "Info"}; + int[] mnemonics = {KeyEvent.VK_C, KeyEvent.VK_E, KeyEvent.VK_W, KeyEvent.VK_I}; + for (int i = 0; i < ServerLogSettings.SHOWN_LEVELS.size(); i++) { + Level level = ServerLogSettings.SHOWN_LEVELS.get(i); + JCheckBox box = new JCheckBox(labels[i], view.levels.contains(level)); + box.setMnemonic(mnemonics[i]); + box.setOpaque(false); + box.addActionListener(e -> { + if (box.isSelected()) view.levels.add(level); + else view.levels.remove(level); + settingsChanged(); + }); + levelBoxes.put(level, box); + bar.add(box); + bar.add(Box.createHorizontalStrut(UIScale.scale(6))); + } + bar.add(Box.createHorizontalStrut(UIScale.scale(12))); + + JButton highlighting = new JButton("Highlighting…"); + highlighting.setMnemonic(KeyEvent.VK_H); + highlighting.addActionListener(e -> { + if (ServerLogHighlightDialog.edit(this, view.highlights)) settingsChanged(); + }); + JButton exclude = new JButton("Exclude Filter…"); + exclude.setMnemonic(KeyEvent.VK_X); + exclude.addActionListener(e -> { + if (ServerLogExcludeDialog.edit(this, view.excludes)) settingsChanged(); + }); + bar.add(highlighting); + bar.add(Box.createHorizontalStrut(UIScale.scale(6))); + bar.add(exclude); + bar.add(Box.createHorizontalGlue()); + + timeZone.setSelectedIndex(view.localTime ? 1 : 0); + timeZone.setMaximumSize(timeZone.getPreferredSize()); + timeZone.addActionListener(e -> { + view.localTime = timeZone.getSelectedIndex() == 1; + settingsChanged(); + }); + bar.add(timeZone); + return bar; + } + + private JScrollPane buildLog() { + log.setEditable(false); + log.setDocument(doc); + log.setFont(new Font(Font.MONOSPACED, Font.PLAIN, UIScale.scale(12))); + log.setBackground(Theme.chatBg()); + log.setForeground(Theme.chatText()); + log.setBorder(new ScaledEmptyBorder(4, 6, 4, 6)); + JScrollPane scroll = new JScrollPane(log); + scroll.getViewport().setBackground(Theme.chatBg()); + return scroll; + } + + private JPanel buildBottom() { + JButton reload = new JButton("Reload", Icons.of("REFRESH")); + reload.setMnemonic(KeyEvent.VK_R); + reload.setToolTipText("Reload the newest lines
    (F5)"); + reload.addActionListener(e -> reload()); + olderButton.setMnemonic(KeyEvent.VK_O); + olderButton.setEnabled(false); + olderButton.addActionListener(e -> loadOlder()); + JButton close = new JButton("Close"); + close.addActionListener(e -> dispose()); + + JPanel left = new JPanel(); + left.setLayout(new BoxLayout(left, BoxLayout.X_AXIS)); + left.setOpaque(false); + left.add(reload); + left.add(Box.createHorizontalStrut(UIScale.scale(6))); + left.add(olderButton); + + JPanel row = new JPanel(new BorderLayout()); + row.setOpaque(false); + row.add(left, BorderLayout.WEST); + row.add(close, BorderLayout.EAST); + + JPanel bottom = new JPanel(new BorderLayout(0, UIScale.scale(8))); + bottom.setOpaque(false); + bottom.add(status, BorderLayout.NORTH); + bottom.add(row, BorderLayout.SOUTH); + status.setVisible(false); + return bottom; + } + + private void bindKeys() { + bind(KeyStroke.getKeyStroke("F5"), this::reload); + bind(KeyStroke.getKeyStroke("control W"), this::dispose); + bind(KeyStroke.getKeyStroke("control F"), search::open); + Dialogs.closeOnEscape(this); + } + + private void bind(KeyStroke key, Runnable action) { + String name = "ts3-serverlog-" + key; + getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(key, name); + getRootPane().getActionMap().put(name, new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + action.run(); + } + }); + } + + // ---- data ---- + + void serverNameChanged() { + String name = conn.getModel().getServerName(); + setTitle(name == null || name.isBlank() ? TITLE : TITLE + " - " + name); + } + + void connectionLost() { + dispose(); + } + + private void reload() { + request(0); + } + + private void loadOlder() { + if (olderFrom > 0) request(olderFrom); + } + + /** Reads the newest page ({@code from} 0, replacing what is shown) or the one ending at {@code from}. */ + private void request(long from) { + if (loading) return; + loading = true; + olderButton.setEnabled(false); + showStatus("Loading…", Theme.chatEvent()); + conn.requestServerLog(from, (page, error) -> SwingUtilities.invokeLater(() -> { + loading = false; + if (!isDisplayable()) return; + if (error != null) { + failed(error); + olderButton.setEnabled(olderFrom > 0); + return; + } + received(page, from > 0); + })); + } + + private void received(ServerLogPage page, boolean older) { + if (!older) entries.clear(); + entries.addAll(0, page.entries()); + olderFrom = page.olderFrom(); + olderButton.setEnabled(page.hasOlder()); + render(!older); + if (older) log.setCaretPosition(0); + } + + private void failed(String error) { + showStatus(error.toLowerCase(Locale.ROOT).contains("insufficient") + ? "Insufficient permissions to view Server Log" + : "Error requesting server log: " + error, + Theme.isDark() ? new Color(0xFF6B6B) : new Color(0xC00000)); + } + + private void settingsChanged() { + settings.save(); + render(false); + } + + // ---- rendering ---- + + /** Lays the log out again; {@code toEnd} scrolls to the newest line, otherwise the view stays put. */ + private void render(boolean toEnd) { + int channelWidth = 0; + for (ServerLogEntry e : entries) channelWidth = Math.max(channelWidth, e.channel().length()); + + int scrollY = log.getVisibleRect().y; + try { + doc.remove(0, doc.getLength()); + for (ServerLogEntry e : entries) { + String line = format(e, channelWidth); + if (!view.shows(e.level(), line)) continue; + if (onlyMatching != null && !onlyMatching.matches(line)) continue; + doc.insertString(doc.getLength(), line + "\n", style(view.highlightFor(line))); + } + } catch (BadLocationException ignored) { + // appending at the end never fails + } + + showStatus(entries.isEmpty() ? "No log entries available" : null, Theme.chatEvent()); + + if (toEnd) { + log.setCaretPosition(doc.getLength()); + } else { + SwingUtilities.invokeLater(() -> log.scrollRectToVisible( + new Rectangle(0, scrollY, 1, log.getVisibleRect().height))); + } + } + + /** Shows {@code text} under the log, or hides the label for {@code null}. */ + private void showStatus(String text, Color color) { + status.setText(text); + status.setForeground(color); + status.setVisible(text != null); + } + + private String format(ServerLogEntry e, int channelWidth) { + String time = ""; + if (e.timestamp() != null) { + LocalDateTime t = view.localTime + ? e.timestamp().atOffset(ZoneOffset.UTC).atZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime() + : e.timestamp(); + time = TIME.format(t); + } + return pad(time, 19) + " " + pad(e.channel(), channelWidth) + " " + + pad(levelName(e.level()), LEVEL_WIDTH) + " " + e.message(); + } + + private static String levelName(Level level) { + String name = level.name(); + return name.charAt(0) + name.substring(1).toLowerCase(Locale.ROOT); + } + + private static String pad(String s, int width) { + return s.length() >= width ? s : s + " ".repeat(width - s.length()); + } + + private static SimpleAttributeSet style(Highlight h) { + SimpleAttributeSet a = new SimpleAttributeSet(); + if (h == null) return a; + if (h.foreground() != null) StyleConstants.setForeground(a, new Color(h.foreground())); + if (h.background() != null) StyleConstants.setBackground(a, new Color(h.background())); + return a; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerLogExcludeDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerLogExcludeDialog.java new file mode 100644 index 0000000..96e1d4b --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerLogExcludeDialog.java @@ -0,0 +1,27 @@ +package eu.lixko.ts3j.client.ui; + +import java.awt.Window; +import java.util.List; + +/** The Server Log's exclude filter: terms whose lines are left out. */ +final class ServerLogExcludeDialog extends ListEditorDialog { + + private ServerLogExcludeDialog(Window owner, List terms) { + super(owner, "Exclude Filter", "Exclude lines containing:", "Term:", terms, false); + } + + /** @return whether the terms were changed */ + static boolean edit(Window owner, List terms) { + return new ServerLogExcludeDialog(owner, terms).showAndApply(terms); + } + + @Override + protected String item(String text, String old) { + return text; + } + + @Override + protected String text(String item) { + return item; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerLogHighlightDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerLogHighlightDialog.java new file mode 100644 index 0000000..8cf2c34 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerLogHighlightDialog.java @@ -0,0 +1,145 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.config.ServerLogSettings.Highlight; + +import javax.swing.DefaultListCellRenderer; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JColorChooser; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JPanel; +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Component; +import java.awt.FlowLayout; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.Window; +import java.util.List; +import java.util.function.Function; + +/** The Server Log's highlighting: keywords and the colours their lines are drawn in, first match first. */ +final class ServerLogHighlightDialog extends ListEditorDialog { + + private JButton foreground; + private JButton background; + private JButton clearForeground; + private JButton clearBackground; + + private ServerLogHighlightDialog(Window owner, List highlights) { + super(owner, "Highlighting", null, "Keyword:", highlights, true); + list.setCellRenderer(new DefaultListCellRenderer() { + @Override + public Component getListCellRendererComponent(JList l, Object value, int index, + boolean selected, boolean focused) { + Highlight h = (Highlight) value; + super.getListCellRendererComponent(l, h.keyword(), index, selected, focused); + if (!selected) { + if (h.foreground() != null) setForeground(new Color(h.foreground())); + if (h.background() != null) setBackground(new Color(h.background())); + } + return this; + } + }); + } + + /** @return whether the highlights were changed */ + static boolean edit(Window owner, List highlights) { + return new ServerLogHighlightDialog(owner, highlights).showAndApply(highlights); + } + + @Override + protected Highlight item(String text, Highlight old) { + return old == null ? new Highlight(text, null, null) : new Highlight(text, old.foreground(), old.background()); + } + + @Override + protected String text(Highlight item) { + return item.keyword(); + } + + @Override + protected JComponent extraControls() { + foreground = new JButton("Text Color…"); + foreground.addActionListener(e -> choose("Text Color", Highlight::foreground, true)); + clearForeground = new JButton("None"); + clearForeground.addActionListener(e -> update(null, true)); + background = new JButton("Background…"); + background.addActionListener(e -> choose("Background", Highlight::background, false)); + clearBackground = new JButton("None"); + clearBackground.addActionListener(e -> update(null, false)); + + JPanel row = new JPanel(new FlowLayout(FlowLayout.LEFT, UIScale.scale(4), 0)); + row.setOpaque(false); + row.add(foreground); + row.add(clearForeground); + row.add(new JLabel(" ")); + row.add(background); + row.add(clearBackground); + return row; + } + + @Override + protected void selectionChanged() { + Highlight h = list.getSelectedValue(); + foreground.setEnabled(h != null); + background.setEnabled(h != null); + clearForeground.setEnabled(h != null && h.foreground() != null); + clearBackground.setEnabled(h != null && h.background() != null); + foreground.setIcon(new Swatch(h == null ? null : h.foreground())); + background.setIcon(new Swatch(h == null ? null : h.background())); + } + + private void choose(String title, Function current, boolean isForeground) { + Highlight h = list.getSelectedValue(); + if (h == null) return; + Integer rgb = current.apply(h); + Color chosen = JColorChooser.showDialog(this, title, rgb == null ? Theme.chatText() : new Color(rgb)); + if (chosen != null) update(chosen.getRGB() & 0xFFFFFF, isForeground); + } + + private void update(Integer rgb, boolean isForeground) { + int i = list.getSelectedIndex(); + if (i < 0) return; + Highlight h = model.get(i); + model.set(i, isForeground ? new Highlight(h.keyword(), rgb, h.background()) + : new Highlight(h.keyword(), h.foreground(), rgb)); + selectionChanged(); + } + + /** A colour sample; struck through when there is none. */ + private record Swatch(Integer rgb) implements Icon { + @Override + public void paintIcon(Component c, Graphics g, int x, int y) { + Graphics2D g2 = (Graphics2D) g.create(); + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + int w = getIconWidth() - 1; + int h = getIconHeight() - 1; + if (rgb != null) { + g2.setColor(new Color(rgb)); + g2.fillRect(x, y, w, h); + } + g2.setColor(Theme.border()); + g2.drawRect(x, y, w, h); + if (rgb == null) { + g2.setStroke(new BasicStroke(UIScale.scale(1f))); + g2.drawLine(x, y + h, x + w, y); + } + g2.dispose(); + } + + @Override + public int getIconWidth() { + return UIScale.scale(14); + } + + @Override + public int getIconHeight() { + return UIScale.scale(14); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerMenu.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerMenu.java new file mode 100644 index 0000000..31dfce6 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerMenu.java @@ -0,0 +1,28 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.net.ChannelSettings; + +import javax.swing.JMenuItem; +import javax.swing.JPopupMenu; + +/** + * The context menu for the server itself — the tree's root row. + */ +final class ServerMenu { + + private ServerMenu() { + } + + static JPopupMenu build(ServerTreePanel.Actions actions) { + JPopupMenu menu = new JPopupMenu(); + JMenuItem create = new JMenuItem("Create Channel", Icons.of("CHANNEL_CREATE")); + create.addActionListener(a -> actions.createChannel(null, ChannelSettings.Type.PERMANENT)); + menu.add(create); + JMenuItem spacer = new JMenuItem("Create Spacer", + Icons.ofAny("CHANNEL_CREATE_SPACER", "CHANNEL_CREATE")); + spacer.setToolTipText("Create a new spacer"); + spacer.addActionListener(a -> actions.createSpacer()); + menu.add(spacer); + return menu; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java new file mode 100644 index 0000000..567dda1 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java @@ -0,0 +1,371 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.audio.AudioBackend; +import eu.lixko.ts3j.client.config.BanReasonPresets; +import eu.lixko.ts3j.client.config.IdentityStore; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.contacts.ContactStore; +import eu.lixko.ts3j.client.net.ChannelNode; +import eu.lixko.ts3j.client.net.ClientEntry; +import eu.lixko.ts3j.client.net.ConnectionListener.ChatScope; +import eu.lixko.ts3j.client.net.OfflineMessage; +import eu.lixko.ts3j.client.net.PictureDownloads; +import eu.lixko.ts3j.client.net.TeamspeakConnection; +import eu.lixko.ts3j.client.net.avatar.Avatar; +import eu.lixko.ts3j.client.session.ServerSession; +import eu.lixko.ts3j.client.sound.SoundNotifier; +import eu.lixko.ts3j.client.text.TsLink; + +import javax.swing.JComponent; +import javax.swing.JOptionPane; +import javax.swing.JSplitPane; +import javax.swing.SwingUtilities; +import java.awt.Component; +import java.awt.Window; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; + +/** + * One server connection and the views bound to it (tree, info and chat). The + * client keeps several of these side by side; {@link MainFrame} shows one at a + * time and owns the toolbar, menus and status bar that act on it. + * + *

    The connection and the client's own state on it live in the {@link ServerSession}; + * ServerTab owns the panels, tree context-menu actions and selection live in + * {@link ServerTabTreeActions}, and session callbacks in {@link ServerTabConnectionEvents}. + */ +final class ServerTab { + + private final MainFrame host; + private final Settings settings; + + private final ServerSession session; + private final ContactStore contacts; + private final TeamspeakConnection conn; + private final GroupIcons groupIcons; + private final ServerTabTreeActions treeActions; + private final ServerTreePanel treePanel; + private final ChatPanel chatPanel; + private final InfoPanel infoPanel; + private final AvatarActions avatar; + private final JComponent component; + private JSplitPane leftColumn; + private int normalDividerSize; + private int savedDividerLocation = -1; + /** Whether the saved divider share has been applied; before that, layout is not the user's doing. */ + private boolean splitRestored; + + /** The one open ban list window for this server, if any. */ + private BanListDialog banList; + private PrivilegeKeysDialog privilegeKeys; + private ComplaintsDialog complaints; + private ServerLogDialog serverLog; + private OfflineMessagesDialog offlineMessages; + /** The unread count last reported, to tell new mail from messages being read. */ + private int unreadMessages; + + ServerTab(MainFrame host, Settings settings, IdentityStore identities, AudioBackend audio, + SoundNotifier sounds, ContactStore contacts, PictureDownloads pictures) { + this.host = host; + this.settings = settings; + this.contacts = contacts; + this.infoPanel = new InfoPanel(settings, pictures, host.infoZoom()); + + // ServerTabConnectionEvents must exist before the session (which needs a listener + // up front), and the session must exist before the tree/chat panels and the other + // tab helpers that read from it — so wiring finishes with an explicit attach() once + // everything is built. Nothing fires callbacks before then. + ServerTabConnectionEvents events = new ServerTabConnectionEvents(host, this, settings); + this.session = new ServerSession(settings, identities, audio, sounds, contacts, events); + this.conn = session.connection(); + this.groupIcons = new GroupIcons(conn.getIcons()); + this.chatPanel = new ChatPanel(host.chatZoom(), settings, pictures, conn::serverUniqueId); + this.treeActions = new ServerTabTreeActions(host, this, conn, chatPanel, infoPanel, groupIcons); + this.treePanel = new ServerTreePanel(conn.getModel(), groupIcons, contacts, settings, treeActions); + treeActions.attach(treePanel); + events.attach(session, treePanel, chatPanel, treeActions); + + chatPanel.setSendHandler(this::onSendChat); + chatPanel.setLinkHandler(new ChatPanel.LinkHandler() { + @Override + public void onClientLink(TsLink.Ref ref, Component source, int x, int y) { + treeActions.handleClientLink(ref, source, x, y); + } + + @Override + public void onChannelLink(TsLink.Ref ref, Component source, int x, int y) { + treeActions.handleChannelLink(ref, source, x, y); + } + + @Override + public void onOfflineMessagesLink() { + showOfflineMessages(); + } + }); + chatPanel.setAttachmentHandler(new ChatAttachmentActions(host, session, chatPanel, pictures, ServerTab::scope)); + chatPanel.setSharingAvailable(host.canShareFiles()); + chatPanel.setInputEnabled(false); + + infoPanel.setDescriptionHandler(new InfoPanel.DescriptionHandler() { + @Override + public void showInfoTab(String html, Runnable onClose) { + chatPanel.openDescriptionTab("info", Icons.channelClientPair(), "", html, onClose); + } + + @Override + public void closeInfoTab() { + chatPanel.closeNoteTab("info"); + } + + @Override + public void setPanelHidden(boolean hidden) { + ServerTab.this.setInfoPanelHidden(hidden); + } + }); + + this.avatar = new AvatarActions(host, conn); + infoPanel.setAvatarHandler(new InfoPanel.AvatarHandler() { + @Override + public void steal(Avatar other) { + avatar.steal(other); + } + + @Override + public boolean canSet() { + return session.canSetAvatar(); + } + + @Override + public boolean canDeleteOthers() { + return session.canDeleteOtherAvatars(); + } + + @Override + public void deleteOf(ClientEntry client) { + avatar.deleteOf(client); + } + + @Override + public void set() { + avatar.choose(); + } + + @Override + public void delete() { + avatar.delete(); + } + }); + + leftColumn = new JSplitPane(JSplitPane.VERTICAL_SPLIT, treePanel, infoPanel); + leftColumn.setResizeWeight(0.68); + leftColumn.setContinuousLayout(true); + normalDividerSize = leftColumn.getDividerSize(); + // The info panel keeps the height the user gave it, in this tab and the next session. + leftColumn.addComponentListener(new ComponentAdapter() { + @Override + public void componentResized(ComponentEvent e) { + if (splitRestored) return; + splitRestored = true; + leftColumn.setDividerLocation(settings.infoSplitRatio); + } + }); + leftColumn.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, e -> rememberSplit()); + + JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftColumn, chatPanel); + split.setResizeWeight(0.55); + split.setDividerLocation(400); + split.setContinuousLayout(true); + this.component = split; + } + + // ---- accessors ---- + + JComponent component() { + return component; + } + + ServerSession session() { + return session; + } + + TeamspeakConnection connection() { + return conn; + } + + ChatPanel chat() { + return chatPanel; + } + + /** Opens the server's ban list, or brings the already open one forward. */ + void showBanList(BanReasonPresets presets) { + if (!session.isConnected()) return; + if (banList == null || !banList.isDisplayable()) { + banList = new BanListDialog(host, conn, settings, presets); + } + banList.setVisible(true); + banList.toFront(); + } + + /** Opens the server's complaints, or brings the already open window forward. */ + void showComplaints() { + if (!session.isConnected()) return; + if (complaints == null || !complaints.isDisplayable()) { + complaints = new ComplaintsDialog(host, conn, treeActions::banClient); + } + complaints.setVisible(true); + complaints.toFront(); + } + + /** Opens the server's log, or brings the already open window forward. */ + void showServerLog() { + if (!session.isConnected()) return; + if (serverLog == null || !serverLog.isDisplayable()) { + serverLog = new ServerLogDialog(host, conn, settings); + } + serverLog.setVisible(true); + serverLog.toFront(); + } + + /** Opens our offline message inbox, or brings the already open window forward. */ + void showOfflineMessages() { + if (!session.isConnected()) return; + if (offlineMessages == null || !offlineMessages.isDisplayable()) { + offlineMessages = new OfflineMessagesDialog(host, conn, new OfflineMessagesDialog.Composer() { + @Override + public void compose() { + composeOfflineMessage(); + } + + @Override + public void reply(OfflineMessage message, String body) { + if (!session.isConnected()) return; + OfflineMessageComposeDialog.reply(offlineMessages, conn, contacts, message, body).setVisible(true); + } + }); + } + offlineMessages.setVisible(true); + offlineMessages.toFront(); + } + + void composeOfflineMessage() { + if (!session.isConnected() || !conn.canSendOfflineMessages()) return; + Window owner = offlineMessages != null && offlineMessages.isShowing() ? offlineMessages : host; + OfflineMessageComposeDialog.compose(owner, conn, contacts).setVisible(true); + } + + /** New mail refreshes an open inbox; a message being read does not need to. */ + void unreadMessagesChanged(int unread) { + boolean newMail = unread > unreadMessages; + unreadMessages = unread; + if (newMail && offlineMessages != null && offlineMessages.isDisplayable()) offlineMessages.reload(); + } + + /** Asks for a privilege key and redeems it on this server. */ + void usePrivilegeKey() { + if (!session.isConnected()) return; + String key = (String) JOptionPane.showInputDialog(host, "Privilege Key:", "Use Privilege Key", + JOptionPane.PLAIN_MESSAGE, Icons.of("TOKEN_USE"), null, null); + if (key == null || key.isBlank()) return; + conn.usePrivilegeKey(key.trim(), error -> { + if (error == null) return; + SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(host, error, + "Error using Privilege Key", JOptionPane.ERROR_MESSAGE)); + }); + } + + /** Opens the server's privilege keys, or brings the already open window forward. */ + void showPrivilegeKeys() { + if (!session.isConnected()) return; + if (privilegeKeys == null || !privilegeKeys.isDisplayable()) { + privilegeKeys = new PrivilegeKeysDialog(host, conn, groupIcons); + } + privilegeKeys.setVisible(true); + privilegeKeys.toFront(); + } + + /** The server's name changed or the connection went; the server admin windows follow. */ + void serverWindowsChanged(boolean connected) { + if (banList != null) { + if (connected) banList.serverNameChanged(); + else banList.connectionLost(); + } + if (complaints != null) { + if (connected) complaints.serverNameChanged(); + else complaints.connectionLost(); + } + if (serverLog != null) { + if (connected) serverLog.serverNameChanged(); + else serverLog.connectionLost(); + } + if (privilegeKeys != null) { + if (connected) privilegeKeys.serverNameChanged(); + else privilegeKeys.connectionLost(); + } + if (offlineMessages != null) { + if (connected) offlineMessages.serverNameChanged(); + else offlineMessages.connectionLost(); + } + if (!connected) unreadMessages = 0; + } + + /** The contact list changed: names, colours and per-client playback follow. */ + void contactsChanged() { + conn.applyContacts(); + treePanel.refreshRowSizes(); + treeActions.renderInfo(); + } + + // ---- dialogs ---- + + AvatarActions avatar() { + return avatar; + } + + // ---- chat ---- + + private void onSendChat(ChatPanel.Target target, int clientId, String text) { + session.sendChat(scope(target), clientId, text); + } + + private static ChatScope scope(ChatPanel.Target target) { + return switch (target) { + case SERVER -> ChatScope.SERVER; + case PRIVATE -> ChatScope.PRIVATE; + default -> ChatScope.CHANNEL; + }; + } + + /** Opens the file repository browser for a channel, as the "Browse Files" hotkey/menu action does. */ + void browseFiles(ChannelNode channel) { + treeActions.browseFiles(channel); + } + + /** + * Records where the user put the divider, as a share of the column. Collapsed and + * pre-layout positions are not the user's choice, so they are left out. + */ + private void rememberSplit() { + if (!splitRestored || !infoPanel.isVisible()) return; + int span = leftColumn.getHeight() - leftColumn.getDividerSize(); + if (span <= 0) return; + double ratio = leftColumn.getDividerLocation() / (double) span; + if (ratio <= 0.05 || ratio >= 0.98) return; + settings.infoSplitRatio = ratio; + } + + /** Collapses the info panel to nothing while its content lives in the chat tab, or restores it. */ + private void setInfoPanelHidden(boolean hidden) { + if (hidden == !infoPanel.isVisible()) return; + if (hidden) { + savedDividerLocation = leftColumn.getDividerLocation(); + infoPanel.setVisible(false); + leftColumn.setDividerSize(0); + leftColumn.setDividerLocation(1.0); + } else { + infoPanel.setVisible(true); + leftColumn.setDividerSize(normalDividerSize); + if (savedDividerLocation >= 0) leftColumn.setDividerLocation(savedDividerLocation); + } + leftColumn.revalidate(); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabConnectionEvents.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabConnectionEvents.java new file mode 100644 index 0000000..58e2826 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabConnectionEvents.java @@ -0,0 +1,209 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.net.ChannelNode; +import eu.lixko.ts3j.client.net.TeamspeakConnection; +import eu.lixko.ts3j.client.session.ServerSession; + +import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Marshals {@link ServerSession} callbacks onto the EDT and fans them out to this tab's + * views (tree, chat, info panel) and to {@link MainFrame}. + * + *

    Constructed before the session it listens to exists — the session's constructor + * needs a listener up front — so {@link #attach} wires the rest of the tab in once + * everything else has been built. + */ +final class ServerTabConnectionEvents implements ServerSession.Listener { + + private final MainFrame host; + private final ServerTab tab; + private final Settings settings; + + private final AtomicBoolean modelChangePending = new AtomicBoolean(); + + private ServerSession session; + private TeamspeakConnection conn; + private ServerTreePanel treePanel; + private ChatPanel chatPanel; + private ServerTabTreeActions treeActions; + + ServerTabConnectionEvents(MainFrame host, ServerTab tab, Settings settings) { + this.host = host; + this.tab = tab; + this.settings = settings; + } + + void attach(ServerSession session, ServerTreePanel treePanel, ChatPanel chatPanel, + ServerTabTreeActions treeActions) { + this.session = session; + this.conn = session.connection(); + this.treePanel = treePanel; + this.chatPanel = chatPanel; + this.treeActions = treeActions; + } + + @Override + public void onSessionChanged() { + SwingUtilities.invokeLater(() -> { + if (session.isConnected()) tab.serverWindowsChanged(true); + host.tabUpdated(tab); + }); + } + + @Override + public void onSystemMessage(String text) { + SwingUtilities.invokeLater(() -> chatPanel.appendSystem(text)); + } + + @Override + public void onOwnChat(ChatScope scope, int peerClientId, String peerName, String text) { + String me = settings.nickname + " (you)"; + int myId = conn.getSelfClientId(); + SwingUtilities.invokeLater(() -> { + switch (scope) { + case SERVER -> chatPanel.appendServerMessage(myId, me, text); + case PRIVATE -> chatPanel.appendPrivateMessage(peerClientId, peerName, myId, me, text); + default -> chatPanel.appendChannelMessage(myId, me, text); + } + }); + } + + @Override + public void onUnreadMessagesChanged(int unread) { + SwingUtilities.invokeLater(() -> { + tab.unreadMessagesChanged(unread); + host.tabUpdated(tab); + }); + } + + @Override + public void onStatus(String text) { + // Reaches the tab through onSessionChanged. + } + + @Override + public void onConnected() { + SwingUtilities.invokeLater(() -> { + treePanel.setSelfClientId(conn.getSelfClientId()); + chatPanel.setInputEnabled(true); + host.tabConnected(tab); + }); + } + + @Override + public void onDisconnected(String reason) { + SwingUtilities.invokeLater(() -> { + treePanel.showDisconnected(); + treeActions.clearSelection(); + chatPanel.setInputEnabled(false); + chatPanel.closePrivateChats(); + chatPanel.closeNoteTabs(); + chatPanel.setServerName(null); + chatPanel.setChannelName(null); + tab.serverWindowsChanged(false); + host.tabDisconnected(tab); + }); + } + + @Override + public void onModelChanged() { + // Events arrive in bursts (hundreds while connecting); one rebuild covers all of them. + if (!modelChangePending.compareAndSet(false, true)) return; + SwingUtilities.invokeLater(() -> { + modelChangePending.set(false); + treePanel.rebuild(); + treeActions.renderInfo(); + treeActions.refreshGroupsDialog(); + host.refreshHostButton(tab); + if (session.isConnected()) { + ChannelNode channel = session.currentChannel(); + chatPanel.setServerName(conn.getModel().getServerName()); + chatPanel.setChannelName(channel == null ? null : channel.name); + } + }); + } + + @Override + public void onServerIconChanged(long iconId) { + SwingUtilities.invokeLater(() -> host.serverIconChanged(tab, iconId)); + } + + @Override + public void onInfoUpdated() { + SwingUtilities.invokeLater(treeActions::renderInfo); + } + + @Override + public void onIconsUpdated() { + SwingUtilities.invokeLater(() -> { + treePanel.refreshRowSizes(); + treeActions.renderInfo(); + }); + } + + @Override + public void onChat(ChatScope scope, int fromClientId, String fromUniqueId, String fromName, String message) { + SwingUtilities.invokeLater(() -> { + switch (scope) { + case PRIVATE -> { + chatPanel.appendPrivateMessage(fromClientId, fromUniqueId, fromName, + fromClientId, fromUniqueId, fromName, message); + host.notifier().privateMessage(tab, fromClientId, fromName, message); + } + case SERVER -> chatPanel.appendServerMessage(fromClientId, fromUniqueId, fromName, message); + default -> chatPanel.appendChannelMessage(fromClientId, fromUniqueId, fromName, message); + } + }); + } + + @Override + public void onChatHistory(ChatScope scope, List htmlEntries) { + SwingUtilities.invokeLater(() -> { + if (scope == ChatScope.SERVER) chatPanel.setServerHistory(htmlEntries); + else if (scope == ChatScope.CHANNEL) chatPanel.setChannelHistory(htmlEntries); + }); + } + + @Override + public void onPrivateChatHistory(int clientId, String nickname, List htmlEntries) { + SwingUtilities.invokeLater(() -> chatPanel.setPrivateHistory(clientId, nickname, htmlEntries)); + } + + @Override + public void onTalkStateChanged(int clientId, boolean talking) { + SwingUtilities.invokeLater(() -> { + treePanel.refreshVisual(); + if (clientId == conn.getSelfClientId()) host.selfStateChanged(tab); + }); + } + + @Override + public void onError(String message) { + // Reaches the chat through onSystemMessage and the tab through onSessionChanged. + } + + @Override + public void onServerLog(String message) { + SwingUtilities.invokeLater(() -> chatPanel.appendServerLog(message)); + } + + @Override + public void onServerLogHtml(String html) { + SwingUtilities.invokeLater(() -> chatPanel.appendServerLogHtml(html)); + } + + @Override + public void onPoke(String fromName, String message) { + SwingUtilities.invokeLater(() -> { + host.notifier().poke(tab, fromName, message); + host.selectTab(tab); + JOptionPane.showMessageDialog(host, fromName + " poked you:\n\n" + message, + "Poke", JOptionPane.INFORMATION_MESSAGE); + }); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabPane.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabPane.java new file mode 100644 index 0000000..4f4c14e --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabPane.java @@ -0,0 +1,198 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTabbedPane; +import javax.swing.SwingUtilities; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Insets; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseWheelEvent; +import java.util.ArrayList; +import java.util.List; + +/** + * Container for the open server connections. With a single connection the + * server view fills the window as it always did; from the second connection on + * the views move into a {@link JTabbedPane} whose tab strip sits directly under + * the toolbar. + */ +final class ServerTabPane extends JPanel { + + interface Listener { + void selectTab(ServerTab tab); + + void closeTab(ServerTab tab); + } + + private final Listener listener; + private final JTabbedPane tabbed = new JTabbedPane(); + private final List tabs = new ArrayList<>(); + private final TabDragReorder dragReorder = new TabDragReorder(tabbed, this::moveTab); + + /** True while the tab strip is in use, i.e. more than one connection is open. */ + private boolean tabbedMode; + /** Suppresses selection callbacks while we rearrange the pane ourselves. */ + private boolean updating; + /** Remembered so a drag-reorder can rebuild the tab labels without the caller's help. */ + private ServerTab lastMicTab; + + ServerTabPane(Listener listener) { + super(new BorderLayout()); + this.listener = listener; + tabbed.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); + tabbed.setFocusable(false); + tabbed.addChangeListener(e -> { + if (updating) return; + int i = tabbed.getSelectedIndex(); + if (i >= 0 && i < tabs.size()) listener.selectTab(tabs.get(i)); + }); + tabbed.addMouseWheelListener(this::onWheel); + dragReorder.attach(tabbed); + } + + /** + * The tab strip is out of the component tree while a single server is open, so a + * look-and-feel switch would miss it and leave it in the old theme's colours. + */ + @Override + public void updateUI() { + super.updateUI(); + if (tabbed != null && tabbed.getParent() == null) SwingUtilities.updateComponentTreeUI(tabbed); + } + + /** Drags a tab from one position to another, keeping the current selection on screen. */ + private void moveTab(int from, int to) { + if (from < 0 || to < 0 || from >= tabs.size() || to >= tabs.size() || from == to) return; + ServerTab selected = tabbed.getSelectedIndex() >= 0 && tabbed.getSelectedIndex() < tabs.size() + ? tabs.get(tabbed.getSelectedIndex()) : null; + tabs.add(to, tabs.remove(from)); + updating = true; + try { + tabbed.removeAll(); + for (ServerTab tab : tabs) tabbed.addTab(tab.session().title(), tab.component()); + if (selected != null) tabbed.setSelectedIndex(tabs.indexOf(selected)); + } finally { + updating = false; + } + refresh(lastMicTab); + } + + /** + * Scrolling over the tab strip steps through the connections. The content + * area keeps its own scrolling, so only wheel events on the strip itself + * (and on the tab labels, which forward theirs) change tabs. + */ + private void onWheel(MouseWheelEvent e) { + if (!tabbedMode) return; + Component content = tabbed.getSelectedComponent(); + if (content != null && content.getBounds().contains(e.getPoint())) return; + + int steps = e.getWheelRotation(); + if (steps == 0) return; + int target = Math.max(0, Math.min(tabs.size() - 1, tabbed.getSelectedIndex() + steps)); + if (target != tabbed.getSelectedIndex()) listener.selectTab(tabs.get(target)); + e.consume(); + } + + void addTab(ServerTab tab) { + tabs.add(tab); + relayout(); + } + + void removeTab(ServerTab tab) { + tabs.remove(tab); + relayout(); + } + + void setSelected(ServerTab tab) { + int i = tabs.indexOf(tab); + if (!tabbedMode || i < 0 || tabbed.getSelectedIndex() == i) return; + updating = true; + try { + tabbed.setSelectedIndex(i); + } finally { + updating = false; + } + } + + /** Refreshes the tab labels; {@code micTab} is marked as owning the microphone. */ + void refresh(ServerTab micTab) { + lastMicTab = micTab; + if (!tabbedMode) return; + for (int i = 0; i < tabs.size(); i++) { + ServerTab tab = tabs.get(i); + tabbed.setTitleAt(i, tab.session().title()); + tabbed.setToolTipTextAt(i, tab.session().status()); + tabbed.setTabComponentAt(i, buildTabComponent(tab, tab == micTab)); + } + } + + /** + * Moves the views between the plain single-server layout and the tabbed one, + * keeping whatever is currently selected on screen. + */ + private void relayout() { + boolean wantTabs = tabs.size() > 1; + updating = true; + try { + removeAll(); + tabbed.removeAll(); + if (wantTabs) { + for (ServerTab tab : tabs) tabbed.addTab(tab.session().title(), tab.component()); + add(tabbed, BorderLayout.CENTER); + } else if (!tabs.isEmpty()) { + add(tabs.get(0).component(), BorderLayout.CENTER); + } + tabbedMode = wantTabs; + } finally { + updating = false; + } + revalidate(); + repaint(); + } + + /** A tab's label: title, microphone marker and a close button. */ + private JComponent buildTabComponent(ServerTab tab, boolean hasMic) { + JPanel cell = new JPanel(new FlowLayout(FlowLayout.LEFT, UIScale.scale(4), 0)); + cell.setOpaque(false); + cell.setBorder(new ScaledEmptyBorder(1, 0, 1, 0)); + + JLabel label = new JLabel(tab.session().title(), hasMic ? Icons.micActiveSmall() : null, JLabel.LEADING); + label.setFont(Theme.uiFont()); + label.setToolTipText(hasMic ? "Speaking on this server" : tab.session().status()); + // A label with a tooltip swallows mouse events, so select the tab explicitly. + label.addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + listener.selectTab(tab); + } + }); + cell.add(label); + dragReorder.attach(cell); + dragReorder.attach(label); + + JButton close = new JButton("✕"); + close.setFont(Theme.uiFont()); + close.setFocusable(false); + close.setBorder(BorderFactory.createEmptyBorder()); + close.setContentAreaFilled(false); + close.setMargin(new Insets(0, 0, 0, 0)); + close.setForeground(Theme.chatSystem()); + close.setPreferredSize(UIScale.scale(new Dimension(14, 14))); + close.setToolTipText("Close this connection"); + close.addActionListener(e -> listener.closeTab(tab)); + cell.add(close); + return cell; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabTreeActions.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabTreeActions.java new file mode 100644 index 0000000..faf8aba --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabTreeActions.java @@ -0,0 +1,366 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.contacts.ContactType; +import eu.lixko.ts3j.client.net.ChannelNode; +import eu.lixko.ts3j.client.net.Spacers; +import eu.lixko.ts3j.client.net.ChannelSettings; +import eu.lixko.ts3j.client.net.ClientEntry; +import eu.lixko.ts3j.client.net.Group; +import eu.lixko.ts3j.client.net.TeamspeakConnection; +import eu.lixko.ts3j.client.text.TsLink; + +import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; +import java.awt.Component; + +/** + * Context-menu and drag/drop actions for one server's tree, plus tracking which + * node is selected so the info panel stays in sync. Also handles client/channel + * links clicked in the chat log, which open the same menus as the tree does. + * + *

    Constructed before the {@link ServerTreePanel} it drives exists — the tree's + * constructor needs an {@link ServerTreePanel.Actions} up front — so {@link #attach} + * wires the tree back in once it has been built. + */ +final class ServerTabTreeActions implements ServerTreePanel.Actions { + + private final MainFrame host; + private final ServerTab tab; + private final TeamspeakConnection conn; + private final ChatPanel chatPanel; + private final InfoPanel infoPanel; + private final GroupIcons groupIcons; + private ServerTreePanel treePanel; + + private Object currentSelection; + /** The one open {@link ServerGroupsDialog}, if any, refreshed whenever the model changes. */ + private ServerGroupsDialog groupsDialog; + + ServerTabTreeActions(MainFrame host, ServerTab tab, TeamspeakConnection conn, + ChatPanel chatPanel, InfoPanel infoPanel, GroupIcons groupIcons) { + this.host = host; + this.tab = tab; + this.conn = conn; + this.chatPanel = chatPanel; + this.infoPanel = infoPanel; + this.groupIcons = groupIcons; + } + + void attach(ServerTreePanel treePanel) { + this.treePanel = treePanel; + } + + /** Called by {@link ServerTabConnectionEvents} whenever the model changes, to live-refresh an open dialog. */ + void refreshGroupsDialog() { + if (groupsDialog != null) groupsDialog.refresh(); + } + + /** Refreshes the info panel for whatever is currently selected (or clears it). */ + void renderInfo() { + Object sel = currentSelection; + if (sel instanceof ChannelNode) { + infoPanel.showChannel((ChannelNode) sel); + } else if (sel instanceof ClientEntry) { + ClientEntry client = (ClientEntry) sel; + infoPanel.showClient(client, conn.getModel(), conn.getIcons(), + conn.getContacts().find(client.uniqueId), conn.avatarOf(client)); + } else if (sel instanceof String && conn.isConnected()) { + // The root row is the server itself, whose user object is just its name. + infoPanel.showServer(conn.getModel(), conn.getServerHost() + ":" + conn.getServerPort()); + } else { + infoPanel.clear(); + } + } + + /** Drops the selection on disconnect, since the model it points into is gone. */ + void clearSelection() { + currentSelection = null; + infoPanel.clear(); + } + + /** A client link in the chat log was clicked: show the same menu as the tree does. */ + void handleClientLink(TsLink.Ref ref, Component source, int x, int y) { + ClientEntry client = conn.getModel().getClient(ref.id); + // The id is only valid for the session the link was made in; fall back to + // the unique id (and finally the nickname) so older links still resolve. + if (client == null || (!ref.uniqueId.isEmpty() && !ref.uniqueId.equals(client.uniqueId))) { + ClientEntry byUid = ref.uniqueId.isEmpty() ? null + : conn.getModel().findClientByUniqueId(ref.uniqueId); + if (byUid == null && !ref.name.isEmpty()) byUid = conn.getModel().findClientByName(ref.name); + if (byUid != null) client = byUid; + } + if (client == null) { + chatPanel.appendSystem("That client is no longer on the server."); + return; + } + ClientMenu.build(client, client.id == conn.getSelfClientId(), false, conn.getModel(), groupIcons, this) + .show(source, x, y); + } + + void handleChannelLink(TsLink.Ref ref, Component source, int x, int y) { + ChannelNode channel = conn.getModel().getChannel(ref.id); + if (channel == null) { + chatPanel.appendSystem("That channel no longer exists."); + return; + } + ChannelMenu.build(channel, this).show(source, x, y); + } + + // ---- ServerTreePanel.Actions ---- + + @Override + public void joinChannel(int channelId) { + if (conn.isConnected()) conn.joinChannel(channelId, null); + } + + @Override + public void moveClientToChannel(ClientEntry client, ChannelNode target) { + if (!conn.isConnected()) return; + if (client.id == conn.getSelfClientId()) { + conn.joinChannel(target.id, null); + } else { + conn.moveClient(client.id, target.id, null); + } + } + + @Override + public void moveChannel(ChannelNode channel, int newParentId, int orderPredecessorId) { + if (conn.isConnected()) conn.moveChannel(channel.id, newParentId, orderPredecessorId); + } + + @Override + public void openPrivateChat(ClientEntry client) { + chatPanel.openPrivateChat(client.id, client.uniqueId, conn.displayName(client)); + conn.loadPrivateChatHistory(client.id, client.uniqueId); + } + + @Override + public void pokeClient(ClientEntry client) { + String msg = JOptionPane.showInputDialog(host, "Poke message for " + client.nickname + ":", "Poke!"); + if (msg != null) conn.poke(client.id, msg); + } + + @Override + public void complainAboutClient(ClientEntry client) { + if (!conn.isConnected()) return; + String reason = ReasonDialog.prompt(host, "Make a Complaint", "Enter the reason for your complaint:", + TeamspeakConnection.COMPLAINT_REASON_LIMIT); + if (reason != null) conn.complain(client, reason); + } + + @Override + public void kickClientFromChannel(ClientEntry client) { + String reason = kickReason("Kick Client from Channel", client); + if (reason != null) conn.kickFromChannel(client.id, reason); + } + + @Override + public void kickClientFromServer(ClientEntry client) { + String reason = kickReason("Kick Client from Server", client); + if (reason != null) conn.kickFromServer(client.id, reason); + } + + private String kickReason(String title, ClientEntry client) { + if (!conn.isConnected()) return null; + return ReasonDialog.prompt(host, title, "Reason for kicking " + client.nickname + ":", + TeamspeakConnection.KICK_REASON_LIMIT); + } + + @Override + public void banClient(ClientEntry client) { + if (!conn.isConnected()) return; + BanDialog dialog = new BanDialog(host, client.nickname, + conn.getModel().maxBanSeconds()); + dialog.setVisible(true); + if (dialog.isConfirmed()) conn.banClient(client.id, dialog.getSeconds(), dialog.getReason()); + } + + @Override + public void toggleClientMute(ClientEntry client) { + if (conn.getPlayback() == null) return; + boolean now = !conn.getPlayback().isClientMuted(client.id); + conn.getPlayback().setClientMuted(client.id, now); + } + + @Override + public void findClientInTree(ClientEntry client) { + host.selectTab(tab); + treePanel.selectClient(client.id); + } + + @Override + public void showConnectionInfo(ClientEntry client) { + if (!conn.isConnected()) return; + new ConnectionInfoDialog(host, conn, client.id, client.nickname).setVisible(true); + } + + @Override + public void moveClientToOwnChannel(ClientEntry client) { + if (!conn.isConnected() || client.id == conn.getSelfClientId()) return; + ClientEntry self = conn.getModel().getClient(conn.getSelfClientId()); + if (self != null) conn.moveClient(client.id, self.channelId, null); + } + + @Override + public void setClientServerGroup(ClientEntry client, Group group, boolean assign) { + if (conn.isConnected()) conn.setClientServerGroup(client.databaseId, group.id, assign); + } + + @Override + public void setClientChannelGroup(ClientEntry client, Group group) { + if (conn.isConnected()) conn.setClientChannelGroup(client.databaseId, client.channelId, group.id); + } + + @Override + public void showServerGroupsDialog(ClientEntry client) { + if (!conn.isConnected()) return; + groupsDialog = new ServerGroupsDialog(host, conn, groupIcons, client, this); + groupsDialog.setVisible(true); + groupsDialog = null; + } + + /** + * Reads the description from the server before prompting, since the model only + * carries one for clients whose info has been looked at. + */ + @Override + public boolean canDeleteOtherAvatars() { + return tab.session().canDeleteOtherAvatars(); + } + + @Override + public void deleteClientAvatar(ClientEntry client) { + tab.avatar().deleteOf(client); + } + + @Override + public void changeClientDescription(ClientEntry client) { + if (!conn.isConnected()) return; + conn.requestClientDescription(client.id, (description, error) -> SwingUtilities.invokeLater(() -> { + if (error != null) { + JOptionPane.showMessageDialog(host, "Could not read the description: " + error, + "Error", JOptionPane.ERROR_MESSAGE); + return; + } + String edited = (String) JOptionPane.showInputDialog(host, + "Description for " + client.nickname + ":", "Change Description", + JOptionPane.PLAIN_MESSAGE, Icons.of("EDIT"), null, description); + if (edited == null || edited.equals(description)) return; + conn.setClientDescription(client.id, edited, failure -> SwingUtilities.invokeLater(() -> { + if (failure != null) { + JOptionPane.showMessageDialog(host, "Could not change the description: " + failure, + "Error", JOptionPane.ERROR_MESSAGE); + } + })); + })); + } + + @Override + public void addContact(ClientEntry client, ContactType type) { + conn.getContacts().add(client.uniqueId, client.nickname, type, host.settings().contactDefaults); + } + + @Override + public void editContact(ClientEntry client) { + host.showContacts(client.uniqueId); + } + + @Override + public void removeContact(ClientEntry client) { + conn.getContacts().remove(client.uniqueId); + } + + @Override + public ContactType contactTypeOf(ClientEntry client) { + return conn.getContacts().typeOf(client.uniqueId); + } + + @Override + public void changeClientVolume(ClientEntry client) { + if (!conn.isConnected()) return; + new ClientVolumeDialog(host, conn, client).setVisible(true); + } + + @Override + public void renameSelf(String nickname) { + host.changeNickname(nickname); + } + + @Override + public void setChannelSubscribed(ChannelNode channel, boolean family, boolean subscribed) { + if (conn.isConnected()) conn.setChannelsSubscribed(channel.familyIds(family), subscribed); + } + + @Override + public void editChannel(ChannelNode channel) { + if (!conn.isConnected()) return; + ChannelDialog.toEdit(host, conn, groupIcons, channel).setVisible(true); + } + + @Override + public void deleteChannel(ChannelNode channel) { + if (!conn.isConnected()) return; + // Like TeamSpeak, a channel that is not empty takes its sub-channels along and sends its clients away. + boolean occupied = !channel.children.isEmpty() || !channel.clients.isEmpty(); + String question = "Delete channel \"" + channel.name + "\"" + + (occupied ? " with its sub-channels and the clients in it?" : "?"); + if (JOptionPane.showConfirmDialog(host, question, "Delete Channel", JOptionPane.OK_CANCEL_OPTION, + JOptionPane.WARNING_MESSAGE) != JOptionPane.OK_OPTION) { + return; + } + conn.deleteChannel(channel.id, true, error -> { + if (error != null) SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(host, + "Could not delete the channel: " + error, "Error", JOptionPane.ERROR_MESSAGE)); + }); + } + + @Override + public void createChannel(ChannelNode parent, ChannelSettings.Type type) { + if (!conn.isConnected()) return; + ChannelSettings defaults = new ChannelSettings(); + defaults.type = type; + ChannelDialog.toCreate(host, conn, groupIcons, + parent == null ? "Create Channel" : "Create Sub-Channel of " + parent.name, + parent == null ? 0 : parent.id, defaults).setVisible(true); + } + + @Override + public void createSpacer() { + if (!conn.isConnected()) return; + ChannelSettings defaults = new ChannelSettings(); + // Spacers are cosmetic root channels, so they outlive everyone and, being channels, + // need a name no other channel has — which is what the tag's number is for. + defaults.name = Spacers.freeName(conn.getModel().childrenOf(0)); + ChannelDialog.toCreate(host, conn, groupIcons, "Create Spacer", 0, defaults) + .setVisible(true); + } + + @Override + public boolean isConnected() { + return conn.isConnected(); + } + + @Override + public void browseFiles(ChannelNode channel) { + if (!conn.canTransferFiles()) return; + new FileBrowserDialog(host, conn, channel).setVisible(true); + } + + @Override + public boolean isClientLocallyMuted(int clientId) { + return conn.getPlayback() != null && conn.getPlayback().isClientMuted(clientId); + } + + @Override + public void onSelectionChanged(Object userObject) { + currentSelection = userObject; + renderInfo(); + if (!conn.isConnected()) return; + if (userObject instanceof ChannelNode) { + ChannelNode ch = (ChannelNode) userObject; + if (!ch.descriptionLoaded) conn.requestChannelInfo(ch.id); + } else if (userObject instanceof ClientEntry) { + conn.requestClientInfo(((ClientEntry) userObject).id); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreeCellRenderer.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreeCellRenderer.java new file mode 100644 index 0000000..e2e676d --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreeCellRenderer.java @@ -0,0 +1,118 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.contacts.Contact; +import eu.lixko.ts3j.client.contacts.ContactStore; +import eu.lixko.ts3j.client.net.ChannelNode; +import eu.lixko.ts3j.client.net.Spacers; +import eu.lixko.ts3j.client.net.ClientEntry; +import eu.lixko.ts3j.client.net.ClientStatus; + +import javax.swing.ImageIcon; +import javax.swing.JTree; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeCellRenderer; +import java.awt.Color; +import java.awt.Component; +import java.util.function.IntPredicate; + +/** + * Draws a {@link ServerTreePanel} row: the status icon and the label. The group + * icon strip is painted separately, right-aligned, by {@link DropIndicatorTree}. + */ +final class ServerTreeCellRenderer extends DefaultTreeCellRenderer { + + /** Whether a client id is our own, which the panel learns on connecting. */ + private final IntPredicate isSelf; + private final ContactStore contacts; + private final Settings settings; + + ServerTreeCellRenderer(IntPredicate isSelf, ContactStore contacts, Settings settings) { + this.isSelf = isSelf; + this.contacts = contacts; + this.settings = settings; + } + + @Override + public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, + boolean expanded, boolean leaf, int row, + boolean hasFocus) { + super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); + setBackgroundNonSelectionColor(Theme.treeBg()); + setBackgroundSelectionColor(Theme.treeSelection()); + setBorderSelectionColor(Theme.treeSelection()); + + Object obj = ((DefaultMutableTreeNode) value).getUserObject(); + if (obj instanceof ChannelNode) { + ChannelNode c = (ChannelNode) obj; + Spacers.Spacer spacer = Spacers.parse(c.name); + if (spacer != null) { + setText(Spacers.render(spacer, 40)); + setIcon(null); + setForeground(Theme.idleClient()); + setFont(Theme.uiFont()); + } else { + setText(c.name); + setIcon(iconFor(c)); + setForeground(Theme.channelText()); + setFont(Theme.uiBold()); + } + } else if (obj instanceof ClientEntry) { + ClientEntry cl = (ClientEntry) obj; + Contact contact = contacts.find(cl.uniqueId); + String label = contact == null ? cl.nickname : contact.displayName(cl.nickname); + if (cl.away && !cl.awayMessage.isEmpty() && (contact == null || !contact.ignoreAwayMessage)) { + label += " [" + cl.awayMessage + "]"; + } + setText(label); + setIcon(iconFor(cl)); + // Talking shows in the client's icon, as it does in TeamSpeak. Marking the + // name as well would also re-measure the row mid-speech, which leaves the + // nickname clipped to an ellipsis for as long as it lasts. Our own name is + // bold throughout, so its width never changes either. + setForeground(contactColor(contact)); + setFont(isSelf.test(cl.id) ? Theme.uiBold() : Theme.uiFont()); + } else { + // root / server + setText(String.valueOf(obj)); + setIcon(Icons.server()); + setForeground(Theme.serverText()); + setFont(Theme.uiBold()); + } + return this; + } + + /** Friends and blocked clients stand out by colour, as in TeamSpeak, unless turned off. */ + private Color contactColor(Contact contact) { + if (contact == null || !settings.colorContacts) return Theme.treeText(); + switch (contact.type) { + case FRIEND: + return Theme.friend(); + case BLOCKED: + return Theme.blocked(); + default: + return Theme.treeText(); + } + } + + private ImageIcon iconFor(ChannelNode c) { + if (c.hasPassword) return Icons.channelLocked(c.subscribed); + if (c.maxClients >= 0 && c.clients.size() >= c.maxClients) return Icons.channelFull(c.subscribed); + return Icons.channel(c.subscribed); + } + + private ImageIcon iconFor(ClientEntry cl) { + return switch (ClientStatus.of(cl)) { + case QUERY -> Icons.clientQuery(); + case SPEAKERS_DISABLED -> Icons.speakerDisabled(); + case SPEAKERS_MUTED -> Icons.speakerMuted(); + case MIC_DISABLED -> Icons.micDisabled(); + case MIC_MUTED -> Icons.micMuted(); + case AWAY -> Icons.clientAway(); + case COMMANDER_TALKING -> Icons.clientCommanderTalking(); + case COMMANDER -> Icons.clientCommander(); + case TALKING -> Icons.clientTalking(); + case IDLE -> Icons.clientIdle(); + }; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreeDragAndDrop.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreeDragAndDrop.java new file mode 100644 index 0000000..1d9ef26 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreeDragAndDrop.java @@ -0,0 +1,236 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.net.ChannelNode; +import eu.lixko.ts3j.client.net.Spacers; +import eu.lixko.ts3j.client.net.ClientEntry; +import eu.lixko.ts3j.client.net.ServerModel; +import eu.lixko.ts3j.client.text.TsLink; + +import javax.swing.JComponent; +import javax.swing.JTree; +import javax.swing.TransferHandler; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.TreePath; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.Transferable; +import java.awt.datatransfer.UnsupportedFlavorException; +import java.util.function.Function; + +/** + * Drag-and-drop for the {@link ServerTreePanel} tree: dragging a client onto a + * channel moves it there, dragging a channel reorders/reparents it, and dropping + * either outside the tree yields its TS3 link BBCode, which the chat input accepts + * as plain text. + */ +final class ServerTreeDragAndDrop { + + /** Carries the dragged node inside this JVM; drops elsewhere get the BBCode text. */ + private static final DataFlavor NODE_FLAVOR = new DataFlavor( + DataFlavor.javaJVMLocalObjectMimeType + ";class=java.lang.Object", + "TeamSpeak tree node"); + + private final ServerModel model; + private final ServerTreePanel.Actions actions; + private final DropIndicatorTree tree; + /** Looks up the tree path currently showing a given channel/client, or {@code null}. */ + private final Function pathOf; + + ServerTreeDragAndDrop(ServerModel model, ServerTreePanel.Actions actions, DropIndicatorTree tree, + Function pathOf) { + this.model = model; + this.actions = actions; + this.tree = tree; + this.pathOf = pathOf; + } + + TransferHandler transferHandler() { + return new TreeTransferHandler(); + } + + private static DefaultMutableTreeNode nodeOf(TreePath path) { + return path == null ? null : (DefaultMutableTreeNode) path.getLastPathComponent(); + } + + /** + * The channel a dragged client would land in, or {@code null} if the drop makes + * no sense (outside a channel, or the channel the client is already in). + */ + private ChannelNode resolveClientDrop(JTree.DropLocation loc, ClientEntry dragged) { + DefaultMutableTreeNode target = nodeOf(loc.getPath()); + if (target == null) return null; + Object obj = target.getUserObject(); + ChannelNode channel = null; + if (obj instanceof ChannelNode) { + channel = (ChannelNode) obj; + } else if (obj instanceof ClientEntry) { + channel = model.getChannel(((ClientEntry) obj).channelId); + } + if (channel == null || Spacers.isSpacer(channel.name)) return null; + if (channel.id == dragged.channelId) return null; + return channel; + } + + /** + * The new parent and predecessor for a dragged channel as {@code {cpid, order}}, + * or {@code null} if this drop is not a legal (or meaningful) move. + */ + private int[] resolveChannelDrop(JTree.DropLocation loc, ChannelNode dragged) { + DefaultMutableTreeNode target = nodeOf(loc.getPath()); + if (target == null) return null; + + DefaultMutableTreeNode parentNode; + int insertIndex; + if (loc.getChildIndex() >= 0) { + parentNode = target; + insertIndex = loc.getChildIndex(); + } else { + // Dropped onto a node: become its last subchannel. + parentNode = target.getUserObject() instanceof ClientEntry + ? (DefaultMutableTreeNode) target.getParent() : target; + if (parentNode == null) return null; + insertIndex = parentNode.getChildCount(); + } + + int parentId = 0; + Object parentObj = parentNode.getUserObject(); + if (parentObj instanceof ChannelNode) { + ChannelNode parent = (ChannelNode) parentObj; + if (Spacers.isSpacer(parent.name)) return null; + if (isSelfOrDescendant(parent, dragged)) return null; // would detach the subtree + parentId = parent.id; + } else if (parentNode.getParent() != null) { + return null; + } + + int predecessorId = 0; + for (int i = 0; i < insertIndex && i < parentNode.getChildCount(); i++) { + Object o = ((DefaultMutableTreeNode) parentNode.getChildAt(i)).getUserObject(); + if (o instanceof ChannelNode && ((ChannelNode) o).id != dragged.id) { + predecessorId = ((ChannelNode) o).id; + } + } + if (parentId == dragged.parentId && predecessorId == dragged.order) return null; // no-op + return new int[]{parentId, predecessorId}; + } + + /** Whether {@code candidate} is {@code ancestor} itself or sits below it. */ + private boolean isSelfOrDescendant(ChannelNode candidate, ChannelNode ancestor) { + ChannelNode c = candidate; + for (int guard = 0; c != null && guard < 64; guard++) { + if (c.id == ancestor.id) return true; + c = model.getChannel(c.parentId); + } + return false; + } + + private final class TreeTransferHandler extends TransferHandler { + @Override + public int getSourceActions(JComponent c) { + return COPY | MOVE; + } + + @Override + protected Transferable createTransferable(JComponent c) { + TreePath path = tree.getSelectionPath(); + if (path == null) return null; + Object obj = nodeOf(path).getUserObject(); + if (obj instanceof ClientEntry) { + ClientEntry cl = (ClientEntry) obj; + return new NodeTransferable(cl, TsLink.clientBBCode(cl.id, cl.uniqueId, cl.nickname)); + } + if (obj instanceof ChannelNode) { + ChannelNode ch = (ChannelNode) obj; + // Spacers have no meaningful link text, but can still be re-ordered. + return new NodeTransferable(ch, Spacers.isSpacer(ch.name) + ? null : TsLink.channelBBCode(ch.id, ch.name)); + } + return null; + } + + @Override + public boolean canImport(TransferSupport support) { + if (!support.isDrop() || !support.isDataFlavorSupported(NODE_FLAVOR)) { + tree.highlightChannel(null); + return false; + } + if ((support.getSourceDropActions() & MOVE) == MOVE) support.setDropAction(MOVE); + Object resolved = resolve(support); + // A client always lands *inside* a channel, so mark that channel instead of + // drawing a line that would suggest a position among its clients. + tree.highlightChannel(resolved instanceof ChannelNode + ? pathOf.apply(resolved) : null); + // The indicator spans the full width, past the row rectangles Swing + // repaints on its own when the drop location moves. + tree.repaint(); + return resolved != null; + } + + @Override + protected void exportDone(JComponent source, Transferable data, int action) { + tree.highlightChannel(null); + tree.repaint(); + } + + @Override + public boolean importData(TransferSupport support) { + if (!canImport(support)) return false; + Object dragged = draggedNode(support); + Object resolved = resolve(support); + tree.highlightChannel(null); + if (dragged instanceof ClientEntry) { + actions.moveClientToChannel((ClientEntry) dragged, (ChannelNode) resolved); + } else if (dragged instanceof ChannelNode) { + int[] place = (int[]) resolved; + actions.moveChannel((ChannelNode) dragged, place[0], place[1]); + } + return true; + } + + /** The destination for this drop: a ChannelNode, an {@code {cpid, order}} pair, or null. */ + private Object resolve(TransferSupport support) { + Object dragged = draggedNode(support); + if (!(support.getDropLocation() instanceof JTree.DropLocation)) return null; + JTree.DropLocation loc = (JTree.DropLocation) support.getDropLocation(); + if (dragged instanceof ClientEntry) return resolveClientDrop(loc, (ClientEntry) dragged); + if (dragged instanceof ChannelNode) return resolveChannelDrop(loc, (ChannelNode) dragged); + return null; + } + + private Object draggedNode(TransferSupport support) { + try { + return support.getTransferable().getTransferData(NODE_FLAVOR); + } catch (Exception e) { + return null; + } + } + } + + /** Offers the dragged node locally and its TS3 link BBCode to other applications. */ + private static final class NodeTransferable implements Transferable { + private final Object node; + private final String text; + + NodeTransferable(Object node, String text) { + this.node = node; + this.text = text; + } + + @Override + public DataFlavor[] getTransferDataFlavors() { + return text == null ? new DataFlavor[]{NODE_FLAVOR} + : new DataFlavor[]{NODE_FLAVOR, DataFlavor.stringFlavor}; + } + + @Override + public boolean isDataFlavorSupported(DataFlavor flavor) { + return NODE_FLAVOR.equals(flavor) || (text != null && DataFlavor.stringFlavor.equals(flavor)); + } + + @Override + public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException { + if (NODE_FLAVOR.equals(flavor)) return node; + if (text != null && DataFlavor.stringFlavor.equals(flavor)) return text; + throw new UnsupportedFlavorException(flavor); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreePanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreePanel.java new file mode 100644 index 0000000..43af08b --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreePanel.java @@ -0,0 +1,493 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.contacts.ContactStore; +import eu.lixko.ts3j.client.contacts.ContactType; +import eu.lixko.ts3j.client.net.ChannelNode; +import eu.lixko.ts3j.client.net.Spacers; +import eu.lixko.ts3j.client.net.ChannelSettings; +import eu.lixko.ts3j.client.net.ClientEntry; +import eu.lixko.ts3j.client.net.Group; +import eu.lixko.ts3j.client.net.ServerModel; + +import javax.swing.AbstractAction; +import javax.swing.DropMode; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JViewport; +import javax.swing.KeyStroke; +import javax.swing.SwingUtilities; +import javax.swing.plaf.basic.BasicTreeUI; +import javax.swing.event.TreeExpansionEvent; +import javax.swing.event.TreeExpansionListener; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeModel; +import javax.swing.tree.TreePath; +import java.awt.BorderLayout; +import java.awt.Rectangle; +import java.awt.event.ActionEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * The server view: a tree of channels each containing its clients, styled to + * resemble the TeamSpeak 3 client. Talk state colours clients green live. + */ +public final class ServerTreePanel extends JPanel { + + /** Actions the tree can request of the controller. */ + public interface Actions { + void joinChannel(int channelId); + + void openPrivateChat(ClientEntry client); + + void pokeClient(ClientEntry client); + + void complainAboutClient(ClientEntry client); + + void kickClientFromChannel(ClientEntry client); + + void kickClientFromServer(ClientEntry client); + + void banClient(ClientEntry client); + + void toggleClientMute(ClientEntry client); + + void showConnectionInfo(ClientEntry client); + + /** Moves a client into the channel we are currently in. */ + void moveClientToOwnChannel(ClientEntry client); + + /** Opens the channel editor for a channel. */ + void editChannel(ChannelNode channel); + + void deleteChannel(ChannelNode channel); + + /** + * Opens the channel creator. + * + * @param parent the channel the new one goes below, or {@code null} for a top-level one + * @param type the channel type to start with + */ + void createChannel(ChannelNode parent, ChannelSettings.Type type); + + /** Opens the channel creator pre-filled as a spacer, which is always top-level. */ + void createSpacer(); + + /** Whether the server is there to act on at all. */ + boolean isConnected(); + + /** Open the file repository browser for a channel. */ + void browseFiles(ChannelNode channel); + + /** + * Changes a channel's subscription. + * + * @param family whether the channels below it are included + */ + void setChannelSubscribed(ChannelNode channel, boolean family, boolean subscribed); + + boolean isClientLocallyMuted(int clientId); + + /** Selects and scrolls to a client in the tree, e.g. from a chat/log link. */ + void findClientInTree(ClientEntry client); + + /** A channel or client node was selected (or {@code null} when cleared). */ + void onSelectionChanged(Object userObject); + + /** Drag-and-drop of a client onto a channel. */ + void moveClientToChannel(ClientEntry client, ChannelNode target); + + /** + * Drag-and-drop of a channel to a new place in the tree. + * + * @param orderPredecessorId the channel it should sit below among its new + * siblings, or 0 to place it first + */ + void moveChannel(ChannelNode channel, int newParentId, int orderPredecessorId); + + /** Assigns or removes a server group for a client. */ + void setClientServerGroup(ClientEntry client, Group group, boolean assign); + + /** Assigns a channel group for a client in its current channel. */ + void setClientChannelGroup(ClientEntry client, Group group); + + /** Opens the full server-groups list dialog for a client. */ + void showServerGroupsDialog(ClientEntry client); + + /** Edits a client's description — our own included. */ + void changeClientDescription(ClientEntry client); + + /** Whether we may delete other clients' avatars. */ + boolean canDeleteOtherAvatars(); + + void deleteClientAvatar(ClientEntry client); + + /** A new nickname for ourselves, typed into the tree row. */ + void renameSelf(String nickname); + + /** Files a client in the contact list as a friend, blocked or neutral. */ + void addContact(ClientEntry client, ContactType type); + + /** Opens the contact list at this client's entry. */ + void editContact(ClientEntry client); + + void removeContact(ClientEntry client); + + /** The type a client is filed under, or {@code null} for a client that is no contact. */ + ContactType contactTypeOf(ClientEntry client); + + /** Opens the per-client volume dialog. */ + void changeClientVolume(ClientEntry client); + } + + private final DropIndicatorTree tree; + private final JScrollPane scroll = new JScrollPane() { + @Override + public void updateUI() { + super.updateUI(); + // The rows stop at the last channel, so the space below them belongs to the tree + // rather than to the window behind it. + if (getViewport() != null) getViewport().setBackground(Theme.treeBg()); + } + }; + private final ServerTreeSearch search; + private final DefaultMutableTreeNode root = new DefaultMutableTreeNode(); + /** + * The nodes only mirror the connection's model, so an edited row is not written + * back into the tree: the new nickname goes to the server, and the row follows + * once it reports the rename. + */ + private final DefaultTreeModel treeModel = new DefaultTreeModel(root) { + @Override + public void valueForPathChanged(TreePath path, Object newValue) { + String nickname = String.valueOf(newValue).trim(); + Object edited = ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); + // The server answers a rename to the name already held with "nickname is + // already in use", so a field closed unchanged is simply left alone. + if (edited instanceof ClientEntry && nickname.equals(((ClientEntry) edited).nickname)) return; + if (!nickname.isEmpty()) actions.renameSelf(nickname); + } + }; + /** + * True while the tree is changed programmatically: a {@link #rebuild()} clearing and restoring + * the selection, or channels being reopened. The listeners ignore what happens meanwhile. + */ + private boolean rebuilding; + /** Channels the user collapsed; every other channel is shown open. */ + private final Set collapsedChannels = new HashSet<>(); + private final ServerModel model; + private final GroupIcons groupIcons; + private final Actions actions; + private final NicknameCellEditor nicknameEditor; + private int selfClientId = -1; + + public ServerTreePanel(ServerModel model, GroupIcons groupIcons, ContactStore contacts, Settings settings, + Actions actions) { + super(new BorderLayout()); + this.model = model; + this.groupIcons = groupIcons; + this.actions = actions; + root.setUserObject("Not connected"); + this.tree = new DropIndicatorTree(treeModel, model, groupIcons, settings); + tree.setRootVisible(true); + // The server node is the only top-level row and always stays open, so it gets + // no expand control. Nesting is tightened too: horizontal space in this view + // is scarce and channel names are long. + tree.setShowsRootHandles(false); + // Double-click joins a channel; expanding is left to the handles and the keyboard. + tree.setToggleClickCount(0); + if (tree.getUI() instanceof BasicTreeUI) { + BasicTreeUI ui = (BasicTreeUI) tree.getUI(); + ui.setLeftChildIndent(4); + ui.setRightChildIndent(10); + } + tree.setRowHeight(UIScale.scale(20)); + // Lays out only the rows on screen. The default cache measures every row as it is + // expanded, which freezes the window for seconds on servers with hundreds of channels. + tree.setLargeModel(true); + tree.setBackground(Theme.treeBg()); + tree.setFont(Theme.uiFont()); + ServerTreeCellRenderer renderer = new ServerTreeCellRenderer(id -> id == selfClientId, contacts, settings); + tree.setCellRenderer(renderer); + nicknameEditor = NicknameCellEditor.create(tree, renderer, id -> id == selfClientId); + tree.setCellEditor(nicknameEditor); + tree.setEditable(true); + tree.setPathEditable(nicknameEditor::editsPath); + tree.setInvokesStopCellEditing(true); + scroll.setViewportView(tree); + // The icon strip is drawn against the viewport's right edge, so the blitted + // pixels a scroll would reuse are stale; repaint the whole viewport instead. + scroll.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE); + // Scrolling slides the rows past a pointer that has not moved, so the outlined + // row has to be worked out again. + scroll.getViewport().addChangeListener(e -> tree.refreshHoverRow()); + scroll.getViewport().setBackground(Theme.treeBg()); + add(scroll, BorderLayout.CENTER); + + search = new ServerTreeSearch(tree, root, contacts, this::rebuild); + add(search.bar(), BorderLayout.SOUTH); + String find = "ts3-tree-find"; + getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("control F"), find); + getActionMap().put(find, new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + openFind(); + } + }); + + // Within the tree a drag moves the client or channel; dropped elsewhere it + // yields the TS3 link BBCode, which the chat input accepts as plain text. + tree.setDragEnabled(true); + tree.setDropMode(DropMode.ON_OR_INSERT); + tree.setTransferHandler(new ServerTreeDragAndDrop(model, actions, tree, this::pathOf).transferHandler()); + + tree.addTreeExpansionListener(new TreeExpansionListener() { + @Override + public void treeCollapsed(TreeExpansionEvent e) { + if (rebuilding) return; + Object obj = ((DefaultMutableTreeNode) e.getPath().getLastPathComponent()).getUserObject(); + if (obj instanceof ChannelNode) collapsedChannels.add(((ChannelNode) obj).id); + } + + @Override + public void treeExpanded(TreeExpansionEvent e) { + if (rebuilding) return; + DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent(); + if (!(node.getUserObject() instanceof ChannelNode)) return; + collapsedChannels.remove(((ChannelNode) node.getUserObject()).id); + // A rebuild while it was shut left everything below it shut too. + rebuilding = true; + try { + expandOpenChannels(node, e.getPath()); + } finally { + rebuilding = false; + } + } + }); + + tree.addTreeSelectionListener(e -> { + if (rebuilding) return; + TreePath path = tree.getSelectionPath(); + Object obj = null; + if (path != null) { + obj = ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); + } + actions.onSelectionChanged(obj); + }); + + tree.addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + selectRowUnder(e); + maybePopup(e); + } + + @Override + public void mouseReleased(MouseEvent e) { + maybePopup(e); + } + + @Override + public void mouseClicked(MouseEvent e) { + Object obj = nodeAt(e); + if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) { + if (obj instanceof ChannelNode && !Spacers.isSpacer(((ChannelNode) obj).name)) { + actions.joinChannel(((ChannelNode) obj).id); + } else if (obj instanceof ClientEntry) { + if (((ClientEntry) obj).id == selfClientId) { + tree.startEditingAtPath(tree.pathAt(e.getY())); + } else { + actions.openPrivateChat((ClientEntry) obj); + } + } + } else if (SwingUtilities.isMiddleMouseButton(e) && obj instanceof ClientEntry) { + actions.showConnectionInfo((ClientEntry) obj); + } + } + }); + } + + /** + * Selects the row a press landed on. A row acts on its whole line, but Swing's own + * hit testing stops at the end of the label, so a press further right would leave + * the selection where it was. + */ + private void selectRowUnder(MouseEvent e) { + if (!SwingUtilities.isLeftMouseButton(e) && !e.isPopupTrigger()) return; + TreePath path = tree.pathAt(e.getY()); + if (path == null || path.equals(tree.getSelectionPath())) return; + Rectangle bounds = tree.getPathBounds(path); + // Left of the label is the expand handle, which Swing works the row without selecting it. + if (bounds != null && e.getX() < bounds.x) return; + tree.setSelectionPath(path); + } + + /** Opens the find bar above the tree. */ + public void openFind() { + search.open(); + } + + public void setSelfClientId(int id) { + this.selfClientId = id; + } + + /** Selects and scrolls to the row showing {@code client}, if it is currently visible. */ + public void selectClient(int clientId) { + ClientEntry client = model.getClient(clientId); + if (client == null) return; + TreePath path = pathOf(client); + if (path == null) return; + tree.setSelectionPath(path); + tree.scrollPathToVisible(path); + } + + private Object nodeAt(MouseEvent e) { + TreePath path = tree.pathAt(e.getY()); + if (path == null) return null; + DefaultMutableTreeNode n = (DefaultMutableTreeNode) path.getLastPathComponent(); + return n.getUserObject(); + } + + private void maybePopup(MouseEvent e) { + if (!e.isPopupTrigger()) return; + TreePath path = tree.pathAt(e.getY()); + if (path == null) return; + tree.setSelectionPath(path); + Object obj = ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); + if (obj instanceof ClientEntry) { + showClientMenu((ClientEntry) obj, e); + } else if (obj instanceof ChannelNode) { + showChannelMenu((ChannelNode) obj, e); + } else if (path.getPathCount() == 1 && actions.isConnected()) { + // The root row is the server itself, whose user object is just its name. + ServerMenu.build(actions).show(tree, e.getX(), e.getY()); + } + } + + private void showClientMenu(ClientEntry client, MouseEvent e) { + ClientMenu.build(client, client.id == selfClientId, true, model, groupIcons, actions) + .show(tree, e.getX(), e.getY()); + } + + private void showChannelMenu(ChannelNode channel, MouseEvent e) { + if (Spacers.isSpacer(channel.name)) return; // spacers aren't interactive + ChannelMenu.build(channel, actions).show(tree, e.getX(), e.getY()); + } + + /** The path of the tree node showing {@code target}, or {@code null}. */ + private TreePath pathOf(Object target) { + java.util.Enumeration nodes = root.breadthFirstEnumeration(); + while (nodes.hasMoreElements()) { + DefaultMutableTreeNode n = (DefaultMutableTreeNode) nodes.nextElement(); + if (n.getUserObject() == target) return new TreePath(n.getPath()); + } + return null; + } + + /** + * Rebuilds the tree from the model, preserving full expansion. Rebuilding + * replaces every tree node, which would otherwise drop the current + * selection on every update (a client talking, a group change, …); the + * previously selected channel/client is restored by identity once the new + * nodes are in place, so a selection sticks until the user changes it. + */ + public void rebuild() { + Object selected = selectedUserObject(); + rebuilding = true; + try { + root.setUserObject(model.getServerName()); + root.removeAllChildren(); + List roots = model.buildTree(); + boolean filtering = search.isFiltering(); + for (ChannelNode c : roots) { + DefaultMutableTreeNode node = buildChannel(c, filtering); + if (node != null) root.add(node); + } + treeModel.reload(); + expandOpenChannels(root, new TreePath(root)); + if (selected != null) { + TreePath path = pathOf(selected); + if (path != null) tree.setSelectionPath(path); + } + } finally { + rebuilding = false; + } + // The selection listener was swallowed above; tell the caller only if it actually changed + // (e.g. the previously selected channel/client is gone), since it already knows the rest. + Object nowSelected = selectedUserObject(); + if (nowSelected != selected) actions.onSelectionChanged(nowSelected); + search.treeRebuilt(); + } + + /** + * Opens {@code node} and every channel below it, except the ones the user collapsed and + * whatever is below those. While the find bar filters, everything opens, so every match shows. + */ + private void expandOpenChannels(DefaultMutableTreeNode node, TreePath path) { + tree.expandPath(path); + boolean filtering = search.isFiltering(); + for (int i = 0; i < node.getChildCount(); i++) { + DefaultMutableTreeNode child = (DefaultMutableTreeNode) node.getChildAt(i); + if (child.isLeaf() || !(child.getUserObject() instanceof ChannelNode)) continue; + if (!filtering && collapsedChannels.contains(((ChannelNode) child.getUserObject()).id)) continue; + expandOpenChannels(child, path.pathByAddingChild(child)); + } + } + + private Object selectedUserObject() { + TreePath path = tree.getSelectionPath(); + return path == null ? null : ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); + } + + /** + * @param filtering keep only what the find bar matched: a matching channel with its + * clients, a matching client, and the channels leading to either + * @return the channel's node, or {@code null} when filtering left nothing of it + */ + private DefaultMutableTreeNode buildChannel(ChannelNode c, boolean filtering) { + DefaultMutableTreeNode node = new DefaultMutableTreeNode(c); + boolean channelMatches = filtering && search.matches(c); + for (ClientEntry client : c.clients) { + if (!filtering || channelMatches || search.matches(client)) node.add(new DefaultMutableTreeNode(client)); + } + for (ChannelNode child : c.children) { + DefaultMutableTreeNode childNode = buildChannel(child, filtering); + if (childNode != null) node.add(childNode); + } + return !filtering || channelMatches || node.getChildCount() > 0 ? node : null; + } + + /** Clears the tree back to the disconnected placeholder state. */ + public void showDisconnected() { + root.setUserObject("Not connected"); + root.removeAllChildren(); + collapsedChannels.clear(); + treeModel.reload(); + search.treeRebuilt(); + } + + /** Repaint only (e.g. talk-state changes) without rebuilding structure. */ + public void refreshVisual() { + tree.repaint(); + } + + /** + * Re-measures every visible row, for changes that alter a row's width (a group + * icon that finished downloading). A plain repaint would keep the cached widths + * and clip the new icons. + */ + public void refreshRowSizes() { + for (int i = tree.getRowCount() - 1; i >= 0; i--) { + TreePath path = tree.getPathForRow(i); + if (path != null) { + treeModel.nodeChanged((DefaultMutableTreeNode) path.getLastPathComponent()); + } + } + } + +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreeSearch.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreeSearch.java new file mode 100644 index 0000000..4285cb3 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreeSearch.java @@ -0,0 +1,233 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.contacts.Contact; +import eu.lixko.ts3j.client.contacts.ContactStore; +import eu.lixko.ts3j.client.net.ChannelNode; +import eu.lixko.ts3j.client.net.ClientEntry; +import eu.lixko.ts3j.client.net.TreeMatch; +import eu.lixko.ts3j.client.text.TextQuery; + +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JToggleButton; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.TreePath; +import java.awt.Dimension; +import java.awt.Insets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Set; + +/** + * Find in the server tree: looks for clients or for channels by name, washes every + * matching row and selects them one at a time. Optionally prunes the tree down to + * the matches (and the channels leading to them). + */ +final class ServerTreeSearch implements FindBar.Listener { + + private final DropIndicatorTree tree; + private final DefaultMutableTreeNode root; + private final ContactStore contacts; + /** Rebuilds the tree, which asks {@link #isFiltering()} and {@link #matches} what to keep. */ + private final Runnable rebuild; + + private final FindBar bar = new FindBar(this); + private boolean searchChannels; + /** Switches between finding clients and finding channels, showing the kind it finds. */ + private final JButton scope = new JButton() { + @Override + public Icon getIcon() { + return searchChannels ? Icons.channel(true) : Icons.clientIdle(); + } + + /** Sized for the wider of both icons, so the field beside it stays put on a switch. */ + @Override + public Dimension getPreferredSize() { + Icon client = Icons.clientIdle(); + Icon channel = Icons.channel(true); + Insets in = getInsets(); + return new Dimension(Math.max(client.getIconWidth(), channel.getIconWidth()) + in.left + in.right, + Math.max(client.getIconHeight(), channel.getIconHeight()) + in.top + in.bottom); + } + + @Override + public Dimension getMaximumSize() { + return getPreferredSize(); + } + }; + private final JToggleButton onlyMatching; + + private TextQuery query = TextQuery.EMPTY; + private boolean filtering; + /** Matching rows in tree order. */ + private final List hits = new ArrayList<>(); + + ServerTreeSearch(DropIndicatorTree tree, DefaultMutableTreeNode root, ContactStore contacts, Runnable rebuild) { + this.tree = tree; + this.root = root; + this.contacts = contacts; + this.rebuild = rebuild; + scope.addActionListener(e -> { + searchChannels = !searchChannels; + scopeChanged(); + }); + bar.addLeading(scope); + onlyMatching = bar.addFilterToggle("Show only matches"); + bar.addResettable(() -> !searchChannels, () -> { + searchChannels = false; + showScope(); + }); + showScope(); + } + + FindBar bar() { + return bar; + } + + void open() { + bar.open(); + } + + /** Whether the tree should hold only matches and the channels leading to them. */ + boolean isFiltering() { + return filtering; + } + + /** Whether a channel or client row matches the current query in the current scope. */ + boolean matches(Object node) { + if (query.isEmpty()) return false; + if (node instanceof ClientEntry c) { + if (searchChannels) return false; + Contact contact = contacts.find(c.uniqueId); + return TreeMatch.client(query, c.nickname, contact != null ? contact.displayName(c.nickname) : null); + } + if (node instanceof ChannelNode ch) return searchChannels && TreeMatch.channel(query, ch.name); + return false; + } + + /** The tree was rebuilt from the model: its rows (and so the matches) may have changed. */ + void treeRebuilt() { + if (!bar.isOpen()) return; + collectHits(); + updateStatus(); + } + + private void scopeChanged() { + showScope(); + if (bar.isOpen()) bar.fireQueryChanged(); + } + + private void showScope() { + scope.setToolTipText(searchChannels ? "Finding channels — click to find clients" + : "Finding clients — click to find channels"); + scope.repaint(); + bar.setPlaceholder(searchChannels ? "Find channels" : "Find clients"); + } + + @Override + public void queryChanged(TextQuery q) { + query = q.isInvalid() ? TextQuery.EMPTY : q; + boolean filter = onlyMatching.isSelected() && !query.isEmpty(); + if (filter || filtering) { + filtering = filter; + rebuild.run(); + } + collectHits(); + if (!hits.isEmpty()) select(hits.get(0)); + updateStatus(); + } + + @Override + public void next() { + step(true); + } + + @Override + public void previous() { + step(false); + } + + @Override + public void closed() { + query = TextQuery.EMPTY; + hits.clear(); + tree.setSearchHits(Collections.emptySet()); + if (filtering) { + filtering = false; + rebuild.run(); + } + TreePath selected = tree.getSelectionPath(); + if (selected != null) tree.scrollPathToVisible(selected); + tree.requestFocusInWindow(); + } + + /** Moves to the match after (or before) the selected row, wrapping around. */ + private void step(boolean forward) { + if (hits.isEmpty()) return; + List order = preorder(); + int at = order.indexOf(selectedNode()); + DefaultMutableTreeNode target = null; + if (forward) { + for (DefaultMutableTreeNode hit : hits) { + if (order.indexOf(hit) > at) { + target = hit; + break; + } + } + if (target == null) target = hits.get(0); + } else { + for (int i = hits.size() - 1; i >= 0; i--) { + if (at < 0 || order.indexOf(hits.get(i)) < at) { + target = hits.get(i); + break; + } + } + if (target == null) target = hits.get(hits.size() - 1); + } + select(target); + updateStatus(); + } + + private void select(DefaultMutableTreeNode node) { + TreePath path = new TreePath(node.getPath()); + tree.setSelectionPath(path); + tree.scrollPathToVisible(path); + } + + private void collectHits() { + hits.clear(); + Set washed = Collections.newSetFromMap(new IdentityHashMap<>()); + for (DefaultMutableTreeNode n : preorder()) { + if (matches(n.getUserObject())) { + hits.add(n); + washed.add(n.getUserObject()); + } + } + tree.setSearchHits(washed); + } + + private void updateStatus() { + if (query.isEmpty()) { + if (!bar.query().isInvalid()) bar.clearCount(); + bar.setNavigable(false); + return; + } + bar.setNavigable(hits.size() > 1 || (hits.size() == 1 && hits.get(0) != selectedNode())); + bar.setCount(hits.indexOf(selectedNode()) + 1, hits.size(), false); + } + + private DefaultMutableTreeNode selectedNode() { + TreePath path = tree.getSelectionPath(); + return path == null ? null : (DefaultMutableTreeNode) path.getLastPathComponent(); + } + + private List preorder() { + List out = new ArrayList<>(); + Enumeration e = root.preorderEnumeration(); + while (e.hasMoreElements()) out.add((DefaultMutableTreeNode) e.nextElement()); + return out; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/SettingsDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/SettingsDialog.java new file mode 100644 index 0000000..3eae68d --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/SettingsDialog.java @@ -0,0 +1,224 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.audio.AudioBackend; +import eu.lixko.ts3j.client.audio.OpusParameters; +import eu.lixko.ts3j.client.audio.VoiceInput; +import eu.lixko.ts3j.client.audio.VoiceOutput; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.sound.SoundNotifier; + +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.ScrollPaneConstants; +import javax.swing.SwingUtilities; +import java.awt.BorderLayout; +import java.awt.CardLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.List; + +/** + * Options dialog, laid out like TS3's: a sidebar of pages on the left, the chosen page + * on the right, OK/Cancel/Apply below. Each page owns its controls and + * writes {@link Settings} when applied; this class wires the audio pages, which preview + * themselves live against the running audio subsystem, and owns the apply plumbing. + */ +public final class SettingsDialog extends JDialog { + + /** The page the dialog was last left on, to reopen there. */ + private static int lastPage; + + private final Settings settings; + private final VoiceOutput livePlayback; + private final Runnable onApply; + + private final ApplicationPanel applicationPanel; + private final PlaybackPanel playbackPanel; + private final CapturePanel capturePanel; + private final NetworkPanel networkPanel; + private final NotificationsPanel notificationsPanel; + private final DesignPanel designPanel; + private final HotkeysPanel hotkeysPanel; + private final ContactsPanel contactsPanel; + private final ChatLogsPanel chatLogsPanel; + + public SettingsDialog(Frame owner, Settings settings, AudioBackend audio, + VoiceInput liveMic, VoiceOutput livePlayback, + SoundNotifier sounds, HotkeyService hotkeys, MyTeamSpeakPanel myTeamSpeak, + Runnable onApply) { + super(owner, "Options", true); + this.settings = settings; + this.livePlayback = livePlayback; + this.onApply = onApply; + + applicationPanel = new ApplicationPanel(settings); + hotkeysPanel = new HotkeysPanel(hotkeys); + Runnable pushEncoder = () -> { + if (liveMic != null) liveMic.setOpusParameters(OpusParameters.from(audioSnapshot())); + }; + capturePanel = new CapturePanel(settings, audio, liveMic, hotkeys, hotkeysPanel, this::audioSnapshot); + networkPanel = new NetworkPanel(settings, liveMic, pushEncoder); + playbackPanel = new PlaybackPanel(settings, audio.io(), livePlayback, sounds, + capturePanel::setTestOutputDevice); + notificationsPanel = new NotificationsPanel(settings, sounds); + designPanel = new DesignPanel(settings); + contactsPanel = new ContactsPanel(settings); + chatLogsPanel = new ChatLogsPanel(settings); + + List pages = List.of( + new OptionsPage("Application", scrollable(applicationPanel), "SETTINGS"), + new OptionsPage("myTeamSpeak", myTeamSpeak, "MYTS_ACCOUNT"), + new OptionsPage("Playback", scrollable(playbackPanel), "PLAYBACK"), + new OptionsPage("Capture", scrollable(capturePanel), "CAPTURE"), + new OptionsPage("Network", scrollable(networkPanel), "PING_4"), + new OptionsPage("Design", designPanel, "GUISETUP", "CHANNEL_EDIT"), + new OptionsPage("Hotkeys", hotkeysPanel, "HOTKEYS"), + new OptionsPage("Contacts", scrollable(contactsPanel), "CONTACT", "EDIT_FRIEND_FOE_STATUS"), + new OptionsPage("Chat", scrollable(chatLogsPanel), "CHANNEL_CHAT", "PLAYER_CHAT"), + new OptionsPage("Notifications", notificationsPanel, "NOTIFICATIONS")); + + CardLayout cards = new CardLayout(); + JPanel content = new JPanel(cards); + for (OptionsPage page : pages) content.add(page.content(), page.title()); + + OptionsSidebar sidebar = new OptionsSidebar(pages); + sidebar.addListSelectionListener(e -> { + OptionsPage page = sidebar.getSelectedValue(); + if (page == null) return; + cards.show(content, page.title()); + lastPage = sidebar.getSelectedIndex(); + }); + sidebar.setSelectedIndex(Math.min(lastPage, pages.size() - 1)); + JScrollPane sidebarScroll = new JScrollPane(sidebar, + ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + + JPanel body = new JPanel(new BorderLayout(UIScale.scale(8), 0)); + body.setBorder(new ScaledEmptyBorder(10, 10, 0, 10)); + body.add(sidebarScroll, BorderLayout.WEST); + body.add(content, BorderLayout.CENTER); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(body, BorderLayout.CENTER); + getContentPane().add(buildButtons(), BorderLayout.SOUTH); + + Runnable iconsChanged = () -> SwingUtilities.invokeLater(sidebar::repaint); + IconTheme.get().addListener(iconsChanged); + + // The microphone test hears typing too, so typing attenuation can be tried out here. + Runnable testKeyPress = () -> SwingUtilities.invokeLater( + () -> capturePanel.applyLive(VoiceInput::keyPressed)); + hotkeys.addKeyPressListener(testKeyPress); + + Dialogs.closeOnEscape(this, this::cancel); + setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + cancel(); + } + + @Override + public void windowClosed(WindowEvent e) { + hotkeys.removeKeyPressListener(testKeyPress); + IconTheme.get().removeListener(iconsChanged); + capturePanel.stopTest(); + } + }); + + pack(); + setSize(UIScale.scale(new Dimension(900, 620))); + setMinimumSize(UIScale.scale(new Dimension(640, 440))); + setLocationRelativeTo(owner); + } + + private JComponent buildButtons() { + JButton ok = new JButton("OK"); + JButton cancel = new JButton("Cancel"); + JButton apply = new JButton("Apply"); + ok.addActionListener(e -> { + apply(); + close(); + }); + cancel.addActionListener(e -> cancel()); + apply.addActionListener(e -> apply()); + + JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT, UIScale.scale(6), 0)); + buttons.setBorder(new ScaledEmptyBorder(10, 10, 10, 10)); + buttons.add(ok); + buttons.add(cancel); + buttons.add(apply); + getRootPane().setDefaultButton(ok); + return buttons; + } + + private static JScrollPane scrollable(JPanel content) { + JScrollPane sp = new JScrollPane(content, + ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + sp.setBorder(null); + sp.getVerticalScrollBar().setUnitIncrement(16); + return sp; + } + + /** Copies the audio pages into {@code target}, without touching anything else. */ + private void writeAudioSettings(Settings target) { + playbackPanel.writeInto(target); + capturePanel.writeInto(target); + networkPanel.writeInto(target); + } + + /** + * The audio pages as a standalone {@link Settings}, so the microphone test chain runs + * with the values currently on screen rather than the ones last saved. + * + *

    The test always runs voice activation: it exists to tune the gate, and push-to-talk + * would need the global hotkey, which belongs to the connected microphone. + */ + private Settings audioSnapshot() { + Settings snapshot = new Settings(); + snapshot.packetLoss = settings.packetLoss; + writeAudioSettings(snapshot); + if (snapshot.inputMode == Settings.InputMode.PUSH_TO_TALK) { + snapshot.inputMode = Settings.InputMode.VOICE_ACTIVATION; + } + return snapshot; + } + + private void apply() { + writeAudioSettings(settings); + applicationPanel.apply(); + notificationsPanel.apply(); + designPanel.apply(); + contactsPanel.apply(); + chatLogsPanel.apply(); + hotkeysPanel.apply(); + settings.save(); + + capturePanel.applyLive(m -> m.apply(settings)); + if (livePlayback != null) { + livePlayback.setMasterVolume(settings.outputVolume); + livePlayback.setOutputDevice(settings.outputDevice); + } + if (onApply != null) onApply.run(); + } + + /** Leaves without applying, putting back the settings that preview themselves live. */ + private void cancel() { + notificationsPanel.revert(); + designPanel.revert(); + close(); + } + + private void close() { + capturePanel.stopTest(); + dispose(); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/Spinners.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/Spinners.java new file mode 100644 index 0000000..6801ee5 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/Spinners.java @@ -0,0 +1,29 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.UIScale; + +import javax.swing.JSpinner; +import java.awt.Dimension; + +/** Shared shaping for the numeric spinners the channel editor is full of. */ +final class Spinners { + + /** Width that fits a five-digit power without swallowing the rest of a form row. */ + private static final int WIDTH = 80; + + private Spinners() { + } + + /** + * Keeps a spinner to a sensible width and drops the grouping separator: these hold + * permission powers and client counts, which TeamSpeak shows as plain numbers. + */ + static JSpinner compact(JSpinner spinner) { + JSpinner.NumberEditor editor = new JSpinner.NumberEditor(spinner, "#"); + spinner.setEditor(editor); + Dimension size = new Dimension(UIScale.scale(WIDTH), spinner.getPreferredSize().height); + spinner.setPreferredSize(size); + spinner.setMaximumSize(size); + return spinner; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/StatusBar.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/StatusBar.java new file mode 100644 index 0000000..dfed98b --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/StatusBar.java @@ -0,0 +1,82 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; + +import javax.swing.JLabel; +import javax.swing.JPanel; +import java.awt.BorderLayout; +import java.awt.Cursor; +import java.awt.FlowLayout; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +/** + * The strip at the bottom of the window: connection status on the left, codec info on the + * right, and while the server on screen is being recorded, a label that stops it. An envelope + * shows while that server holds unread offline messages for us, and opens them. + */ +final class StatusBar extends JPanel { + + private final JLabel statusLabel = new JLabel("Not connected"); + private final JLabel codecLabel = new JLabel(); + private final JLabel recordingLabel = new JLabel("Recording", Icons.of("RECORDING_STOP"), JLabel.LEADING); + private final JLabel unreadLabel = new JLabel(Icons.of("OFFLINE_MESSAGES")); + + StatusBar(Runnable onStopRecording, Runnable onOpenOfflineMessages) { + super(new BorderLayout()); + setBackground(Theme.statusBg()); + setBorder(new ScaledEmptyBorder(3, 8, 3, 8)); + statusLabel.setFont(Theme.uiFont()); + codecLabel.setFont(Theme.uiFont()); + codecLabel.setForeground(Theme.chatSystem()); + recordingLabel.setFont(Theme.uiFont()); + recordingLabel.setToolTipText("Stop Recording"); + recordingLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + recordingLabel.setVisible(false); + recordingLabel.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + onStopRecording.run(); + } + }); + unreadLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + unreadLabel.setVisible(false); + unreadLabel.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + onOpenOfflineMessages.run(); + } + }); + JPanel east = new JPanel(new FlowLayout(FlowLayout.TRAILING, UIScale.scale(12), 0)); + east.setOpaque(false); + east.add(unreadLabel); + east.add(recordingLabel); + east.add(codecLabel); + // In the centre, a long status is cut short rather than drawn over the labels beside it. + add(statusLabel, BorderLayout.CENTER); + add(east, BorderLayout.EAST); + } + + void showRecording(boolean recording) { + recordingLabel.setVisible(recording); + } + + void showUnreadMessages(int unread) { + unreadLabel.setVisible(unread > 0); + unreadLabel.setToolTipText("

    You have " + unread + " unread " + + (unread == 1 ? "offline message" : "offline messages") + "

    "); + } + + void setStatus(String text) { + statusLabel.setText(text); + } + + void setCodec(String text) { + codecLabel.setText(text); + } + + String codecText() { + return codecLabel.getText(); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/TabDragReorder.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/TabDragReorder.java new file mode 100644 index 0000000..e9614d1 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/TabDragReorder.java @@ -0,0 +1,285 @@ +package eu.lixko.ts3j.client.ui; + +import javax.swing.JComponent; +import javax.swing.JRootPane; +import javax.swing.JTabbedPane; +import javax.swing.SwingUtilities; +import javax.swing.Timer; +import java.awt.AlphaComposite; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.image.BufferedImage; +import java.util.ArrayList; +import java.util.List; + +/** + * Lets the user reorder a {@link JTabbedPane}'s tabs by dragging one sideways over + * another, browser-tab style. Snapshots of every tab are drawn on the window's + * glass pane: the dragged one follows the cursor's X only (its Y stays put, and it + * can't leave the strip) and stays drawn on top; it swaps with whichever neighbour + * it reaches the midpoint of. The real tab model is only updated once, when the + * mouse is released, and the overlay eases into its final position on top of it. + * + *

    Swing delivers drag events only to whichever component originally got the + * press, so every component that should start a drag — the tab strip itself + * and each custom tab label — must be {@link #attach}ed individually. + */ +final class TabDragReorder { + + /** Moves the tab at {@code from} to sit where {@code to} currently is. */ + interface Reorder { + void moveTab(int from, int to); + } + + /** Below this many pixels of movement, a press is treated as a click, not a drag. */ + private static final int THRESHOLD = 5; + private static final double EASE = 0.35; + private static final double SETTLE_EPSILON = 0.5; + private static final int FRAME_MS = 15; + + private final JTabbedPane tabbed; + private final Reorder reorder; + + private int pressSlot = -1; + private Point pressPoint; + private boolean dragging; + private boolean releasing; + + private Overlay overlay; + private List order; + private Tile draggedTile; + private int dragSlot; + private int startSlot; + private int stripStartX; + private int stripWidth; + private int grabDx; + private Timer timer; + + TabDragReorder(JTabbedPane tabbed, Reorder reorder) { + this.tabbed = tabbed; + this.reorder = reorder; + } + + void attach(JComponent source) { + MouseAdapter listener = new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + Point inTabbed = SwingUtilities.convertPoint(e.getComponent(), e.getPoint(), tabbed); + pressSlot = tabbed.indexAtLocation(inTabbed.x, inTabbed.y); + pressPoint = inTabbed; + dragging = false; + } + + @Override + public void mouseDragged(MouseEvent e) { + if (pressSlot < 0) return; + Point inTabbed = SwingUtilities.convertPoint(e.getComponent(), e.getPoint(), tabbed); + if (!dragging) { + if (pressPoint.distance(inTabbed) < THRESHOLD) return; + dragging = beginDrag(inTabbed); + if (!dragging) return; + } + dragTo(inTabbed.x); + } + + @Override + public void mouseReleased(MouseEvent e) { + if (dragging) endDrag(); + // A custom tab component swallows the press, so the tabbed pane never gets + // to select the tab itself — a plain click has to do it here. + else if (pressSlot >= 0 && pressSlot < tabbed.getTabCount() + && SwingUtilities.isLeftMouseButton(e)) { + tabbed.setSelectedIndex(pressSlot); + } + pressSlot = -1; + dragging = false; + } + }; + source.addMouseListener(listener); + source.addMouseMotionListener(listener); + } + + /** Snapshots every tab and shows them on the glass pane in place of the real strip. */ + private boolean beginDrag(Point inTabbed) { + JRootPane root = tabbed.getRootPane(); + int n = tabbed.getTabCount(); + if (root == null || pressSlot < 0 || pressSlot >= n) return false; + + order = new ArrayList<>(n); + for (int i = 0; i < n; i++) { + Rectangle b = tabbed.getBoundsAt(i); + if (b == null || b.isEmpty()) return false; + order.add(new Tile(snapshot(b), b.x, b.y, b.width, b.height)); + } + stripStartX = order.get(0).x; + stripWidth = 0; + for (Tile t : order) stripWidth += t.width; + draggedTile = order.get(pressSlot); + dragSlot = pressSlot; + startSlot = pressSlot; + grabDx = inTabbed.x - draggedTile.x; + releasing = false; + + if (!(root.getGlassPane() instanceof Overlay)) { + root.setGlassPane(new Overlay()); + } + overlay = (Overlay) root.getGlassPane(); + overlay.origin = SwingUtilities.convertPoint(tabbed, new Point(0, 0), overlay); + overlay.tiles = order; + overlay.onTop = draggedTile; + overlay.setVisible(true); + overlay.repaint(); + + timer = new Timer(FRAME_MS, e -> tick()); + timer.start(); + return true; + } + + private BufferedImage snapshot(Rectangle bounds) { + BufferedImage img = new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_ARGB); + Graphics2D g = img.createGraphics(); + g.setClip(0, 0, bounds.width, bounds.height); + g.translate(-bounds.x, -bounds.y); + tabbed.paint(g); + g.dispose(); + return img; + } + + /** + * Swaps the dragged tile with whichever neighbour it has reached the midpoint + * of: its trailing edge past the next tile's midpoint when moving right, or its + * leading edge past the previous tile's midpoint when moving left. Checked + * against the neighbour's target slot rather than its live position, since that + * may itself still be mid-animation. + */ + private void dragTo(int cursorX) { + int min = stripStartX; + int max = stripStartX + stripWidth - draggedTile.width; + draggedTile.currentX = Math.max(min, Math.min(max, cursorX - grabDx)); + + if (dragSlot + 1 < order.size()) { + Tile next = order.get(dragSlot + 1); + double rightEdge = draggedTile.currentX + draggedTile.width; + if (rightEdge > next.targetX + next.width / 2.0) { + swap(dragSlot, dragSlot + 1); + return; + } + } + if (dragSlot - 1 >= 0) { + Tile prev = order.get(dragSlot - 1); + double leftEdge = draggedTile.currentX; + if (leftEdge < prev.targetX + prev.width / 2.0) { + swap(dragSlot - 1, dragSlot); + } + } + } + + /** Swaps the two adjacent slots {@code a} and {@code b} (one of them the dragged tile's) in {@link #order}, not the real tab model. */ + private void swap(int a, int b) { + int newSlot = dragSlot == a ? b : a; + order.remove(draggedTile); + order.add(newSlot, draggedTile); + dragSlot = newSlot; + retarget(false); + } + + /** Assigns each tile's slot target from the current {@code order}; the dragged tile follows the cursor instead, unless {@code includeDragged}. */ + private void retarget(boolean includeDragged) { + double x = stripStartX; + for (Tile t : order) { + if (t != draggedTile || includeDragged) t.targetX = x; + x += t.width; + } + } + + /** + * Commits the reorder to the real tab model in one shot. Doing this once here, + * rather than per swap while dragging, matters because reordering the real + * model can rebuild tab components (new labels, new listeners), which would + * otherwise yank the component out from under an in-flight mouse grab. + */ + private void endDrag() { + releasing = true; + if (dragSlot != startSlot) reorder.moveTab(startSlot, dragSlot); + retarget(true); + } + + private void tick() { + boolean settled = true; + for (Tile t : order) { + if (t == draggedTile && !releasing) continue; + double diff = t.targetX - t.currentX; + if (Math.abs(diff) < SETTLE_EPSILON) { + t.currentX = t.targetX; + } else { + t.currentX += diff * EASE; + settled = false; + } + } + overlay.repaint(); + if (releasing && settled) { + timer.stop(); + overlay.tiles = null; + overlay.onTop = null; + overlay.setVisible(false); + order = null; + draggedTile = null; + } + } + + /** One tab's snapshot, animating from {@link #currentX} toward {@link #targetX}. */ + private static final class Tile { + final BufferedImage image; + final int x, y, width, height; + double currentX; + double targetX; + + Tile(BufferedImage image, int x, int y, int width, int height) { + this.image = image; + this.x = x; + this.y = y; + this.width = width; + this.height = height; + this.currentX = x; + this.targetX = x; + } + } + + /** A transparent overlay on the glass pane that paints every tab's animated snapshot. */ + private static final class Overlay extends JComponent { + List tiles; + /** Painted last (on top) so it stays above tabs it's currently overlapping while dragged. */ + Tile onTop; + Point origin = new Point(); + + Overlay() { + setOpaque(false); + } + + /** Never claims mouse events, so drags keep reaching the component that was actually pressed. */ + @Override + public boolean contains(int x, int y) { + return false; + } + + @Override + protected void paintComponent(Graphics g) { + if (tiles == null) return; + Graphics2D g2 = (Graphics2D) g.create(); + g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.9f)); + for (Tile t : tiles) { + if (t != onTop) draw(g2, t); + } + if (onTop != null) draw(g2, onTop); + g2.dispose(); + } + + private void draw(Graphics2D g2, Tile t) { + g2.drawImage(t.image, origin.x + (int) Math.round(t.currentX), origin.y + t.y, null); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/TextZoom.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/TextZoom.java new file mode 100644 index 0000000..9d66e64 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/TextZoom.java @@ -0,0 +1,109 @@ +package eu.lixko.ts3j.client.ui; + +import javax.swing.JEditorPane; +import javax.swing.JViewport; +import javax.swing.SwingUtilities; +import javax.swing.text.BadLocationException; +import javax.swing.text.Document; +import javax.swing.text.SimpleAttributeSet; +import javax.swing.text.StyledDocument; +import java.awt.Component; +import java.awt.Point; +import java.awt.event.MouseWheelEvent; +import java.util.Collections; +import java.util.Set; +import java.util.WeakHashMap; +import java.util.function.DoubleConsumer; + +/** + * A zoom level for the text and pictures of {@link HtmlStyles} panes, changed with + * Ctrl+mouse wheel over any of them and applied to all of them, in a browser's steps. + */ +final class TextZoom { + + private static final double[] LEVELS = {0.5, 0.67, 0.75, 0.8, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3}; + + private final Set panes = Collections.newSetFromMap(new WeakHashMap<>()); + private final DoubleConsumer onChange; + private double factor; + + /** @param onChange told the new factor after every change, e.g. to save it */ + TextZoom(double factor, DoubleConsumer onChange) { + this.factor = nearestLevel(factor); + this.onChange = onChange; + } + + /** The zoom of {@code c}, an {@link HtmlStyles} pane, or 1 if it has none. */ + static float of(Component c) { + return c instanceof JEditorPane pane && pane.getClientProperty(TextZoom.class) instanceof TextZoom zoom + ? (float) zoom.factor : 1f; + } + + /** Zooms {@code pane} with this zoom, and lets Ctrl+wheel over it change it. */ + void attach(JEditorPane pane) { + if (pane.getClientProperty(TextZoom.class) == this) return; + pane.putClientProperty(TextZoom.class, this); + panes.add(pane); + pane.addMouseWheelListener(e -> onWheel(pane, e)); + if (factor != 1) relayout(pane); + } + + private void onWheel(JEditorPane pane, MouseWheelEvent e) { + if (!e.isControlDown()) { + // Listening for the wheel takes it from the scroll pane, so hand plain scrolling on. + Component parent = pane.getParent(); + if (parent != null) parent.dispatchEvent(SwingUtilities.convertMouseEvent(pane, e, parent)); + return; + } + e.consume(); + if (e.getWheelRotation() != 0) step(e.getWheelRotation() < 0 ? 1 : -1); + } + + private void step(int direction) { + int i = indexOf(factor); + int next = Math.max(0, Math.min(LEVELS.length - 1, i + direction)); + if (next == i) return; + factor = LEVELS[next]; + for (JEditorPane pane : panes) relayout(pane); + onChange.accept(factor); + } + + /** Lays {@code pane} out again at the new size, keeping the same text in view. */ + private static void relayout(JEditorPane pane) { + Document doc = pane.getDocument(); + if (!(doc instanceof StyledDocument styled) || doc.getLength() == 0) return; + // An empty change over everything makes every view fetch its font and size again. + if (!(pane.getParent() instanceof JViewport viewport)) { + styled.setCharacterAttributes(0, doc.getLength(), new SimpleAttributeSet(), false); + return; + } + + Point top = viewport.getViewPosition(); + boolean atEnd = top.y + viewport.getExtentSize().height >= pane.getHeight(); + int anchor = pane.viewToModel2D(top); + styled.setCharacterAttributes(0, doc.getLength(), new SimpleAttributeSet(), false); + viewport.getParent().validate(); + int max = Math.max(0, pane.getHeight() - viewport.getExtentSize().height); + int y = max; + if (!atEnd) { + try { + y = Math.min(max, pane.modelToView2D(anchor).getBounds().y); + } catch (BadLocationException ignored) { + // Cannot happen: the text has not changed, only its size. + } + } + viewport.setViewPosition(new Point(top.x, y)); + } + + private static double nearestLevel(double factor) { + return LEVELS[indexOf(factor)]; + } + + private static int indexOf(double factor) { + int best = 0; + for (int i = 1; i < LEVELS.length; i++) { + if (Math.abs(LEVELS[i] - factor) < Math.abs(LEVELS[best] - factor)) best = i; + } + return best; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/Theme.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/Theme.java new file mode 100644 index 0000000..d8763d2 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/Theme.java @@ -0,0 +1,183 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.ui.FlatUIUtils; +import com.formdev.flatlaf.util.UIScale; + +import javax.swing.UIManager; +import java.awt.Color; +import java.awt.Font; + +/** + * The palette and fonts the client paints with, on top of the active look-and-feel. + * + *

    Surfaces (window, tree, chat background) and fonts come straight from the + * look-and-feel, so the client follows whatever FlatLaf theme is installed. The + * status colours TeamSpeak gives meaning to — talking, away, muted, channel and + * server names — are ours, in a light and a dark variant; {@link #refresh()} picks + * the variant matching the installed theme. + */ +public final class Theme { + + private static boolean dark; + + private Theme() { + } + + /** Re-reads the installed look-and-feel; call after changing it. */ + static void refresh() { + Color bg = UIManager.getColor("Panel.background"); + dark = bg != null && luminance(bg) < 0.5; + } + + public static boolean isDark() { + return dark; + } + + // ---- fonts ---- + + public static Font uiFont() { + Font f = UIManager.getFont("Label.font"); + return f != null ? f : new Font("SansSerif", Font.PLAIN, UIScale.scale(12)); + } + + public static Font uiBold() { + return uiFont().deriveFont(Font.BOLD); + } + + /** A notch below the UI font, for secondary labels. */ + public static Font uiSmall() { + Font f = uiFont(); + return f.deriveFont(Math.max(9f, f.getSize2D() - 2f)); + } + + // ---- surfaces, from the look-and-feel ---- + + public static Color windowBg() { + return ui("Panel.background", 0xF0F0F0, 0x282828); + } + + public static Color toolbarBg() { + return ui("ToolBar.background", 0xE6E9ED, 0x282828); + } + + public static Color statusBg() { + return windowBg(); + } + + public static Color treeBg() { + return ui("Tree.background", 0xFFFFFF, 0x1E1E1E); + } + + public static Color treeText() { + return ui("Tree.foreground", 0x1E1E1E, 0xE0E0E0); + } + + public static Color treeSelection() { + return ui("Tree.selectionBackground", 0xCFE3FB, 0x364B6F); + } + + /** + * Behind the row the pointer is over: the same wash the menu bar puts behind a hovered + * menu. The look-and-feel states it as a shift of whatever surface it sits on, and the + * menu bar resolves it against the window, so this does too — a row hover and a menu + * hover then carry the very same colour. + */ + public static Color hover() { + return FlatUIUtils.deriveColor(ui("MenuBar.hoverBackground", 0xE6E6E6, 0x3D3D3D), windowBg()); + } + + public static Color chatBg() { + return ui("TextPane.background", 0xFAFAFA, 0x1E1E1E); + } + + public static Color border() { + return ui("Component.borderColor", 0xD0D0D0, 0x3E3E3E); + } + + public static Color chatText() { + return ui("TextPane.foreground", 0x202020, 0xE0E0E0); + } + + /** Behind every match of a find bar's query. */ + public static Color searchMatch() { + return pick(0xFFEBA3, 0x5C4E1A); + } + + /** Behind the match a find bar is on. */ + public static Color searchCurrent() { + return pick(0xFFB84D, 0x9C6A12); + } + + // ---- status colours ---- + + public static Color channelText() { + return pick(0x21486B, 0xFFFFFF); + } + + /** The colour of a chat line about what happened on the server. */ + public static Color chatEvent() { + return pick(0x21486B, 0x8FBCE6); + } + + public static Color serverText() { + return pick(0x123456, 0xDCE8F5); + } + + public static Color talking() { + return pick(0x33B35A, 0x4CC479); + } + + public static Color idleClient() { + return pick(0x6E7B87, 0x9AA6B2); + } + + public static Color away() { + return pick(0xC98A1B, 0xE0A83C); + } + + public static Color muted() { + return pick(0xC0392B, 0xE05C4C); + } + + /** TeamSpeak's {@code CustomColor::ClientFriend}, lifted for the dark scheme. */ + public static Color friend() { + return pick(0x008000, 0x5CC96A); + } + + /** TeamSpeak's {@code CustomColor::ClientBlocked}, lifted for the dark scheme. */ + public static Color blocked() { + return pick(0xFF0000, 0xF06A5E); + } + + public static Color accent() { + return pick(0x2C7BE5, 0x5C9BEE); + } + + public static Color chatSystem() { + return pick(0x8A8A8A, 0x9A9A9A); + } + + public static Color chatName() { + return accent(); + } + + /** Links that leave the client, distinct from the colour used for identities. */ + public static Color link() { + return pick(0x1A5FB4, 0x6EA8FF); + } + + private static Color pick(int light, int darkRgb) { + return new Color(dark ? darkRgb : light); + } + + private static Color ui(String key, int lightFallback, int darkFallback) { + // Returned as the look-and-feel's own UIResource colour, so components painted with + // it are recoloured automatically when the look-and-feel is switched. + Color c = UIManager.getColor(key); + return c != null ? c : pick(lightFallback, darkFallback); + } + + private static double luminance(Color c) { + return (0.2126 * c.getRed() + 0.7152 * c.getGreen() + 0.0722 * c.getBlue()) / 255.0; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/TrayController.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/TrayController.java new file mode 100644 index 0000000..6aa7c36 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/TrayController.java @@ -0,0 +1,253 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.session.SelfState; +import eu.lixko.ts3j.client.ui.tray.AwtTray; +import eu.lixko.ts3j.client.ui.tray.TrayBackend; +import eu.lixko.ts3j.client.ui.tray.X11Tray; + +import javax.swing.ImageIcon; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JMenuItem; +import javax.swing.JPopupMenu; +import javax.swing.KeyStroke; +import javax.swing.SwingUtilities; +import javax.swing.event.PopupMenuEvent; +import javax.swing.event.PopupMenuListener; +import java.awt.Frame; +import java.awt.Image; +import java.awt.MenuItem; +import java.awt.PopupMenu; +import java.awt.Window; +import java.awt.event.KeyEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.function.IntFunction; + +/** + * The system tray icon. It shows the local client's state on the active server — + * the same badge the tree draws next to a nickname, so it turns green while + * speaking and into the muted microphone or speaker when muted — and brings the + * window back to the front when clicked. + * + *

    The icon is docked by {@link X11Tray} where the panel can show a transparent + * one, and by {@link AwtTray} everywhere else. On a desktop with no tray at all + * nothing is installed and every call here is a no-op. + */ +final class TrayController { + + private final MainFrame frame; + private final Runnable onQuit; + + private final TrayBackend tray; + + /** What is on screen now, so repeated updates don't touch the tray. */ + private SelfState state; + private String tooltip = ""; + + /** The context menu while it is on screen, and the window it hangs off. */ + private JPopupMenu openMenu; + private JDialog openAnchor; + + TrayController(MainFrame frame, Runnable onQuit) { + this.frame = frame; + this.onQuit = onQuit; + this.tray = install(); + } + + /** What happened when the icon was installed, for the diagnostics in the chat log. */ + String status() { + return tray == null + ? "System tray: no icon could be installed (run with -Dts3j.tray.debug=true for why)." + : "System tray: " + tray.description() + "."; + } + + /** @return the backend that took the icon, or {@code null} when none could */ + private TrayBackend install() { + TrayBackend.Listener listener = new TrayBackend.Listener() { + @Override + public void activated() { + SwingUtilities.invokeLater(TrayController.this::show); + } + + @Override + public void menuRequested(int x, int y) { + SwingUtilities.invokeLater(() -> showMenu(x, y)); + } + }; + // -Dts3j.tray=awt|x11 pins the backend; by default the transparent one is + // tried first and AWT's picks up whatever it leaves. + String choice = System.getProperty("ts3j.tray", "auto"); + IntFunction initial = size -> icon(SelfState.DISCONNECTED, size).getImage(); + TrayBackend backend = choice.equals("awt") ? null : X11Tray.create(listener, initial); + if (backend == null && !choice.equals("x11")) { + backend = AwtTray.create(listener, buildAwtMenu(), initial); + } + return backend; + } + + /** Shows the state of the given server, named by {@code serverName} in the tooltip. */ + void update(SelfState newState, String serverName) { + if (tray == null) return; + String newTooltip = "TeamSpook TS3j — " + (serverName == null || serverName.isBlank() + ? newState.label() + : serverName + ": " + newState.label()); + if (newState == state && newTooltip.equals(tooltip)) return; + state = newState; + tooltip = newTooltip; + tray.setIcon(size -> icon(newState, size).getImage()); + tray.setTooltip(newTooltip); + } + + /** Redraws after the icon pack changed. */ + void refreshIcon() { + if (tray == null || state == null) return; + SelfState current = state; + tray.setIcon(size -> icon(current, size).getImage()); + } + + void dispose() { + if (tray != null) tray.dispose(); + } + + /** The backend that took the icon, or {@code null} when none could. */ + TrayBackend backend() { + return tray; + } + + /** The icon a state is drawn with, from the active icon pack. */ + private static ImageIcon icon(SelfState state, int size) { + return switch (state) { + case DISCONNECTED -> Icons.app(size); + case DEAFENED -> Icons.speakerMuted(size); + case MIC_MUTED -> Icons.micMuted(size); + case MIC_LOCAL_MUTED -> Icons.micLocalMuted(size); + case AWAY -> Icons.clientAway(size); + case COMMANDER_TALKING -> Icons.clientCommanderTalking(size); + case COMMANDER -> Icons.clientCommander(size); + case TALKING -> Icons.clientTalking(size); + case IDLE -> Icons.clientIdle(size); + }; + } + + // ---- menus ---- + + /** The menu for AWT's icon, which shows one of its own. */ + private PopupMenu buildAwtMenu() { + PopupMenu menu = new PopupMenu(); + MenuItem showItem = new MenuItem("Show TeamSpook TS3j"); + showItem.addActionListener(e -> SwingUtilities.invokeLater(this::show)); + MenuItem quitItem = new MenuItem("Quit"); + quitItem.addActionListener(e -> SwingUtilities.invokeLater(onQuit)); + menu.add(showItem); + menu.addSeparator(); + menu.add(quitItem); + return menu; + } + + /** + * The same menu for backends that have none — a Swing popup needs a component to + * hang off, so it is given an empty window at the pointer. + * + *

    Swing dismisses a popup from events it sees itself, and it sees none of the + * clicks that land on the desktop or another application, so the little window is + * made focusable and the menu closed as soon as it loses the focus. Escape and a + * second click on the icon close it too. + */ + private void showMenu(int x, int y) { + if (openMenu != null) { // a second click on the icon: close it again + hideMenu(); + return; + } + JDialog anchor = new JDialog(frame); + anchor.setUndecorated(true); + anchor.setFocusableWindowState(true); + anchor.setAlwaysOnTop(true); + anchor.setLocation(x, y); + anchor.setSize(1, 1); + anchor.setVisible(true); + anchor.toFront(); + anchor.requestFocus(); + anchor.addWindowFocusListener(new WindowAdapter() { + @Override + public void windowLostFocus(WindowEvent e) { + // The menu's own popup window may take the focus instead; only the + // focus moving away from the menu altogether closes it. + if (!ownedBy(e.getOppositeWindow(), anchor)) hideMenu(); + } + }); + + anchor.getRootPane().registerKeyboardAction(e -> hideMenu(), + KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), + JComponent.WHEN_IN_FOCUSED_WINDOW); + + JPopupMenu menu = new JPopupMenu(); + JMenuItem showItem = new JMenuItem("Show TeamSpook TS3j", Icons.app()); + showItem.addActionListener(e -> show()); + JMenuItem quitItem = new JMenuItem("Quit", Icons.of("QUIT")); + quitItem.addActionListener(e -> onQuit.run()); + menu.add(showItem); + menu.addSeparator(); + menu.add(quitItem); + menu.addPopupMenuListener(new PopupMenuListener() { + @Override + public void popupMenuWillBecomeVisible(PopupMenuEvent e) { + } + + @Override + public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { + closed(anchor); + } + + @Override + public void popupMenuCanceled(PopupMenuEvent e) { + closed(anchor); + } + }); + openMenu = menu; + openAnchor = anchor; + menu.show(anchor, 0, 0); + } + + /** @return whether {@code window} is {@code owner} or one of its child windows */ + private static boolean ownedBy(Window window, Window owner) { + for (Window w = window; w != null; w = w.getOwner()) { + if (w == owner) return true; + } + return false; + } + + private void hideMenu() { + if (openMenu != null) openMenu.setVisible(false); // the listener cleans up + closed(openAnchor); + } + + private void closed(JDialog anchor) { + openMenu = null; + openAnchor = null; + if (anchor != null) anchor.dispose(); + } + + /** + * Brings the window back from the taskbar or an iconified state. + * + *

    A window manager ignores {@link Frame#toFront()} from an application that is + * not focused, which is every time the tray icon is used, so the backend is asked + * first — it can make the request the window manager does honour. + */ + void show() { + hideMenu(); + frame.setVisible(true); + frame.setExtendedState(frame.getExtendedState() & ~Frame.ICONIFIED); + // Deferred so the window is mapped before anything tries to raise it. + SwingUtilities.invokeLater(() -> { + if (tray != null && tray.activateWindow(frame.getTitle())) return; + // Whatever Swing can manage: asking to be on top for a moment gets the + // window in front even where a plain raise is refused. + frame.setAlwaysOnTop(true); + frame.toFront(); + frame.requestFocus(); + frame.setAlwaysOnTop(false); + }); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/TrayNotifications.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/TrayNotifications.java new file mode 100644 index 0000000..f4a8806 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/TrayNotifications.java @@ -0,0 +1,36 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.notify.desktop.DesktopNotifications; +import eu.lixko.ts3j.client.ui.tray.AwtTray; + +/** + * Desktop notifications as messages from AWT's tray icon, for Windows and macOS: they + * land in the system's notification centre. A message cannot be replaced or taken back. + */ +final class TrayNotifications implements DesktopNotifications { + + private final AwtTray tray; + + TrayNotifications(AwtTray tray) { + this.tray = tray; + } + + @Override + public int show(Notice notice, int replaces) { + tray.showMessage(notice.title(), notice.body(), notice.onOpen()); + return 1; + } + + @Override + public void close(int id) { + } + + @Override + public boolean canReply() { + return false; + } + + @Override + public void shutdown() { + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/VoiceActivationSection.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/VoiceActivationSection.java new file mode 100644 index 0000000..e5d09fc --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/VoiceActivationSection.java @@ -0,0 +1,336 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.audio.AudioBackend; +import eu.lixko.ts3j.client.audio.InputLevel; +import eu.lixko.ts3j.client.audio.VoiceInput; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.hotkey.Hotkey; +import eu.lixko.ts3j.client.hotkey.HotkeyAction; + +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JSlider; +import javax.swing.JToggleButton; +import java.awt.BorderLayout; +import java.awt.GridBagConstraints; +import java.awt.Insets; +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * The Capture page's activation section: input mode (push-to-talk / continuous / voice + * activation), the detection tuning, and a live input meter. + * + *

    Owns the microphone test (start/stop button, loopback, indicator): it runs a real + * capture chain built from what the Capture and Playback pages have on screen, via + * {@code audioSnapshot}. + */ +final class VoiceActivationSection { + + private final VoiceInput liveMic; + private final HotkeyService hotkeys; + private final HotkeysPanel hotkeysPanel; + private final Supplier audioSnapshot; + private final MicrophoneTest micTest; + + private final JRadioButton vadRadio; + private final JRadioButton pttRadio; + private final JRadioButton contRadio; + private final JComboBox vadModeCombo; + private final JSlider thresholdSlider; + private final JSlider speechSlider; + private final JCheckBox vadOverPttCheck; + private final LevelMeter meter; + private JToggleButton testButton; + private JCheckBox loopbackCheck; + private JLabel talkIndicator; + private final JButton pttKeyButton; + + private final JLabel thresholdLabel; + private final JLabel speechLabel; + private final JPanel testControls; + + VoiceActivationSection(Settings settings, AudioBackend audio, VoiceInput liveMic, HotkeyService hotkeys, + HotkeysPanel hotkeysPanel, Supplier audioSnapshot) { + this.liveMic = liveMic; + this.micTest = new MicrophoneTest(audio, this::onTestLevel, this::onTestTalking); + this.hotkeys = hotkeys; + this.hotkeysPanel = hotkeysPanel; + this.audioSnapshot = audioSnapshot; + + pttRadio = new JRadioButton("Push-To-Talk"); + contRadio = new JRadioButton("Continuous Transmission"); + vadRadio = new JRadioButton("Voice Activity Detection"); + ButtonGroup group = new ButtonGroup(); + group.add(pttRadio); + group.add(contRadio); + group.add(vadRadio); + switch (settings.inputMode) { + case PUSH_TO_TALK: + pttRadio.setSelected(true); + break; + case CONTINUOUS: + contRadio.setSelected(true); + break; + default: + vadRadio.setSelected(true); + } + + pttKeyButton = new JButton(pushToTalkHotkeyText()); + pttKeyButton.setToolTipText("Push-to-talk is a global hotkey; this opens its binding"); + pttKeyButton.addActionListener(e -> editPushToTalkHotkey()); + + vadOverPttCheck = new JCheckBox("Add Voice Activity Detection", settings.vadOverPtt); + vadOverPttCheck.addActionListener(e -> + micTest.configure(m -> m.setVadOverPtt(vadOverPttCheck.isSelected()))); + + vadModeCombo = new JComboBox<>(new String[]{"Automatic", "Volume Gate", "Hybrid"}); + vadModeCombo.setSelectedIndex(vadModeIndex(settings.vadMode)); + vadModeCombo.addActionListener(e -> micTest.configure(m -> m.setVadMode(currentVadMode()))); + vadModeCombo.setToolTipText("Automatic: intelligent speech detection.
    " + + "Volume Gate: transmit when loud enough.
    " + + "Hybrid: loud enough and detected as speech."); + + thresholdSlider = new JSlider((int) InputLevel.MIN_DB, (int) InputLevel.MAX_DB, + (int) Math.round(settings.vadThresholdDb)); + thresholdLabel = new JLabel(Math.round(settings.vadThresholdDb) + " dB"); + speechSlider = new JSlider(0, 100, (int) Math.round(settings.speechThreshold * 100)); + speechLabel = new JLabel(Math.round(settings.speechThreshold * 100) + "%"); + + meter = new LevelMeter(); + meter.setThreshold(settings.vadThresholdDb); + testControls = buildTestControls(); + + thresholdSlider.addChangeListener(e -> { + meter.setThreshold(thresholdSlider.getValue()); + thresholdLabel.setText(thresholdSlider.getValue() + " dB"); + applyLive(m -> m.setThresholdDb(thresholdSlider.getValue())); + }); + speechSlider.addChangeListener(e -> { + speechLabel.setText(speechSlider.getValue() + "%"); + applyLive(m -> m.setSpeechThreshold(speechSlider.getValue() / 100.0)); + }); + + Runnable syncEnabled = () -> { + boolean vad = vadRadio.isSelected(); + boolean ptt = pttRadio.isSelected(); + boolean vadContext = vad || (ptt && vadOverPttCheck.isSelected()); + Settings.VadMode vm = currentVadMode(); + boolean usesGate = vm != Settings.VadMode.AUTOMATIC; + boolean usesSpeech = vm != Settings.VadMode.VOLUME_GATE; + + vadModeCombo.setEnabled(vadContext); + thresholdSlider.setEnabled(vadContext && usesGate); + speechSlider.setEnabled(vadContext && usesSpeech); + pttKeyButton.setEnabled(ptt); + vadOverPttCheck.setEnabled(ptt); + meter.setShowThreshold(vadContext && usesGate); + + if (liveMic != null) { + liveMic.setMode(ptt ? Settings.InputMode.PUSH_TO_TALK + : vad ? Settings.InputMode.VOICE_ACTIVATION + : Settings.InputMode.CONTINUOUS); + liveMic.setVadMode(vm); + liveMic.setVadOverPtt(vadOverPttCheck.isSelected()); + } + }; + vadRadio.addActionListener(e -> syncEnabled.run()); + pttRadio.addActionListener(e -> syncEnabled.run()); + contRadio.addActionListener(e -> syncEnabled.run()); + vadModeCombo.addActionListener(e -> syncEnabled.run()); + vadOverPttCheck.addActionListener(e -> syncEnabled.run()); + syncEnabled.run(); + } + + /** Adds the section's rows to {@code form} from {@code row} on; returns the next free row. */ + int layOut(JPanel form, GridBagConstraints c, int row) { + FormPanel.addRow(form, c, row++, pttRadio, pttKeyButton); + FormPanel.addWide(form, c, row++, indented(vadOverPttCheck)); + FormPanel.addWide(form, c, row++, contRadio); + FormPanel.addRow(form, c, row++, vadRadio, vadModeCombo); + FormPanel.addRow(form, c, row++, indented(new JLabel("Volume gate:")), + FormPanel.sliderWithLabel(thresholdSlider, thresholdLabel)); + FormPanel.addRow(form, c, row++, indented(new JLabel("Speech threshold:")), + FormPanel.sliderWithLabel(speechSlider, speechLabel)); + + Insets insets = c.insets; + c.insets = UIScale.scale(new Insets(10, 4, 4, 4)); + FormPanel.addWide(form, c, row++, meter); + c.insets = insets; + FormPanel.addWide(form, c, row++, testControls); + return row; + } + + /** Lines a dependent control up under the text of the radio button it belongs to. */ + private static JComponent indented(JComponent comp) { + JPanel p = new JPanel(new BorderLayout()); + p.setBorder(new ScaledEmptyBorder(0, 22, 0, 0)); + p.add(comp, BorderLayout.CENTER); + return p; + } + + /** Copies the form into {@code target}, without touching anything else. */ + void writeInto(Settings target) { + target.inputMode = pttRadio.isSelected() ? Settings.InputMode.PUSH_TO_TALK + : contRadio.isSelected() ? Settings.InputMode.CONTINUOUS + : Settings.InputMode.VOICE_ACTIVATION; + target.vadMode = currentVadMode(); + target.vadThresholdDb = thresholdSlider.getValue(); + target.speechThreshold = speechSlider.getValue() / 100.0; + target.vadOverPtt = vadOverPttCheck.isSelected(); + } + + /** Applies a change to the microphone test, if it is running. */ + void configureTest(Consumer change) { + micTest.configure(change); + } + + /** The playback device to loop the test through. */ + void setTestOutputDevice(String deviceId) { + micTest.setOutputDevice(deviceId); + } + + /** Restarts the test chain, if running, so a device change takes effect. */ + void restartTest() { + if (micTest.isRunning()) { + boolean loopback = loopbackCheck.isSelected(); + if (micTest.start(audioSnapshot.get())) { + micTest.setLoopback(loopback); + } else { + setTesting(false); + testButton.setSelected(false); + } + } + } + + void stopTest() { + micTest.stop(); + } + + private static int vadModeIndex(Settings.VadMode m) { + switch (m) { + case AUTOMATIC: + return 0; + case VOLUME_GATE: + return 1; + default: + return 2; + } + } + + private Settings.VadMode currentVadMode() { + switch (vadModeCombo.getSelectedIndex()) { + case 0: + return Settings.VadMode.AUTOMATIC; + case 1: + return Settings.VadMode.VOLUME_GATE; + default: + return Settings.VadMode.HYBRID; + } + } + + private String pushToTalkHotkeyText() { + Hotkey ptt = hotkeys.find(HotkeyAction.PTT_ACTIVATE); + return ptt == null ? "No hotkey assigned" : hotkeys.display(ptt.combo); + } + + /** + * Push-to-talk is an ordinary hotkey, so this shortcut edits that binding — adding + * it when there is none — rather than keeping a key of its own. + */ + private void editPushToTalkHotkey() { + Hotkey existing = hotkeys.find(HotkeyAction.PTT_ACTIVATE); + HotkeyDialog dlg = new HotkeyDialog(javax.swing.SwingUtilities.getWindowAncestor(pttKeyButton), + hotkeys, existing == null ? new Hotkey(HotkeyAction.PTT_ACTIVATE, null) : existing); + dlg.setVisible(true); + if (!dlg.isConfirmed()) return; + List updated = new java.util.ArrayList<>(); + for (Hotkey h : hotkeys.all()) { + if (h != existing) updated.add(h.copy()); + } + updated.add(dlg.result()); + hotkeys.replaceAll(updated); + pttKeyButton.setText(pushToTalkHotkeyText()); + hotkeysPanel.reload(); + } + + /** Applies a live change to the connected microphone and to the test one alike. */ + private void applyLive(Consumer change) { + if (liveMic != null) change.accept(liveMic); + micTest.configure(change); + } + + // ---- microphone test ---- + + /** + * The test row: a toggle that runs the capture chain, an indicator showing whether the + * gate is open, and an optional loopback so you can hear what is being sent. + */ + private JPanel buildTestControls() { + JPanel row = new JPanel(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 8, 0)); + + testButton = new JToggleButton("Begin Test"); + testButton.setToolTipText("Run the capture chain exactly as it runs while connected, " + + "so the bar and the indicator show what would actually be transmitted."); + testButton.addActionListener(e -> setTesting(testButton.isSelected())); + + loopbackCheck = new JCheckBox("Hear myself"); + loopbackCheck.setToolTipText("Play the transmitted audio back through the playback " + + "device. Use headphones to avoid feedback."); + loopbackCheck.setEnabled(false); + loopbackCheck.addActionListener(e -> micTest.setLoopback(loopbackCheck.isSelected())); + + talkIndicator = new JLabel("Not transmitting", Icons.clientIdle(), JLabel.LEFT); + talkIndicator.setToolTipText("Lights up while your microphone is open, exactly as " + + "other users would see you in the channel list."); + + row.add(testButton); + row.add(loopbackCheck); + row.add(talkIndicator); + return row; + } + + private void setTesting(boolean on) { + if (on && !micTest.start(audioSnapshot.get())) { + testButton.setSelected(false); + testButton.setText("Begin Test"); + loopbackCheck.setEnabled(false); + resetTestIndicators(); + talkIndicator.setText("Capture device unavailable"); + return; + } + if (!on) { + micTest.stop(); + loopbackCheck.setSelected(false); + resetTestIndicators(); + } + testButton.setText(on ? "Stop Test" : "Begin Test"); + loopbackCheck.setEnabled(on); + } + + private void resetTestIndicators() { + onTestTalking(false); + onTestLevel(InputLevel.SILENCE_DB); + } + + private void onTestLevel(double db) { + if (meter != null) meter.setLevel(db); + } + + private void onTestTalking(boolean talking) { + if (meter != null) meter.setTransmitting(talking); + if (talkIndicator != null) { + talkIndicator.setIcon(talking ? Icons.clientTalking() : Icons.clientIdle()); + talkIndicator.setText(talking ? "Transmitting" : "Not transmitting"); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/WindowClass.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/WindowClass.java new file mode 100644 index 0000000..e913284 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/WindowClass.java @@ -0,0 +1,46 @@ +package eu.lixko.ts3j.client.ui; + +import java.awt.GraphicsEnvironment; +import java.awt.Toolkit; +import java.lang.reflect.Field; +import java.util.Locale; + +/** + * Gives the client's windows their own X11 {@code WM_CLASS}. + * + *

    AWT names it after the class at the bottom of the stack that first touched the + * toolkit — for a Swing app that is usually {@code java-awt-EventDispatchThread}, + * which every other Java program shares. Task bars group windows and look up their + * launcher by that class (Plasma does so on Wayland too, through Xwayland), so the + * client ended up filed under "Java" together with unrelated programs. + * + *

    The name lives in a private field of {@code sun.awt.X11.XToolkit}; reaching it + * needs {@code --add-opens java.desktop/sun.awt.X11=ALL-UNNAMED}, which the jar's + * manifest grants. Without it the default name stays. + */ +public final class WindowClass { + + /** Matches {@code StartupWMClass} in a launcher's {@code .desktop} file. */ + public static final String NAME = "ts3j-client"; + + private WindowClass() { + } + + /** Call before the first window is created. */ + public static void apply() { + if (!System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("linux") + || GraphicsEnvironment.isHeadless()) { + return; + } + Toolkit toolkit = Toolkit.getDefaultToolkit(); + if (!toolkit.getClass().getName().equals("sun.awt.X11.XToolkit")) return; + try { + Field field = toolkit.getClass().getDeclaredField("awtAppClassName"); + field.setAccessible(true); + field.set(null, NAME); + } catch (ReflectiveOperationException | RuntimeException e) { + System.err.println("Cannot set the window class (run with " + + "--add-opens java.desktop/sun.awt.X11=ALL-UNNAMED): " + e); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/tray/AwtTray.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/tray/AwtTray.java new file mode 100644 index 0000000..f8b0401 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/tray/AwtTray.java @@ -0,0 +1,107 @@ +package eu.lixko.ts3j.client.ui.tray; + +import java.awt.AWTException; +import java.awt.Dimension; +import java.awt.Image; +import java.awt.PopupMenu; +import java.awt.SystemTray; +import java.awt.TrayIcon; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.function.IntFunction; + +/** + * The tray icon AWT itself provides — used where {@link X11Tray} cannot help: + * Windows and macOS, and X11 panels that do not offer a transparent visual. + * + *

    On X11 the toolkit draws the icon onto an opaque background, which is the + * price of this fallback; the menu, on the other hand, is the desktop's own. + */ +public final class AwtTray implements TrayBackend { + + private final TrayIcon icon; + private final int size; + /** What a click on the message last shown does, until it is used. */ + private volatile Runnable messageClick; + + /** + * @param menu the icon's context menu, or {@code null} to have right clicks + * reported to {@code listener} instead + * @param initial the image to dock with, rendered at the tray's icon size + * @return the icon, or {@code null} when this desktop has no tray at all + */ + public static AwtTray create(Listener listener, PopupMenu menu, IntFunction initial) { + if (!SystemTray.isSupported()) { + TrayLog.debug("this desktop has no system tray"); + return null; + } + try { + AwtTray tray = new AwtTray(listener, menu, initial); + TrayLog.debug("using AWT's tray icon, " + tray.size + "px (it draws a background)"); + return tray; + } catch (AWTException | UnsupportedOperationException e) { + TrayLog.debug("AWT would not add the icon: " + e.getMessage()); + return null; + } + } + + private AwtTray(Listener listener, PopupMenu menu, IntFunction initial) + throws AWTException { + Dimension traySize = SystemTray.getSystemTray().getTrayIconSize(); + size = Math.max(16, Math.min(traySize.width, traySize.height)); + + // Added with its final image and tooltip: some panels take the icon they are + // handed at that moment and ignore later changes. + icon = new TrayIcon(initial.apply(size), "TeamSpook TS3j"); + if (menu != null) icon.setPopupMenu(menu); + // The action event only fires on a double click (and not at all on some + // desktops), so listen for the click itself. + icon.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON1) { + listener.activated(); + } else if (menu == null && e.isPopupTrigger()) { + listener.menuRequested(e.getXOnScreen(), e.getYOnScreen()); + } + } + }); + // Fired by a click on a message (and on some desktops a double click on the icon). + icon.addActionListener(e -> { + Runnable click = messageClick; + messageClick = null; + if (click != null) click.run(); + }); + SystemTray.getSystemTray().add(icon); + } + + /** + * Shows a message by the icon, which Windows turns into a toast in its notification + * centre and macOS into a banner in its own. + */ + public void showMessage(String title, String body, Runnable onClick) { + messageClick = onClick; + icon.displayMessage(title, body, TrayIcon.MessageType.NONE); + } + + @Override + public void setIcon(IntFunction render) { + Image image = render.apply(size); + if (image != null) icon.setImage(image); + } + + @Override + public void setTooltip(String tooltip) { + icon.setToolTip(tooltip); + } + + @Override + public String description() { + return "AWT's own icon, " + size + "px (the desktop draws a background behind it)"; + } + + @Override + public void dispose() { + SystemTray.getSystemTray().remove(icon); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/tray/TrayBackend.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/tray/TrayBackend.java new file mode 100644 index 0000000..0990352 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/tray/TrayBackend.java @@ -0,0 +1,51 @@ +package eu.lixko.ts3j.client.ui.tray; + +import java.awt.Image; +import java.util.function.IntFunction; + +/** A tray icon, however the desktop happens to provide one. */ +public interface TrayBackend { + + /** + * Sets the icon to show. + * + * @param render draws it at the size the tray asks for — panels differ, and the + * size can change while the icon is docked + */ + void setIcon(IntFunction render); + + /** Sets the text the panel shows on hover, where it supports one. */ + void setTooltip(String tooltip); + + /** Takes the icon out of the tray again. */ + void dispose(); + + /** How this icon is being shown, for the client's own diagnostics. */ + String description(); + + /** + * Asks the window manager to bring a window of this application to the front. + * Swing cannot: a window manager ignores a raise from an application that does + * not have the focus, which is exactly the case when the tray icon is used. + * + * @param title the window's title + * @return {@code false} when this backend cannot ask, and the caller should try + * whatever Swing can do + */ + default boolean activateWindow(String title) { + return false; + } + + /** What the user did with the icon. */ + interface Listener { + + /** The icon was clicked (or activated from the keyboard). */ + void activated(); + + /** + * A context menu was asked for at a screen position. Only called by backends + * that have no menu of their own. + */ + void menuRequested(int x, int y); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/tray/TrayLog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/tray/TrayLog.java new file mode 100644 index 0000000..b3cef14 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/tray/TrayLog.java @@ -0,0 +1,20 @@ +package eu.lixko.ts3j.client.ui.tray; + +/** + * Diagnostics for the tray icon, off unless {@code -Dts3j.tray.debug=true} is given. + * + *

    Which backend ends up with the icon depends on what the panel offers, and a + * panel that quietly ignores a docking request leaves nothing to see, so it is + * worth being able to ask. + */ +final class TrayLog { + + private static final boolean ENABLED = Boolean.getBoolean("ts3j.tray.debug"); + + private TrayLog() { + } + + static void debug(String message) { + if (ENABLED) System.err.println("tray: " + message); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/tray/X11.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/tray/X11.java new file mode 100644 index 0000000..9e8e3b5 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/tray/X11.java @@ -0,0 +1,470 @@ +package eu.lixko.ts3j.client.ui.tray; + +import java.lang.foreign.AddressLayout; +import java.lang.foreign.Arena; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.Linker; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.SymbolLookup; +import java.lang.foreign.ValueLayout; +import java.lang.invoke.MethodHandle; +import java.nio.charset.StandardCharsets; + +/** + * Raw binding to {@code libX11} through the Foreign Function & Memory API, with + * just the calls {@link X11Tray} needs. + * + *

    This class is the only place that knows about Xlib's ABI: the entry points, the + * protocol constants and the offsets of the few structures that are read or written + * directly. Loading is lazy and failure is expected — on a machine with no X11 (or a + * pure Wayland session) {@link #isAvailable()} returns {@code false} and the caller + * falls back to AWT's own tray icon. + * + *

    Offsets are those of the LP64 ABI, in which {@code XID}, {@code Atom} and + * {@code long} are 64 bits wide and every field is naturally aligned. + */ +final class X11 { + + private X11() { + } + + static final AddressLayout PTR = ValueLayout.ADDRESS; + static final ValueLayout.OfInt INT = ValueLayout.JAVA_INT; + static final ValueLayout.OfLong LONG = ValueLayout.JAVA_LONG; + + // ---- protocol constants (X.h) ---- + + static final int INPUT_OUTPUT = 1; + static final int ALLOC_NONE = 0; + static final int PROP_MODE_REPLACE = 0; + static final int Z_PIXMAP = 2; + static final int SUCCESS = 0; + + /** Fields of {@code XSetWindowAttributes} passed to {@code XCreateWindow}. */ + static final long CW_BACK_PIXEL = 1L << 1; + static final long CW_BORDER_PIXEL = 1L << 3; + static final long CW_EVENT_MASK = 1L << 11; + static final long CW_COLORMAP = 1L << 13; + + static final long BUTTON_PRESS_MASK = 1L << 2; + static final long SUBSTRUCTURE_NOTIFY_MASK = 1L << 19; + static final long SUBSTRUCTURE_REDIRECT_MASK = 1L << 20; + static final long EXPOSURE_MASK = 1L << 15; + static final long STRUCTURE_NOTIFY_MASK = 1L << 17; + static final long NO_EVENT_MASK = 0L; + + static final int BUTTON_PRESS = 4; + static final int EXPOSE = 12; + static final int MAP_NOTIFY = 19; + static final int REPARENT_NOTIFY = 21; + static final int CONFIGURE_NOTIFY = 22; + static final int CLIENT_MESSAGE = 33; + + /** Predefined atoms (Xatom.h). */ + static final long XA_STRING = 31; + static final long XA_VISUALID = 32; + + static final long VISUAL_ID_MASK = 0x1; + /** {@code AnyPropertyType}: read a property whatever its type. */ + static final long ANY_PROPERTY_TYPE = 0; + + // ---- structure layout ---- + + /** {@code XEvent} is a union; 192 bytes is its size on every LP64 platform. */ + static final long EVENT_SIZE = 192; + static final long EVENT_TYPE = 0; + + /** {@code XExposeEvent} / {@code XConfigureEvent} / {@code XButtonEvent} share this prefix. */ + static final long EVENT_WINDOW = 32; + + /** {@code XConfigureEvent}: the reconfigured window, then its new geometry. */ + static final long CONFIGURE_WINDOW = 40; + static final long CONFIGURE_WIDTH = 56; + static final long CONFIGURE_HEIGHT = 60; + + /** {@code XReparentEvent}: the reparented window and its new parent. */ + static final long REPARENT_WINDOW = 40; + static final long REPARENT_PARENT = 48; + + /** {@code XButtonEvent}. */ + static final long BUTTON_X_ROOT = 72; + static final long BUTTON_Y_ROOT = 76; + static final long BUTTON_BUTTON = 84; + + /** {@code XClientMessageEvent}. */ + static final long CLIENT_MESSAGE_TYPE = 40; + static final long CLIENT_MESSAGE_FORMAT = 48; + static final long CLIENT_MESSAGE_DATA = 56; + + /** {@code XSetWindowAttributes}. */ + static final long ATTRIBUTES_SIZE = 112; + static final long ATTRIBUTES_BACKGROUND_PIXEL = 8; + static final long ATTRIBUTES_BORDER_PIXEL = 24; + static final long ATTRIBUTES_EVENT_MASK = 72; + static final long ATTRIBUTES_COLORMAP = 96; + + /** {@code XSizeHints} fields we set, and its {@code flags} bits (Xutil.h). */ + static final long SIZE_HINTS_SIZE = 80; + static final long SIZE_HINTS_FLAGS = 0; + static final long SIZE_HINTS_MIN_WIDTH = 24; + static final long SIZE_HINTS_MIN_HEIGHT = 28; + static final long SIZE_HINTS_MAX_WIDTH = 32; + static final long SIZE_HINTS_MAX_HEIGHT = 36; + static final long SIZE_HINTS_BASE_WIDTH = 64; + static final long SIZE_HINTS_BASE_HEIGHT = 68; + static final long P_MIN_SIZE = 1L << 4; + static final long P_MAX_SIZE = 1L << 5; + static final long P_BASE_SIZE = 1L << 8; + + /** {@code XVisualInfo}. */ + static final long VISUAL_INFO_SIZE = 64; + static final long VISUAL_INFO_VISUAL = 0; + static final long VISUAL_INFO_VISUALID = 8; + static final long VISUAL_INFO_DEPTH = 20; + + /** {@code XImage}: only the data pointer is touched, to unhook it before freeing. */ + static final long IMAGE_DATA = 16; + + private static final Linker LINKER = Linker.nativeLinker(); + private static final String[] LIBRARY_NAMES = {"libX11.so.6", "libX11.so"}; + + private static final class Handles { + static final SymbolLookup LOOKUP = load(); + + static final MethodHandle X_OPEN_DISPLAY = + downcall("XOpenDisplay", FunctionDescriptor.of(PTR, PTR)); + static final MethodHandle X_CLOSE_DISPLAY = + downcall("XCloseDisplay", FunctionDescriptor.of(INT, PTR)); + static final MethodHandle X_INTERN_ATOM = + downcall("XInternAtom", FunctionDescriptor.of(LONG, PTR, PTR, INT)); + static final MethodHandle X_GET_SELECTION_OWNER = + downcall("XGetSelectionOwner", FunctionDescriptor.of(LONG, PTR, LONG)); + static final MethodHandle X_DEFAULT_SCREEN = + downcall("XDefaultScreen", FunctionDescriptor.of(INT, PTR)); + static final MethodHandle X_ROOT_WINDOW = + downcall("XRootWindow", FunctionDescriptor.of(LONG, PTR, INT)); + static final MethodHandle X_GET_WINDOW_PROPERTY = + downcall("XGetWindowProperty", FunctionDescriptor.of(INT, PTR, LONG, LONG, LONG, LONG, + INT, LONG, PTR, PTR, PTR, PTR, PTR)); + static final MethodHandle X_GET_VISUAL_INFO = + downcall("XGetVisualInfo", FunctionDescriptor.of(PTR, PTR, LONG, PTR, PTR)); + static final MethodHandle X_FREE = + downcall("XFree", FunctionDescriptor.of(INT, PTR)); + static final MethodHandle X_CREATE_COLORMAP = + downcall("XCreateColormap", FunctionDescriptor.of(LONG, PTR, LONG, PTR, INT)); + static final MethodHandle X_CREATE_WINDOW = + downcall("XCreateWindow", FunctionDescriptor.of(LONG, PTR, LONG, INT, INT, INT, INT, + INT, INT, INT, PTR, LONG, PTR)); + static final MethodHandle X_DESTROY_WINDOW = + downcall("XDestroyWindow", FunctionDescriptor.of(INT, PTR, LONG)); + static final MethodHandle X_CHANGE_PROPERTY = + downcall("XChangeProperty", FunctionDescriptor.of(INT, PTR, LONG, LONG, LONG, INT, + INT, PTR, INT)); + static final MethodHandle X_SELECT_INPUT = + downcall("XSelectInput", FunctionDescriptor.of(INT, PTR, LONG, LONG)); + static final MethodHandle X_SEND_EVENT = + downcall("XSendEvent", FunctionDescriptor.of(INT, PTR, LONG, INT, LONG, PTR)); + static final MethodHandle X_QUERY_TREE = + downcall("XQueryTree", FunctionDescriptor.of(INT, PTR, LONG, PTR, PTR, PTR, PTR)); + static final MethodHandle X_SET_WM_NORMAL_HINTS = + downcall("XSetWMNormalHints", FunctionDescriptor.ofVoid(PTR, LONG, PTR)); + static final MethodHandle X_RESIZE_WINDOW = + downcall("XResizeWindow", FunctionDescriptor.of(INT, PTR, LONG, INT, INT)); + static final MethodHandle X_MAP_WINDOW = + downcall("XMapWindow", FunctionDescriptor.of(INT, PTR, LONG)); + static final MethodHandle X_UNMAP_WINDOW = + downcall("XUnmapWindow", FunctionDescriptor.of(INT, PTR, LONG)); + static final MethodHandle X_FLUSH = + downcall("XFlush", FunctionDescriptor.of(INT, PTR)); + static final MethodHandle X_PENDING = + downcall("XPending", FunctionDescriptor.of(INT, PTR)); + static final MethodHandle X_NEXT_EVENT = + downcall("XNextEvent", FunctionDescriptor.of(INT, PTR, PTR)); + static final MethodHandle X_CREATE_GC = + downcall("XCreateGC", FunctionDescriptor.of(PTR, PTR, LONG, LONG, PTR)); + static final MethodHandle X_FREE_GC = + downcall("XFreeGC", FunctionDescriptor.of(INT, PTR, PTR)); + static final MethodHandle X_CREATE_IMAGE = + downcall("XCreateImage", FunctionDescriptor.of(PTR, PTR, PTR, INT, INT, INT, PTR, + INT, INT, INT, INT)); + static final MethodHandle X_PUT_IMAGE = + downcall("XPutImage", FunctionDescriptor.of(INT, PTR, LONG, PTR, PTR, INT, INT, INT, + INT, INT, INT)); + + private static SymbolLookup load() { + IllegalArgumentException last = null; + for (String name : LIBRARY_NAMES) { + try { + return SymbolLookup.libraryLookup(name, Arena.global()); + } catch (IllegalArgumentException e) { + last = e; + } + } + throw (last != null) ? last : new IllegalArgumentException("libX11 not found"); + } + + private static MethodHandle downcall(String symbol, FunctionDescriptor descriptor) { + return LINKER.downcallHandle( + LOOKUP.find(symbol).orElseThrow(() -> + new UnsatisfiedLinkError("libX11: unresolved symbol " + symbol)), + descriptor); + } + } + + /** {@code true} when libX11 could be loaded and every symbol we need resolved. */ + static boolean isAvailable() { + try { + return Handles.LOOKUP != null; + } catch (Throwable t) { + return false; + } + } + + // ---- display ---- + + /** @return the display, or {@link MemorySegment#NULL} when it cannot be opened */ + static MemorySegment openDisplay() { + return (MemorySegment) call(Handles.X_OPEN_DISPLAY, MemorySegment.NULL); + } + + static void closeDisplay(MemorySegment display) { + call(Handles.X_CLOSE_DISPLAY, display); + } + + static int defaultScreen(MemorySegment display) { + return (int) call(Handles.X_DEFAULT_SCREEN, display); + } + + static long rootWindow(MemorySegment display, int screen) { + return (long) call(Handles.X_ROOT_WINDOW, display, screen); + } + + static long internAtom(MemorySegment display, Arena arena, String name) { + return (long) call(Handles.X_INTERN_ATOM, display, arena.allocateFrom(name), 0); + } + + static long selectionOwner(MemorySegment display, long atom) { + return (long) call(Handles.X_GET_SELECTION_OWNER, display, atom); + } + + static void flush(MemorySegment display) { + call(Handles.X_FLUSH, display); + } + + // ---- properties ---- + + /** + * Reads a single 32-bit property value (which Xlib hands back as a C {@code long}). + * + * @return the value, or {@code 0} when the window has no such property + */ + static long cardinalProperty(MemorySegment display, Arena arena, long window, long property, + long type) { + MemorySegment actualType = arena.allocate(LONG); + MemorySegment actualFormat = arena.allocate(INT); + MemorySegment items = arena.allocate(LONG); + MemorySegment bytesAfter = arena.allocate(LONG); + MemorySegment data = arena.allocate(PTR); + int status = (int) call(Handles.X_GET_WINDOW_PROPERTY, display, window, property, 0L, 1L, 0, + type, actualType, actualFormat, items, bytesAfter, data); + MemorySegment values = data.get(PTR, 0); + if (status != SUCCESS || values.equals(MemorySegment.NULL)) return 0; + long value = items.get(LONG, 0) > 0 + ? values.reinterpret(Long.BYTES).get(LONG, 0) + : 0; + call(Handles.X_FREE, values); + return value; + } + + static void setCardinals(MemorySegment display, Arena arena, long window, long property, + long type, long... values) { + MemorySegment data = arena.allocate(LONG, values.length); + for (int i = 0; i < values.length; i++) data.setAtIndex(LONG, i, values[i]); + call(Handles.X_CHANGE_PROPERTY, display, window, property, type, 32, PROP_MODE_REPLACE, + data, values.length); + } + + static void setText(MemorySegment display, Arena arena, long window, long property, long type, + String text) { + byte[] bytes = text.getBytes(StandardCharsets.UTF_8); + MemorySegment data = arena.allocate(bytes.length + 1); + MemorySegment.copy(bytes, 0, data, ValueLayout.JAVA_BYTE, 0, bytes.length); + call(Handles.X_CHANGE_PROPERTY, display, window, property, type, 8, PROP_MODE_REPLACE, + data, bytes.length); + } + + /** @return the children of a window, oldest first */ + static long[] children(MemorySegment display, Arena arena, long window) { + MemorySegment rootReturn = arena.allocate(LONG); + MemorySegment parentReturn = arena.allocate(LONG); + MemorySegment childrenReturn = arena.allocate(PTR); + MemorySegment countReturn = arena.allocate(INT); + int status = (int) call(Handles.X_QUERY_TREE, display, window, rootReturn, parentReturn, + childrenReturn, countReturn); + MemorySegment list = childrenReturn.get(PTR, 0); + if (status == 0 || list.equals(MemorySegment.NULL)) return new long[0]; + int count = countReturn.get(INT, 0); + long[] ids = new long[count]; + MemorySegment windows = list.reinterpret((long) count * Long.BYTES); + for (int i = 0; i < count; i++) ids[i] = windows.getAtIndex(LONG, i); + call(Handles.X_FREE, list); + return ids; + } + + /** + * Reads a text property. + * + * @return its value as UTF-8, or {@code null} when the window has no such property + */ + static String textProperty(MemorySegment display, Arena arena, long window, long property) { + MemorySegment actualType = arena.allocate(LONG); + MemorySegment actualFormat = arena.allocate(INT); + MemorySegment items = arena.allocate(LONG); + MemorySegment bytesAfter = arena.allocate(LONG); + MemorySegment data = arena.allocate(PTR); + int status = (int) call(Handles.X_GET_WINDOW_PROPERTY, display, window, property, 0L, 1024L, + 0, ANY_PROPERTY_TYPE, actualType, actualFormat, items, bytesAfter, data); + MemorySegment value = data.get(PTR, 0); + if (status != SUCCESS || value.equals(MemorySegment.NULL)) return null; + long length = items.get(LONG, 0); + byte[] bytes = value.reinterpret(length).toArray(ValueLayout.JAVA_BYTE); + call(Handles.X_FREE, value); + return new String(bytes, StandardCharsets.UTF_8); + } + + /** @return {@code true} when the window carries the property at all */ + static boolean hasProperty(MemorySegment display, Arena arena, long window, long property) { + MemorySegment actualType = arena.allocate(LONG); + MemorySegment actualFormat = arena.allocate(INT); + MemorySegment items = arena.allocate(LONG); + MemorySegment bytesAfter = arena.allocate(LONG); + MemorySegment data = arena.allocate(PTR); + int status = (int) call(Handles.X_GET_WINDOW_PROPERTY, display, window, property, 0L, 0L, 0, + ANY_PROPERTY_TYPE, actualType, actualFormat, items, bytesAfter, data); + MemorySegment value = data.get(PTR, 0); + if (!value.equals(MemorySegment.NULL)) call(Handles.X_FREE, value); + return status == SUCCESS && actualType.get(LONG, 0) != 0; + } + + // ---- visuals ---- + + /** + * Looks a visual up by id. + * + * @return its {@code XVisualInfo} (owned by Xlib, to be released with {@link #free}) + * or {@link MemorySegment#NULL} when the id is unknown + */ + static MemorySegment visualInfo(MemorySegment display, Arena arena, long visualId) { + MemorySegment template = arena.allocate(VISUAL_INFO_SIZE); + template.set(LONG, VISUAL_INFO_VISUALID, visualId); + MemorySegment count = arena.allocate(INT); + MemorySegment info = (MemorySegment) call(Handles.X_GET_VISUAL_INFO, display, + VISUAL_ID_MASK, template, count); + if (info.equals(MemorySegment.NULL) || count.get(INT, 0) < 1) return MemorySegment.NULL; + return info.reinterpret(VISUAL_INFO_SIZE); + } + + static void free(MemorySegment pointer) { + call(Handles.X_FREE, pointer); + } + + // ---- windows ---- + + static long createColormap(MemorySegment display, long window, MemorySegment visual) { + return (long) call(Handles.X_CREATE_COLORMAP, display, window, visual, ALLOC_NONE); + } + + static long createWindow(MemorySegment display, long parent, int width, int height, int depth, + MemorySegment visual, MemorySegment attributes, long valueMask) { + return (long) call(Handles.X_CREATE_WINDOW, display, parent, 0, 0, width, height, 0, depth, + INPUT_OUTPUT, visual, valueMask, attributes); + } + + static void destroyWindow(MemorySegment display, long window) { + call(Handles.X_DESTROY_WINDOW, display, window); + } + + static void selectInput(MemorySegment display, long window, long mask) { + call(Handles.X_SELECT_INPUT, display, window, mask); + } + + /** + * Tells the panel how big the icon wants to be. XEmbed trays lay their children + * out from these hints; without them a panel is free to allocate a sliver. + */ + static void setSizeHints(MemorySegment display, Arena arena, long window, int size) { + MemorySegment hints = arena.allocate(SIZE_HINTS_SIZE); + hints.fill((byte) 0); + hints.set(LONG, SIZE_HINTS_FLAGS, P_MIN_SIZE | P_MAX_SIZE | P_BASE_SIZE); + hints.set(INT, SIZE_HINTS_MIN_WIDTH, size); + hints.set(INT, SIZE_HINTS_MIN_HEIGHT, size); + hints.set(INT, SIZE_HINTS_MAX_WIDTH, size); + hints.set(INT, SIZE_HINTS_MAX_HEIGHT, size); + hints.set(INT, SIZE_HINTS_BASE_WIDTH, size); + hints.set(INT, SIZE_HINTS_BASE_HEIGHT, size); + call(Handles.X_SET_WM_NORMAL_HINTS, display, window, hints); + } + + static void resizeWindow(MemorySegment display, long window, int width, int height) { + call(Handles.X_RESIZE_WINDOW, display, window, width, height); + } + + static void mapWindow(MemorySegment display, long window) { + call(Handles.X_MAP_WINDOW, display, window); + } + + static void unmapWindow(MemorySegment display, long window) { + call(Handles.X_UNMAP_WINDOW, display, window); + } + + // ---- events ---- + + static int pending(MemorySegment display) { + return (int) call(Handles.X_PENDING, display); + } + + static void nextEvent(MemorySegment display, MemorySegment event) { + call(Handles.X_NEXT_EVENT, display, event); + } + + static void sendEvent(MemorySegment display, long window, long mask, MemorySegment event) { + call(Handles.X_SEND_EVENT, display, window, 0, mask, event); + } + + // ---- drawing ---- + + static MemorySegment createGC(MemorySegment display, long drawable) { + return (MemorySegment) call(Handles.X_CREATE_GC, display, drawable, 0L, MemorySegment.NULL); + } + + static void freeGC(MemorySegment display, MemorySegment gc) { + call(Handles.X_FREE_GC, display, gc); + } + + /** Wraps a caller-owned pixel buffer in an {@code XImage} of 32-bit ARGB pixels. */ + static MemorySegment createImage(MemorySegment display, MemorySegment visual, int depth, + MemorySegment data, int width, int height) { + MemorySegment image = (MemorySegment) call(Handles.X_CREATE_IMAGE, display, visual, depth, + Z_PIXMAP, 0, data, width, height, 32, 0); + return image.equals(MemorySegment.NULL) ? image : image.reinterpret(IMAGE_DATA + 8); + } + + /** Frees the {@code XImage} without touching the pixel buffer, which is ours. */ + static void destroyImage(MemorySegment image) { + image.set(PTR, IMAGE_DATA, MemorySegment.NULL); + call(Handles.X_FREE, image); + } + + static void putImage(MemorySegment display, long drawable, MemorySegment gc, + MemorySegment image, int width, int height) { + call(Handles.X_PUT_IMAGE, display, drawable, gc, image, 0, 0, 0, 0, width, height); + } + + private static Object call(MethodHandle handle, Object... args) { + try { + return handle.invokeWithArguments(args); + } catch (Throwable t) { + throw new IllegalStateException("libX11 call failed", t); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/tray/X11Tray.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/tray/X11Tray.java new file mode 100644 index 0000000..0028151 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/tray/X11Tray.java @@ -0,0 +1,508 @@ +package eu.lixko.ts3j.client.ui.tray; + +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.RenderingHints; +import java.awt.image.BufferedImage; +import java.awt.image.DataBufferInt; +import java.lang.foreign.Arena; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.ValueLayout; +import java.util.function.IntFunction; +import java.util.function.LongPredicate; + +/** + * A tray icon docked into the panel's notification area by hand, over the + * freedesktop system tray protocol. + * + *

    AWT can do this too, but its icon is never transparent on X11: the toolkit + * embeds an ordinary window of the screen's default (opaque) visual and fills it + * with a background colour before drawing, so every icon sits on a coloured box. + * Panels that support transparency — MATE's, Xfce's, GNOME's — advertise an ARGB + * visual in {@code _NET_SYSTEM_TRAY_VISUAL} and composite the icon themselves; + * all that is needed is to dock a window of that visual, which is what + * this class does. + * + *

    Everything here runs on one thread of its own, which owns the display + * connection and pumps the X event queue; the rest of the client only posts new + * icons to it. + */ +public final class X11Tray implements TrayBackend { + + /** The size to ask for; the panel resizes us to whatever it wants. */ + private static final int DEFAULT_SIZE = 24; + private static final int POLL_MS = 40; + /** How long to give the panel to adopt the icon before falling back to AWT. */ + private static final int DOCK_TIMEOUT_MS = 500; + /** Anything narrower than this is a sliver, not an icon the panel meant to give us. */ + private static final int MIN_SENSIBLE_SIZE = 8; + /** A tall panel should still not get a huge icon. */ + private static final int MAX_ICON_SIZE = 64; + /** + * Panels that composite the icon themselves need not send us a single expose, so + * the icon is also repainted at this interval — it costs one 24×24 image. + */ + private static final int REPAINT_MS = 2000; + + /** {@code _NET_SYSTEM_TRAY_OPCODE} message: dock this window. */ + private static final long SYSTEM_TRAY_REQUEST_DOCK = 0; + /** {@code _XEMBED_INFO} flag: the icon wants to be mapped. */ + private static final long XEMBED_MAPPED = 1; + + private final Listener listener; + /** Lives as long as the icon: the display connection and every buffer we pass to it. */ + private final Arena arena = Arena.ofShared(); + + private final MemorySegment display; + private final long root; + private final long window; + private final MemorySegment visual; + private final int depth; + private final MemorySegment gc; + + private final long selectionAtom; + private final long opcodeAtom; + private final long managerAtom; + + private final Thread thread; + private volatile boolean running = true; + /** Set once the panel has reparented the icon into itself. */ + private volatile boolean docked; + /** The square size last asked of the panel, so we ask only once per size. */ + private int requested; + + /** The icon and the size the panel gave us, both read by the event thread. */ + private volatile IntFunction render; + private volatile int width = DEFAULT_SIZE; + private volatile int height = DEFAULT_SIZE; + private volatile boolean dirty = true; + + /** The pixel buffer handed to X, kept until the icon's size changes. */ + private MemorySegment pixels; + private long lastDrawn; + private MemorySegment image; + private int imageWidth; + private int imageHeight; + + /** + * Docks an icon into the notification area. + * + * @return the icon, or {@code null} when this is not an X11 session, there is no + * notification area, or it cannot show transparent icons — the caller should then + * fall back to AWT's tray, which works everywhere but always draws a background + */ + public static X11Tray create(Listener listener, IntFunction initial) { + if (!X11.isAvailable()) { + TrayLog.debug("libX11 is not available"); + return null; + } + try { + X11Tray tray = new X11Tray(listener, initial); + TrayLog.debug("docked into the notification area, " + tray.width + "x" + tray.height + + " in an ARGB visual"); + return tray; + } catch (RuntimeException e) { + TrayLog.debug("not usable: " + e.getMessage()); + return null; + } + } + + private X11Tray(Listener listener, IntFunction initial) { + this.listener = listener; + this.render = initial; + + display = X11.openDisplay(); + if (display.equals(MemorySegment.NULL)) throw new Unsupported("no display"); + boolean ok = false; + try { + int screen = X11.defaultScreen(display); + root = X11.rootWindow(display, screen); + + selectionAtom = X11.internAtom(display, arena, "_NET_SYSTEM_TRAY_S" + screen); + opcodeAtom = X11.internAtom(display, arena, "_NET_SYSTEM_TRAY_OPCODE"); + managerAtom = X11.internAtom(display, arena, "MANAGER"); + + long manager = X11.selectionOwner(display, selectionAtom); + if (manager == 0) throw new Unsupported("no notification area"); + + visual = argbVisual(manager); + depth = 32; // argbVisual() accepts nothing else + window = createWindow(); + gc = X11.createGC(display, window); + + // Panels announce themselves with a MANAGER message when they (re)start, + // which is our cue to dock again. + X11.selectInput(display, root, X11.STRUCTURE_NOTIFY_MASK); + requestDock(manager); + // Docking is a request, not a call: a panel that ignores it would leave us + // with an invisible window and the user with no icon at all. + if (!awaitDock()) throw new Unsupported("the notification area did not adopt the icon"); + + thread = new Thread(this::pump, "x11-tray"); + thread.setDaemon(true); + thread.start(); + ok = true; + } finally { + if (!ok) { + X11.closeDisplay(display); + arena.close(); + } + } + } + + // ---- setup ---- + + /** + * @return the visual the panel wants transparent icons drawn in + * @throws Unsupported when it offers none, so nothing would be gained over AWT + */ + private MemorySegment argbVisual(long manager) { + long visualAtom = X11.internAtom(display, arena, "_NET_SYSTEM_TRAY_VISUAL"); + long visualId = X11.cardinalProperty(display, arena, manager, visualAtom, X11.XA_VISUALID); + if (visualId == 0) throw new Unsupported("the notification area is not transparent"); + + MemorySegment info = X11.visualInfo(display, arena, visualId); + if (info.equals(MemorySegment.NULL)) throw new Unsupported("unknown visual " + visualId); + try { + int visualDepth = info.get(ValueLayout.JAVA_INT, X11.VISUAL_INFO_DEPTH); + if (visualDepth != 32) { + throw new Unsupported("visual " + visualId + " has depth " + visualDepth); + } + // The XVisualInfo itself is Xlib's, but the Visual it points at outlives it. + return info.get(X11.PTR, X11.VISUAL_INFO_VISUAL); + } finally { + X11.free(info); + } + } + + private long createWindow() { + MemorySegment attributes = arena.allocate(X11.ATTRIBUTES_SIZE); + // Fully transparent background, and no border pixmap inherited from the root: + // a window whose depth differs from its parent's must name its own. + attributes.set(ValueLayout.JAVA_LONG, X11.ATTRIBUTES_BACKGROUND_PIXEL, 0); + attributes.set(ValueLayout.JAVA_LONG, X11.ATTRIBUTES_BORDER_PIXEL, 0); + attributes.set(ValueLayout.JAVA_LONG, X11.ATTRIBUTES_COLORMAP, + X11.createColormap(display, root, visual)); + attributes.set(ValueLayout.JAVA_LONG, X11.ATTRIBUTES_EVENT_MASK, + X11.EXPOSURE_MASK | X11.STRUCTURE_NOTIFY_MASK | X11.BUTTON_PRESS_MASK); + long mask = X11.CW_BACK_PIXEL | X11.CW_BORDER_PIXEL | X11.CW_COLORMAP | X11.CW_EVENT_MASK; + + long id = X11.createWindow(display, root, DEFAULT_SIZE, DEFAULT_SIZE, depth, visual, + attributes, mask); + if (id == 0) throw new Unsupported("could not create the icon window"); + + // Panels lay their icons out from these; without them MATE's allocates a + // one-pixel-wide sliver, which looks exactly like no icon at all. + X11.setSizeHints(display, arena, id, DEFAULT_SIZE); + + X11.setText(display, arena, id, X11.internAtom(display, arena, "WM_NAME"), + X11.XA_STRING, "TeamSpook TS3j"); + // XEMBED protocol version 0, and "please map me". + long xembedInfo = X11.internAtom(display, arena, "_XEMBED_INFO"); + X11.setCardinals(display, arena, id, xembedInfo, xembedInfo, 0, XEMBED_MAPPED); + return id; + } + + /** Asks the notification area to adopt our window. */ + private void requestDock(long manager) { + MemorySegment event = arena.allocate(X11.EVENT_SIZE); + event.fill((byte) 0); + event.set(ValueLayout.JAVA_INT, X11.EVENT_TYPE, X11.CLIENT_MESSAGE); + event.set(ValueLayout.JAVA_LONG, X11.EVENT_WINDOW, manager); + event.set(ValueLayout.JAVA_LONG, X11.CLIENT_MESSAGE_TYPE, opcodeAtom); + event.set(ValueLayout.JAVA_INT, X11.CLIENT_MESSAGE_FORMAT, 32); + event.set(ValueLayout.JAVA_LONG, X11.CLIENT_MESSAGE_DATA, 0); // CurrentTime + event.set(ValueLayout.JAVA_LONG, X11.CLIENT_MESSAGE_DATA + 8, SYSTEM_TRAY_REQUEST_DOCK); + event.set(ValueLayout.JAVA_LONG, X11.CLIENT_MESSAGE_DATA + 16, window); + X11.sendEvent(display, manager, X11.NO_EVENT_MASK, event); + X11.flush(display); + } + + /** + * Waits for the panel to reparent the icon into itself. + * + * @return {@code false} when it did not within {@link #DOCK_TIMEOUT_MS} + */ + private boolean awaitDock() { + MemorySegment event = arena.allocate(X11.EVENT_SIZE); + long deadline = System.currentTimeMillis() + DOCK_TIMEOUT_MS; + while (!docked && System.currentTimeMillis() < deadline) { + while (!docked && X11.pending(display) > 0) { + X11.nextEvent(display, event); + handle(event); + } + if (docked) break; + try { + Thread.sleep(POLL_MS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + } + return docked; + } + + // ---- TrayBackend ---- + + @Override + public void setIcon(IntFunction render) { + this.render = render; + dirty = true; + } + + @Override + public void setTooltip(String tooltip) { + // Panels take the tooltip from the icon window's name; those that don't show + // nothing, which is what AWT's own icon does on X11 anyway. + synchronized (this) { + if (!running) return; + X11.setText(display, arena, window, X11.internAtom(display, arena, "WM_NAME"), + X11.XA_STRING, tooltip); + X11.setText(display, arena, window, X11.internAtom(display, arena, "_NET_WM_NAME"), + X11.internAtom(display, arena, "UTF8_STRING"), tooltip); + X11.flush(display); + } + } + + /** + * Sends the window manager an {@code _NET_ACTIVE_WINDOW} request for the named + * window — the EWMH way of saying "the user asked for this window", which is + * honoured where a plain raise is not. + */ + @Override + public boolean activateWindow(String title) { + synchronized (this) { + if (!running) return false; + long target = findWindow(title); + if (target == 0) { + TrayLog.debug("no window named \"" + title + "\" to activate"); + return false; + } + TrayLog.debug("activating window 0x" + Long.toHexString(target)); + + MemorySegment event = arena.allocate(X11.EVENT_SIZE); + event.fill((byte) 0); + event.set(ValueLayout.JAVA_INT, X11.EVENT_TYPE, X11.CLIENT_MESSAGE); + event.set(ValueLayout.JAVA_LONG, X11.EVENT_WINDOW, target); + event.set(ValueLayout.JAVA_LONG, X11.CLIENT_MESSAGE_TYPE, + X11.internAtom(display, arena, "_NET_ACTIVE_WINDOW")); + event.set(ValueLayout.JAVA_INT, X11.CLIENT_MESSAGE_FORMAT, 32); + // Source indication 2: a pager or tray acting for the user, which window + // managers accept without their focus-stealing rules getting in the way. + event.set(ValueLayout.JAVA_LONG, X11.CLIENT_MESSAGE_DATA, 2); + X11.sendEvent(display, root, + X11.SUBSTRUCTURE_NOTIFY_MASK | X11.SUBSTRUCTURE_REDIRECT_MASK, event); + X11.flush(display); + return true; + } + } + + /** + * Finds one of this process' own top-level windows: the one with the given title + * for choice, else any window the window manager is managing for us. + * + *

    Windows are matched by {@code _NET_WM_PID} rather than by name alone, and + * the title is read from {@code _NET_WM_NAME} because {@code WM_NAME} cannot + * carry anything outside Latin-1. + */ + private long findWindow(String title) { + long pid = ProcessHandle.current().pid(); + long pidAtom = X11.internAtom(display, arena, "_NET_WM_PID"); + long nameAtom = X11.internAtom(display, arena, "_NET_WM_NAME"); + long stateAtom = X11.internAtom(display, arena, "WM_STATE"); + + long found = findWindow(root, 0, w -> + X11.cardinalProperty(display, arena, w, pidAtom, X11.ANY_PROPERTY_TYPE) == pid + && title.equals(X11.textProperty(display, arena, w, nameAtom))); + if (found != 0) return found; + return findWindow(root, 0, w -> + X11.cardinalProperty(display, arena, w, pidAtom, X11.ANY_PROPERTY_TYPE) == pid + && X11.hasProperty(display, arena, w, stateAtom)); + } + + /** + * Walks the window tree below {@code parent}. Only the top few levels are looked + * at: a reparenting window manager puts client windows one or two frames below + * the root. + */ + private long findWindow(long parent, int depth, LongPredicate match) { + if (depth > 3) return 0; + for (long child : X11.children(display, arena, parent)) { + if (match.test(child)) return child; + long found = findWindow(child, depth + 1, match); + if (found != 0) return found; + } + return 0; + } + + @Override + public String description() { + return "docked into the notification area, " + width + "x" + height + ", transparent"; + } + + @Override + public void dispose() { + if (!running) return; + running = false; + try { + thread.join(500); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + synchronized (this) { + if (image != null) X11.destroyImage(image); + X11.freeGC(display, gc); + X11.destroyWindow(display, window); + X11.closeDisplay(display); + } + arena.close(); + } + + // ---- event thread ---- + + private void pump() { + MemorySegment event = arena.allocate(X11.EVENT_SIZE); + while (running) { + try { + synchronized (this) { + while (running && X11.pending(display) > 0) { + X11.nextEvent(display, event); + handle(event); + } + boolean due = System.currentTimeMillis() - lastDrawn >= REPAINT_MS; + if (running && (dirty || due)) { + dirty = false; + lastDrawn = System.currentTimeMillis(); + draw(); + } + } + Thread.sleep(POLL_MS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } catch (RuntimeException e) { + TrayLog.debug("the display connection failed: " + e.getMessage()); + return; // the display died with the panel or the session + } + } + } + + private void handle(MemorySegment event) { + switch (event.get(ValueLayout.JAVA_INT, X11.EVENT_TYPE)) { + case X11.EXPOSE -> dirty = true; + case X11.CONFIGURE_NOTIFY -> { + if (event.get(ValueLayout.JAVA_LONG, X11.CONFIGURE_WINDOW) != window) return; + int w = event.get(ValueLayout.JAVA_INT, X11.CONFIGURE_WIDTH); + int h = event.get(ValueLayout.JAVA_INT, X11.CONFIGURE_HEIGHT); + if (w == width && h == height) return; + width = w; + height = h; + dirty = true; + askForSquare(); + } + case X11.REPARENT_NOTIFY -> { + if (event.get(ValueLayout.JAVA_LONG, X11.REPARENT_WINDOW) != window) return; + if (event.get(ValueLayout.JAVA_LONG, X11.REPARENT_PARENT) == root) { + // The panel went away and handed the window back to the root; hide + // it so it does not turn up in the middle of the screen. + docked = false; + X11.unmapWindow(display, window); + } else { + // Adopted. The panel is meant to map us because of _XEMBED_INFO, + // but mapping ourselves costs nothing and does not depend on it. + docked = true; + X11.mapWindow(display, window); + dirty = true; + } + } + case X11.MAP_NOTIFY -> dirty = true; + case X11.BUTTON_PRESS -> { + long button = event.get(ValueLayout.JAVA_INT, X11.BUTTON_BUTTON); + int x = event.get(ValueLayout.JAVA_INT, X11.BUTTON_X_ROOT); + int y = event.get(ValueLayout.JAVA_INT, X11.BUTTON_Y_ROOT); + if (button == 1) { + listener.activated(); + } else if (button == 3) { + listener.menuRequested(x, y); + } + } + case X11.CLIENT_MESSAGE -> { + // A panel started: dock into it. + if (event.get(ValueLayout.JAVA_LONG, X11.CLIENT_MESSAGE_TYPE) != managerAtom) return; + if (event.get(ValueLayout.JAVA_LONG, X11.CLIENT_MESSAGE_DATA + 8) != selectionAtom) { + return; + } + long manager = event.get(ValueLayout.JAVA_LONG, X11.CLIENT_MESSAGE_DATA + 16); + if (manager != 0) { + requestDock(manager); + X11.mapWindow(display, window); + dirty = true; + } + } + default -> { + } + } + } + + /** + * Asks for a square icon when the panel has given us a sliver — its idea of the + * icon size is then the other side, and a panel that lays out from the size hints + * grants it. Each size is asked for once, so a panel that refuses cannot put us + * in a loop. + */ + private void askForSquare() { + int narrow = Math.min(width, height); + int wide = Math.max(width, height); + // Only a sliver is worth arguing about; any sane allocation is left alone. + if (narrow >= MIN_SENSIBLE_SIZE) return; + int wanted = Math.min(wide, MAX_ICON_SIZE); + if (wanted <= 0 || wanted == requested) return; + requested = wanted; + X11.setSizeHints(display, arena, window, wanted); + X11.resizeWindow(display, window, wanted, wanted); + X11.flush(display); + } + + /** Paints the current icon over the whole window, alpha and all. */ + private void draw() { + IntFunction painter = render; + if (painter == null) return; + int w = width; + int h = height; + if (w <= 0 || h <= 0) return; + + if (image == null || imageWidth != w || imageHeight != h) { + if (image != null) X11.destroyImage(image); + pixels = arena.allocate((long) w * h * Integer.BYTES); + image = X11.createImage(display, visual, depth, pixels, w, h); + imageWidth = w; + imageHeight = h; + if (image.equals(MemorySegment.NULL)) { + image = null; + return; + } + } + + // X wants the pixels premultiplied, in the server's own byte order — which + // for a 32-bit ARGB visual on a local display is an int per pixel. + BufferedImage buffer = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE); + Graphics2D g = buffer.createGraphics(); + g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, + RenderingHints.VALUE_INTERPOLATION_BILINEAR); + Image icon = painter.apply(Math.min(w, h)); + if (icon != null) g.drawImage(icon, 0, 0, w, h, null); + g.dispose(); + + int[] data = ((DataBufferInt) buffer.getRaster().getDataBuffer()).getData(); + MemorySegment.copy(data, 0, pixels, ValueLayout.JAVA_INT, 0, data.length); + X11.putImage(display, window, gc, image, w, h); + X11.flush(display); + } + + /** Thrown while setting up when this desktop cannot do what we need. */ + private static final class Unsupported extends RuntimeException { + Unsupported(String message) { + super(message); + } + } +} diff --git a/ts3-client/swing/src/main/resources/com/ts3client/ui/app-icon-small.svg b/ts3-client/swing/src/main/resources/eu/lixko/ts3j/client/ui/app-icon-small.svg similarity index 100% rename from ts3-client/swing/src/main/resources/com/ts3client/ui/app-icon-small.svg rename to ts3-client/swing/src/main/resources/eu/lixko/ts3j/client/ui/app-icon-small.svg diff --git a/ts3-client/swing/src/main/resources/com/ts3client/ui/app-icon.svg b/ts3-client/swing/src/main/resources/eu/lixko/ts3j/client/ui/app-icon.svg similarity index 100% rename from ts3-client/swing/src/main/resources/com/ts3client/ui/app-icon.svg rename to ts3-client/swing/src/main/resources/eu/lixko/ts3j/client/ui/app-icon.svg diff --git a/ts3-client/swing/src/main/resources/com/ts3client/ui/laf/FlatDarkLaf.properties b/ts3-client/swing/src/main/resources/eu/lixko/ts3j/client/ui/laf/FlatDarkLaf.properties similarity index 100% rename from ts3-client/swing/src/main/resources/com/ts3client/ui/laf/FlatDarkLaf.properties rename to ts3-client/swing/src/main/resources/eu/lixko/ts3j/client/ui/laf/FlatDarkLaf.properties diff --git a/ts3-client/swing/src/main/resources/com/ts3client/ui/laf/FlatLaf.properties b/ts3-client/swing/src/main/resources/eu/lixko/ts3j/client/ui/laf/FlatLaf.properties similarity index 100% rename from ts3-client/swing/src/main/resources/com/ts3client/ui/laf/FlatLaf.properties rename to ts3-client/swing/src/main/resources/eu/lixko/ts3j/client/ui/laf/FlatLaf.properties diff --git a/ts3-client/swing/src/test/java/com/ts3client/ui/DisplayScaleTest.java b/ts3-client/swing/src/test/java/com/ts3client/ui/DisplayScaleTest.java deleted file mode 100644 index a4edf1a..0000000 --- a/ts3-client/swing/src/test/java/com/ts3client/ui/DisplayScaleTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.ts3client.ui; - -import org.junit.jupiter.api.Test; - -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -class DisplayScaleTest { - - private static final List KWINRC = List.of( - "[Plugins]", - "Scale=9", - "", - "[Xwayland]", - "Scale = 1.5", - "", - "[Xwayland][Extra]", - "Scale=2"); - - @Test - void readsTheKeyFromItsOwnGroupOnly() { - assertEquals("1.5", DisplayScale.iniValue(KWINRC, "Xwayland", "Scale")); - } - - @Test - void missingKeyIsNull() { - assertNull(DisplayScale.iniValue(KWINRC, "Xwayland", "Other")); - assertNull(DisplayScale.iniValue(KWINRC, "Compositing", "Scale")); - } -} diff --git a/ts3-client/swing/src/test/java/com/ts3client/ui/MicrophoneTestTest.java b/ts3-client/swing/src/test/java/com/ts3client/ui/MicrophoneTestTest.java deleted file mode 100644 index 2a39cfb..0000000 --- a/ts3-client/swing/src/test/java/com/ts3client/ui/MicrophoneTestTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.ts3client.ui; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; - -class MicrophoneTestTest { - - private static int sampleAt(byte[] pcm, int index) { - return (short) (((pcm[2 * index + 1] & 0xFF) << 8) | (pcm[2 * index] & 0xFF)); - } - - @Test - void convertsFloatSamplesToLittleEndianPcm() { - byte[] pcm = MicrophoneTest.toPcm16(new float[]{0f, 1f, -1f, 0.5f}); - assertEquals(8, pcm.length); - assertEquals(0, sampleAt(pcm, 0)); - assertEquals(32767, sampleAt(pcm, 1)); - assertEquals(-32767, sampleAt(pcm, 2)); - assertEquals(16384, sampleAt(pcm, 3), 1); - } - - @Test - void clampsSamplesOutsideRange() { - byte[] pcm = MicrophoneTest.toPcm16(new float[]{2f, -2f}); - assertEquals(32767, sampleAt(pcm, 0)); - assertEquals(-32767, sampleAt(pcm, 1)); - } - - @Test - void upmixRepeatsMonoAcrossChannels() { - byte[] mono = MicrophoneTest.toPcm16(new float[]{0.25f, -0.25f}); - byte[] stereo = MicrophoneTest.upmix(mono, 2); - assertEquals(mono.length * 2, stereo.length); - // Each mono sample appears once per channel, in order. - assertEquals(sampleAt(mono, 0), sampleAt(stereo, 0)); - assertEquals(sampleAt(mono, 0), sampleAt(stereo, 1)); - assertEquals(sampleAt(mono, 1), sampleAt(stereo, 2)); - assertEquals(sampleAt(mono, 1), sampleAt(stereo, 3)); - } - - @Test - void upmixIsIdentityForOneChannel() { - byte[] mono = MicrophoneTest.toPcm16(new float[]{0.1f, 0.2f, 0.3f}); - assertArrayEquals(mono, MicrophoneTest.upmix(mono, 1)); - } -} diff --git a/ts3-client/swing/src/test/java/eu/lixko/ts3j/client/ui/DisplayScaleTest.java b/ts3-client/swing/src/test/java/eu/lixko/ts3j/client/ui/DisplayScaleTest.java new file mode 100644 index 0000000..9effd05 --- /dev/null +++ b/ts3-client/swing/src/test/java/eu/lixko/ts3j/client/ui/DisplayScaleTest.java @@ -0,0 +1,32 @@ +package eu.lixko.ts3j.client.ui; + +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class DisplayScaleTest { + + private static final List KWINRC = List.of( + "[Plugins]", + "Scale=9", + "", + "[Xwayland]", + "Scale = 1.5", + "", + "[Xwayland][Extra]", + "Scale=2"); + + @Test + void readsTheKeyFromItsOwnGroupOnly() { + assertEquals("1.5", DisplayScale.iniValue(KWINRC, "Xwayland", "Scale")); + } + + @Test + void missingKeyIsNull() { + assertNull(DisplayScale.iniValue(KWINRC, "Xwayland", "Other")); + assertNull(DisplayScale.iniValue(KWINRC, "Compositing", "Scale")); + } +} diff --git a/ts3-client/swing/src/test/java/eu/lixko/ts3j/client/ui/MicrophoneTestTest.java b/ts3-client/swing/src/test/java/eu/lixko/ts3j/client/ui/MicrophoneTestTest.java new file mode 100644 index 0000000..8d8ac4e --- /dev/null +++ b/ts3-client/swing/src/test/java/eu/lixko/ts3j/client/ui/MicrophoneTestTest.java @@ -0,0 +1,48 @@ +package eu.lixko.ts3j.client.ui; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class MicrophoneTestTest { + + private static int sampleAt(byte[] pcm, int index) { + return (short) (((pcm[2 * index + 1] & 0xFF) << 8) | (pcm[2 * index] & 0xFF)); + } + + @Test + void convertsFloatSamplesToLittleEndianPcm() { + byte[] pcm = MicrophoneTest.toPcm16(new float[]{0f, 1f, -1f, 0.5f}); + assertEquals(8, pcm.length); + assertEquals(0, sampleAt(pcm, 0)); + assertEquals(32767, sampleAt(pcm, 1)); + assertEquals(-32767, sampleAt(pcm, 2)); + assertEquals(16384, sampleAt(pcm, 3), 1); + } + + @Test + void clampsSamplesOutsideRange() { + byte[] pcm = MicrophoneTest.toPcm16(new float[]{2f, -2f}); + assertEquals(32767, sampleAt(pcm, 0)); + assertEquals(-32767, sampleAt(pcm, 1)); + } + + @Test + void upmixRepeatsMonoAcrossChannels() { + byte[] mono = MicrophoneTest.toPcm16(new float[]{0.25f, -0.25f}); + byte[] stereo = MicrophoneTest.upmix(mono, 2); + assertEquals(mono.length * 2, stereo.length); + // Each mono sample appears once per channel, in order. + assertEquals(sampleAt(mono, 0), sampleAt(stereo, 0)); + assertEquals(sampleAt(mono, 0), sampleAt(stereo, 1)); + assertEquals(sampleAt(mono, 1), sampleAt(stereo, 2)); + assertEquals(sampleAt(mono, 1), sampleAt(stereo, 3)); + } + + @Test + void upmixIsIdentityForOneChannel() { + byte[] mono = MicrophoneTest.toPcm16(new float[]{0.1f, 0.2f, 0.3f}); + assertArrayEquals(mono, MicrophoneTest.upmix(mono, 1)); + } +} diff --git a/ts3-client/tools/AppIcon.java b/ts3-client/tools/AppIcon.java index 2efdfa5..9846cc9 100644 --- a/ts3-client/tools/AppIcon.java +++ b/ts3-client/tools/AppIcon.java @@ -41,7 +41,7 @@ public class AppIcon { public static void main(String[] args) throws IOException { Path root = Path.of(""); - Path ui = root.resolve("ts3-client/swing/src/main/resources/com/ts3client/ui"); + Path ui = root.resolve("ts3-client/swing/src/main/resources/eu/lixko/ts3j/client/ui"); Files.writeString(ui.resolve("app-icon.svg"), svg(path(icon(LARGE), 6))); Files.writeString(ui.resolve("app-icon-small.svg"), svg(path(icon(SMALL), 0.5))); Files.writeString(root.resolve("android/app/src/main/res/drawable/ic_launcher_foreground.xml"),