Welcome to mirror list, hosted at ThFree Co, Russian Federation.

TalkingUI.cpp « mumble « src - github.com/mumble-voip/mumble.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 03ff76b88217b479fef98cc2921c6c5adbaeb549 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
// Copyright 2020-2021 The Mumble Developers. All rights reserved.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file at the root of the
// Mumble source tree or at <https://www.mumble.info/LICENSE>.

#include "TalkingUI.h"
#include "Channel.h"
#include "ChannelListener.h"
#include "ClientUser.h"
#include "MainWindow.h"
#include "TalkingUIComponent.h"
#include "UserModel.h"
#include "widgets/MultiStyleWidgetWrapper.h"
#include "Global.h"

#include <QGroupBox>
#include <QGuiApplication>
#include <QHBoxLayout>
#include <QItemSelectionModel>
#include <QLabel>
#include <QModelIndex>
#include <QMouseEvent>
#include <QPalette>
#include <QScreen>
#include <QTextDocumentFragment>
#include <QVBoxLayout>
#include <QtCore/QDateTime>
#include <QtCore/QStringList>
#include <QtCore/QTimer>
#include <QtGui/QPainter>
#include <QtGui/QPixmap>

#include <algorithm>

TalkingUI::TalkingUI(QWidget *parent) : QWidget(parent), m_containers(), m_currentSelection(nullptr) {
	setupUI();
}

int TalkingUI::findContainer(int associatedChannelID, ContainerType type) const {
	for (std::size_t i = 0; i < m_containers.size(); i++) {
		const std::unique_ptr< TalkingUIContainer > &currentContainer = m_containers[i];

		if (currentContainer->getType() == type && currentContainer->getAssociatedChannelID() == associatedChannelID) {
			return static_cast< int >(i);
		}
	}

	return -1;
}

std::unique_ptr< TalkingUIContainer > TalkingUI::removeContainer(const TalkingUIContainer &container) {
	return removeContainer(container.getAssociatedChannelID(), container.getType());
}

std::unique_ptr< TalkingUIContainer > TalkingUI::removeContainer(int associatedChannelID, ContainerType type) {
	int index = findContainer(associatedChannelID, type);

	std::unique_ptr< TalkingUIContainer > container(nullptr);

	if (index >= 0) {
		// Move the container out of the vector
		container = std::move(m_containers[index]);
		m_containers.erase(m_containers.begin() + index);

		// If the container is currently selected, clear the selection
		if (isSelected(*container)) {
			setSelection(EmptySelection());
		}
	}

	return container;
}

std::unique_ptr< TalkingUIContainer > TalkingUI::removeIfSuperfluous(const TalkingUIContainer &container) {
	if (container.isEmpty() && !container.isPermanent()) {
		return removeContainer(container);
	}

	return nullptr;
}

struct container_ptr_less {
	bool operator()(const std::unique_ptr< TalkingUIContainer > &first,
					const std::unique_ptr< TalkingUIContainer > &second) {
		return *first < *second;
	}
};

void TalkingUI::sortContainers() {
	// Remove all containers from the UI
	for (auto &currentContainer : m_containers) {
		layout()->removeWidget(currentContainer->getWidget());
	}

	// Sort the containers
	std::sort(m_containers.begin(), m_containers.end(), container_ptr_less());

	// Add them again in the order they appear in the vector
	for (auto &currentContainer : m_containers) {
		layout()->addWidget(currentContainer->getWidget());
	}
}

TalkingUIUser *TalkingUI::findUser(unsigned int userSession) {
	for (auto &currentContainer : m_containers) {
		TalkingUIEntry *entry = currentContainer->get(userSession, EntryType::USER);

		if (entry) {
			// We know that it must be a TalkingUIUser since that is what we searched for
			return static_cast< TalkingUIUser * >(entry);
		}
	}

	return nullptr;
}

void TalkingUI::removeUser(unsigned int userSession) {
	TalkingUIUser *userEntry = findUser(userSession);

	if (userEntry) {
		// If the user that is going to be deleted is currently selected, clear the selection
		if (isSelected(*userEntry)) {
			setSelection(EmptySelection());
		}

		TalkingUIContainer *userContainer = userEntry->getContainer();

		userContainer->removeEntry(userEntry);

		removeIfSuperfluous(*userContainer);

		updateUI();
	}
}

void TalkingUI::addListener(const ClientUser *user, const Channel *channel) {
	TalkingUIChannelListener *existingEntry = findListener(user->uiSession, channel->iId);

	if (!existingEntry) {
		// Only create entry if it doesn't exist yet

		// First make sure the channel exists
		addChannel(channel);

		std::unique_ptr< TalkingUIContainer > &channelContainer =
			m_containers[findContainer(channel->iId, ContainerType::CHANNEL)];

		std::unique_ptr< TalkingUIChannelListener > listenerEntry =
			std::make_unique< TalkingUIChannelListener >(*user, *channel);

		channelContainer->addEntry(std::move(listenerEntry));

		sortContainers();
	}
}

TalkingUIChannelListener *TalkingUI::findListener(unsigned int userSession, int channelID) {
	int channelIndex = findContainer(channelID, ContainerType::CHANNEL);

	if (channelIndex >= 0) {
		std::unique_ptr< TalkingUIContainer > &channelContainer = m_containers[channelIndex];

		TalkingUIEntry *entry = channelContainer->get(userSession, EntryType::LISTENER);

		if (entry) {
			return static_cast< TalkingUIChannelListener * >(entry);
		}
	}

	return nullptr;
}

void TalkingUI::removeListener(unsigned int userSession, int channelID) {
	TalkingUIChannelListener *listenerEntry = findListener(userSession, channelID);

	if (listenerEntry) {
		// If the user that is going to be deleted is currently selected, clear the selection
		if (isSelected(*listenerEntry)) {
			setSelection(EmptySelection());
		}

		TalkingUIContainer *userContainer = listenerEntry->getContainer();

		userContainer->removeEntry(listenerEntry);

		removeIfSuperfluous(*userContainer);

		updateUI();
	}
}

void TalkingUI::removeAllListeners() {
	// Find all listener entries
	std::vector< TalkingUIEntry * > entriesToBeRemoved;
	for (auto &currentContainer : m_containers) {
		for (auto &currentEntry : currentContainer->getEntries()) {
			if (currentEntry->getType() == EntryType::LISTENER) {
				entriesToBeRemoved.push_back(currentEntry.get());
			}
		}
	}

	// remove the individual entries
	for (auto currentEntry : entriesToBeRemoved) {
		TalkingUIContainer *container = currentEntry->getContainer();

		container->removeEntry(currentEntry);

		removeIfSuperfluous(*container);
	}

	// if we removed something, update the UI
	if (entriesToBeRemoved.size() > 0) {
		updateUI();
	}
}

void TalkingUI::setupUI() {
	QVBoxLayout *layout = new QVBoxLayout;

	setLayout(layout);

	setWindowTitle(QObject::tr("Talking UI"));

	setAttribute(Qt::WA_ShowWithoutActivating);
	setWindowFlags(Qt::Dialog | Qt::WindowStaysOnTopHint);

	// Hide the "?" (context help) button in the title bar of the widget as we don't want
	// that due to it taking valuable screen space so that the title can't be displayed
	// properly and as the TalkingUI doesn't provide context help anyways, this is not a big loss.
	setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);

	connect(Global::get().mw->qtvUsers->selectionModel(), &QItemSelectionModel::currentChanged, this,
			&TalkingUI::on_mainWindowSelectionChanged);
}

void TalkingUI::setFontSize(MultiStyleWidgetWrapper &widgetWrapper) {
	const double fontFactor = Global::get().s.iTalkingUI_RelativeFontSize / 100.0;
	const int origLineHeight = QFontMetrics(font()).height();

	if (font().pixelSize() >= 0) {
		// font specified in pixels
		uint32_t pixelSize = static_cast< uint32_t >(std::max(fontFactor * font().pixelSize(), 1.0));
		widgetWrapper.setFontSize(pixelSize, true);
	} else {
		// font specified in points
		uint32_t pointSize =  static_cast< uint32_t >(std::max(fontFactor * font().pointSize(), 1.0));
		widgetWrapper.setFontSize(pointSize, false);
	}

	m_currentLineHeight = static_cast< int >(std::max(origLineHeight * fontFactor, 1.0));
}

void TalkingUI::updateStatusIcons(const ClientUser *user) {
	TalkingUIUser *userEntry = findUser(user->uiSession);

	if (!userEntry) {
		return;
	}

	TalkingUIUser::UserStatus status;
	status.muted        = user->bMute;
	status.selfMuted    = user->bSelfMute;
	status.localMuted   = user->bLocalMute;
	status.deafened     = user->bDeaf;
	status.selfDeafened = user->bSelfDeaf;

	userEntry->setStatus(status);
}

void TalkingUI::hideUser(unsigned int session) {
	removeUser(session);

	updateUI();
}

QString createChannelName(const Channel *chan, bool abbreviateName, int minPrefixChars, int minPostfixChars,
						  int idealMaxChars, int parentLevel, const QString &separator,
						  const QString &abbreviationIndicator, bool abbreviateCurrentChannel) {
	if (!abbreviateName) {
		return chan->qsName;
	}

	// Assemble list of relevant channel names (representing the channel hierarchy
	QStringList nameList;
	do {
		nameList << chan->qsName;

		chan = chan->cParent;
	} while (chan && nameList.size() < (parentLevel + 1));

	const bool reachedRoot = !chan;

	// We also want to abbreviate names that nominally have the same amount of characters before and
	// after abbreviation. However as we're typically not using mono-spaced fonts, the abbreviation
	// indicator might still occupy less space than the original text.
	const int abbreviableSize = minPrefixChars + minPostfixChars + abbreviationIndicator.size();

	// Iterate over all names and check how many of them could be abbreviated
	int totalCharCount = reachedRoot ? separator.size() : 0;
	for (int i = 0; i < nameList.size(); i++) {
		totalCharCount += nameList[i].size();

		if (i + 1 < nameList.size()) {
			// Account for the separator's size as well
			totalCharCount += separator.size();
		}
	}

	QString groupName = reachedRoot ? separator : QString();

	for (int i = nameList.size() - 1; i >= 0; i--) {
		if (totalCharCount > idealMaxChars && nameList[i].size() >= abbreviableSize
			&& (abbreviateCurrentChannel || i != 0)) {
			// Abbreviate the names as much as possible
			groupName += nameList[i].left(minPrefixChars) + abbreviationIndicator + nameList[i].right(minPostfixChars);
		} else {
			groupName += nameList[i];
		}

		if (i != 0) {
			groupName += separator;
		}
	}

	return groupName;
}

void TalkingUI::addChannel(const Channel *channel) {
	if (findContainer(channel->iId, ContainerType::CHANNEL) < 0) {
		// Create a QGroupBox for this channel
		const QString channelName =
			createChannelName(channel, Global::get().s.bTalkingUI_AbbreviateChannelNames, Global::get().s.iTalkingUI_PrefixCharCount,
							  Global::get().s.iTalkingUI_PostfixCharCount, Global::get().s.iTalkingUI_MaxChannelNameLength,
							  Global::get().s.iTalkingUI_ChannelHierarchyDepth, Global::get().s.qsTalkingUI_ChannelSeparator,
							  Global::get().s.qsTalkingUI_AbbreviationReplacement, Global::get().s.bTalkingUI_AbbreviateCurrentChannel);

		std::unique_ptr< TalkingUIChannel > channelContainer =
			std::make_unique< TalkingUIChannel >(channel->iId, channelName, *this);

		QWidget *channelWidget = channelContainer->getWidget();

		setFontSize(channelContainer->getStylableWidget());

		layout()->addWidget(channelWidget);

		m_containers.push_back(std::move(channelContainer));
	}
}

TalkingUIUser *TalkingUI::findOrAddUser(const ClientUser *user) {
	TalkingUIUser *oldUserEntry = findUser(user->uiSession);
	bool nameMatches            = true;

	if (oldUserEntry) {
		// We also verify whether the name for that user matches up (if it is contained in m_entries) in case
		// a user didn't get removed from the map but its ID got reused by a new client.

		nameMatches = oldUserEntry->getName() == user->qsName;

		if (!nameMatches) {
			// Hide and remove the stale user
			hideUser(user->uiSession);

			// reset pointer
			oldUserEntry = nullptr;
		}
	}

	// Make sure that the user's channel exists in this UI.
	// Note that this has to be done **after** the name check above as
	// the user might have been renamed in which case the abovementioned
	// code block removes the old user entry. If that user was the only
	// client in its channel, the channel gets removed as well. However
	// the code below expects the user's channel to exist.
	addChannel(user->cChannel);

	if (!oldUserEntry || !nameMatches) {
		// Create an entry for this user
		bool isSelf = Global::get().uiSession == user->uiSession;

		int channelIndex = findContainer(user->cChannel->iId, ContainerType::CHANNEL);
		if (channelIndex < 0) {
			qCritical("TalkingUI::findOrAddUser User's channel does not exist!");
			return nullptr;
		}
		std::unique_ptr< TalkingUIContainer > &channelContainer = m_containers[channelIndex];
		if (!channelContainer) {
			qCritical("TalkingUI::findOrAddUser requesting unknown channel!");
			return nullptr;
		}

		std::unique_ptr< TalkingUIUser > userEntry = std::make_unique< TalkingUIUser >(*user);
		TalkingUIUser *newUserEntry = userEntry.get();

		// * 1000 as the setting is in seconds whereas the timer expects milliseconds
		userEntry->setLifeTime(Global::get().s.iTalkingUI_SilentUserLifeTime * 1000);

		userEntry->restrictLifetime(!isSelf || !Global::get().s.bTalkingUI_LocalUserStaysVisible);

		userEntry->setPriority(isSelf ? EntryPriority::HIGH : EntryPriority::DEFAULT);

		QObject::connect(user, &ClientUser::localVolumeAdjustmentsChanged, this,
						 &TalkingUI::on_userLocalVolumeAdjustmentsChanged);

		// If this user is currently selected, mark him/her as such
		if (Global::get().mw && Global::get().mw->pmModel && Global::get().mw->pmModel->getSelectedUser() == user) {
			setSelection(UserSelection(userEntry->getWidget(), userEntry->getAssociatedUserSession()));
		}

		// As the font size of the newly created widget did not adapt to any StyleSheet it might have inherited
		// from its parents (the channel box), the size the talking icon is initialized to in the entry's
		// constructor is incorrect. Therefore we have to explicitly update it here.
		userEntry->setIconSize(m_currentLineHeight);

		// Actually add the user to the respective channel
		channelContainer->addEntry(std::move(userEntry));

		sortContainers();

		return newUserEntry;
	} else {
		return oldUserEntry;
	}
}

void TalkingUI::moveUserToChannel(unsigned int userSession, int channelID) {
	int targetChanIndex = findContainer(channelID, ContainerType::CHANNEL);

	if (targetChanIndex < 0) {
		qCritical("TalkingUI::moveUserToChannel Can't find channel for speaker");
		return;
	}

	std::unique_ptr< TalkingUIContainer > &targetChannel = m_containers[targetChanIndex];

	if (targetChannel->contains(userSession, EntryType::USER)) {
		// The given user is already in the target channel - nothing to do
		return;
	}

	// Iterate all containers in order to find the one the user is currently in
	TalkingUIUser *userEntry = findUser(userSession);

	if (userEntry) {
		TalkingUIContainer *oldContainer = userEntry->getContainer();

		targetChannel->addEntry(oldContainer->removeEntry(userEntry));

		removeIfSuperfluous(*oldContainer);

		sortContainers();
	} else {
		qCritical("TalkingUI::moveUserToChannel Unable to locate user");
		return;
	}

	updateUI();
}

void TalkingUI::updateUI() {
	// Use timer to execute this after all other events have been processed
	QTimer::singleShot(0, [this]() { adjustSize(); });
}

void TalkingUI::setSelection(const TalkingUISelection &selection) {
	if (dynamic_cast< const EmptySelection * >(&selection)) {
		// The selection is set to an empty selection
		if (m_currentSelection) {
			// There currently is a selection -> clear and remove it
			m_currentSelection->discard();
			m_currentSelection.reset();
		}
	} else {
		if (m_currentSelection) {
			if (selection == *m_currentSelection) {
				// Selection hasn't actually changed
				return;
			}

			// Discard old selection (it'll get deleted on re-assignment below)
			m_currentSelection->discard();
		}

		// Use the new selection (which at this point we know is not the empty selection)
		m_currentSelection = selection.cloneToHeap();

		m_currentSelection->apply();
		m_currentSelection->syncToMainWindow();
	}
}

bool TalkingUI::isSelected(const TalkingUIComponent &component) const {
	if (m_currentSelection) {
		return *m_currentSelection == component.getWidget();
	}

	return false;
}

void TalkingUI::mousePressEvent(QMouseEvent *event) {
	bool foundTarget = false;

	for (auto &currentContainer : m_containers) {
		QRect containerArea(currentContainer->getWidget()->mapToGlobal({ 0, 0 }),
							currentContainer->getWidget()->size());

		if (containerArea.contains(event->globalPos())) {
			for (auto &currentEntry : currentContainer->getEntries()) {
				QRect entryArea(currentEntry->getWidget()->mapToGlobal({ 0, 0 }), currentEntry->getWidget()->size());

				if (entryArea.contains(event->globalPos())) {
					switch (currentEntry->getType()) {
						case EntryType::USER:
							setSelection(
								UserSelection(currentEntry->getWidget(), currentEntry->getAssociatedUserSession()));
							break;
						case EntryType::LISTENER:
							TalkingUIChannelListener *listenerEntry =
								static_cast< TalkingUIChannelListener * >(currentEntry.get());
							setSelection(ListenerSelection(listenerEntry->getWidget(),
														   listenerEntry->getAssociatedUserSession(),
														   listenerEntry->getAssociatedChannelID()));
							break;
					}

					foundTarget = true;

					break;
				}
			}

			if (!foundTarget) {
				// Select channel itself
				setSelection(
					ChannelSelection(currentContainer->getWidget(), currentContainer->getAssociatedChannelID()));

				foundTarget = true;
			}

			break;
		}
	}

	if (foundTarget) {
		if (event->button() == Qt::RightButton && Global::get().mw) {
			// If an entry is selected and the right mouse button was clicked, we pretend as if the user had clicked on
			// the client in the MainWindow. For this to work we map the global mouse position to the local coordinate
			// system of the UserView in the MainWindow. The function will use some internal logic to determine the user
			// to invoke the context menu on but if that fails (which in this case it will), it'll fall back to the
			// currently selected item. This item we have updated to the correct one with the setSelection() call above
			// resulting in the proper context menu being shown at the position of the mouse which in this case is in
			// the TalkingUI.
			QMetaObject::invokeMethod(Global::get().mw, "on_qtvUsers_customContextMenuRequested", Qt::QueuedConnection,
									  Q_ARG(QPoint, Global::get().mw->qtvUsers->mapFromGlobal(event->globalPos())), Q_ARG(bool, false));
		}
	} else {
		// Clear selection
		setSelection(EmptySelection());
	}

	updateUI();
}

void TalkingUI::setVisible(bool visible) {
	if (visible) {
		adjustSize();
	}

	QWidget::setVisible(visible);
}

QSize TalkingUI::sizeHint() const {
	// Prefer to occupy at least 10% of the screen's size
	// This aims to be a good compromise between not being in the way and not
	// being too small to being handled properly.
	int width = QGuiApplication::screens()[0]->availableSize().width() * 0.1;

	return { width, 0 };
}

QSize TalkingUI::minimumSizeHint() const {
	return { 0, 0 };
}

void TalkingUI::on_talkingStateChanged() {
	ClientUser *user = qobject_cast< ClientUser * >(sender());

	if (!user) {
		// If the user that caused this event doesn't exist anymore, it means that it
		// got deleted in the meantime. This in turn means that the user disconnected
		// from the server. In that case it has been removed via on_clientDisconnected
		// already (or shortly will be), so it is safe to silently ignore this case
		// here.
		return;
	}

	if (!user->cChannel) {
		// If the user doesn't have an associated channel, something's either wrong
		// or that user has just disconnected. In either way, we want to make sure
		// that this user won't stick around in the UI.
		hideUser(user->uiSession);
		return;
	}

	TalkingUIUser *userEntry = findOrAddUser(user);

	if (userEntry) {
		userEntry->setTalkingState(user->tsState);
	}

	updateUI();
}

void TalkingUI::on_mainWindowSelectionChanged(const QModelIndex &current, const QModelIndex &previous) {
	Q_UNUSED(previous);

	// Sync the selection in the MainWindow to the TalkingUI
	if (Global::get().mw && Global::get().mw->pmModel) {
		bool clearSelection = true;

		const ClientUser *user = Global::get().mw->pmModel->getUser(current);
		const Channel *channel = Global::get().mw->pmModel->getChannel(current);

		if (Global::get().mw->pmModel->isChannelListener(current)) {
			TalkingUIChannelListener *listenerEntry = findListener(user->uiSession, channel->iId);

			if (listenerEntry) {
				setSelection(ListenerSelection(listenerEntry->getWidget(), user->uiSession, channel->iId));

				clearSelection = false;
			}
		} else {
			if (user) {
				TalkingUIUser *userEntry = findUser(user->uiSession);

				if (userEntry) {
					// Only select the user if there is an actual entry for it in the TalkingUI
					setSelection(UserSelection(userEntry->getWidget(), userEntry->getAssociatedUserSession()));

					clearSelection = false;
				}
			} else if (!user && channel) {
				// if user != nullptr, the selection is actually a user, but UserModel::getChannel still returns
				// the channel of that user. However we only want to select the channel if the user has indeed
				// selected the channel and not just one of the users in it.
				int index = findContainer(channel->iId, ContainerType::CHANNEL);

				if (index >= 0) {
					// Only select the channel if there is present in the TalkingUI
					std::unique_ptr< TalkingUIContainer > &targetContainer = m_containers[index];

					setSelection(
						ChannelSelection(targetContainer->getWidget(), targetContainer->getAssociatedChannelID()));

					clearSelection = false;
				}
			}
		}

		if (clearSelection) {
			setSelection(EmptySelection());
		}
	}
}

void TalkingUI::on_serverSynchronized() {
	if (Global::get().s.bTalkingUI_LocalUserStaysVisible) {
		// According to the settings the local user should always be visible and as we
		// can't count on it to change its talking state right after it has connected to
		// a server, we have to add it manually.
		ClientUser *self = ClientUser::get(Global::get().uiSession);
		findOrAddUser(self);
	}
}

void TalkingUI::on_serverDisconnected() {
	setSelection(EmptySelection());

	// If we disconnect from a server, we have to clear all our users, channels, and so on
	// Since all entries are owned by their respective containers, we only have to delete
	// all containers. These in turn are managed by smart-pointers and therefore it is
	// enough to let those go out of scope.
	m_containers.clear();

	updateUI();
}

void TalkingUI::on_channelChanged(QObject *obj) {
	// According to this function's doc, the passed object must be of type ClientUser
	ClientUser *user = static_cast< ClientUser * >(obj);

	if (!user) {
		return;
	}

	TalkingUIUser *userEntry = findUser(user->uiSession);

	if (userEntry) {
		// The user is visible, so we call moveUserToChannel in order to update
		// the channel this particular user is being displayed in.
		// But first we have to make sure there actually exists and entry for
		// the new channel.
		addChannel(user->cChannel);
		moveUserToChannel(user->uiSession, user->cChannel->iId);
	}
}

void TalkingUI::on_settingsChanged() {
	// The settings might have affected the way we have to display the channel names
	// thus we'll update them just in case
	for (auto &currentContainer : m_containers) {
		// The font size might have changed as well -> update it
		// By the hierarchy in the UI the font-size should propagate to all
		// sub-elements (entries) as well.
		setFontSize(currentContainer->getStylableWidget());

		if (currentContainer->getType() != ContainerType::CHANNEL) {
			continue;
		}

		TalkingUIChannel *channelContainer = static_cast< TalkingUIChannel * >(currentContainer.get());

		const Channel *channel = Channel::get(currentContainer->getAssociatedChannelID());

		if (channel) {
			// Update
			channelContainer->setName(
				createChannelName(channel, Global::get().s.bTalkingUI_AbbreviateChannelNames, Global::get().s.iTalkingUI_PrefixCharCount,
								  Global::get().s.iTalkingUI_PostfixCharCount, Global::get().s.iTalkingUI_MaxChannelNameLength,
								  Global::get().s.iTalkingUI_ChannelHierarchyDepth, Global::get().s.qsTalkingUI_ChannelSeparator,
								  Global::get().s.qsTalkingUI_AbbreviationReplacement, Global::get().s.bTalkingUI_AbbreviateCurrentChannel));
		} else {
			qCritical("TalkingUI: Can't find channel for stored ID");
		}
	}

	// If the font has changed, we have to update the icon size as well
	for (auto &currentContainer : m_containers) {
		for (auto &currentEntry : currentContainer->getEntries()) {
			currentEntry->setIconSize(m_currentLineHeight);

			if (currentEntry->getType() == EntryType::USER) {
				TalkingUIUser *userEntry = static_cast< TalkingUIUser * >(currentEntry.get());

				// The time that a silent user may stick around might have changed as well
				// * 1000 as the setting is in seconds whereas the timer expects milliseconds
				userEntry->setLifeTime(Global::get().s.iTalkingUI_SilentUserLifeTime * 1000);
			}
		}
	}

	const ClientUser *self = ClientUser::get(Global::get().uiSession);

	// Whether or not the current user should always be displayed might also have changed,
	// so we'll have to update that as well.
	TalkingUIUser *localUserEntry = findUser(Global::get().uiSession);
	if (localUserEntry) {
		localUserEntry->restrictLifetime(!Global::get().s.bTalkingUI_LocalUserStaysVisible);
	} else {
		if (self && Global::get().s.bTalkingUI_LocalUserStaysVisible) {
			// Add the local user as it is requested to be displayed
			findOrAddUser(self);
		}
	}


	// Furthermore whether or not to display the local user's listeners might have changed -> clear all
	// listeners from the TalkingUI and add them again if appropriate
	removeAllListeners();
	if (Global::get().s.bTalkingUI_ShowLocalListeners) {
		if (self) {
			const QSet< int > channels = ChannelListener::getListenedChannelsForUser(self->uiSession);

			for (int currentChannelID : channels) {
				const Channel *channel = Channel::get(currentChannelID);

				if (channel) {
					addListener(self, channel);
				}
			}
		}
	}
}

void TalkingUI::on_clientDisconnected(unsigned int userSession) {
	removeUser(userSession);
}

void TalkingUI::on_muteDeafStateChanged() {
	ClientUser *user = qobject_cast< ClientUser * >(sender());

	if (user) {
		// Update icons for local user only
		updateStatusIcons(user);
	}
}

void TalkingUI::on_userLocalVolumeAdjustmentsChanged(float, float) {
	ClientUser *user = qobject_cast< ClientUser * >(sender());

	if (user) {
		TalkingUIUser *userEntry = findUser(user->uiSession);
		if (userEntry) {
			userEntry->setDisplayString(UserModel::createDisplayString(*user, false, nullptr));
		}
	}
}

void TalkingUI::on_channelListenerAdded(const ClientUser *user, const Channel *channel) {
	if (user->uiSession == Global::get().uiSession && Global::get().s.bTalkingUI_ShowLocalListeners) {
		addListener(user, channel);
	}
}

void TalkingUI::on_channelListenerRemoved(const ClientUser *user, const Channel *channel) {
	removeListener(user->uiSession, channel->iId);
}

void TalkingUI::on_channelListenerLocalVolumeAdjustmentChanged(int channelID, float, float) {
	TalkingUIChannelListener *listenerEntry = findListener(Global::get().uiSession, channelID);

	const Channel *channel = Channel::get(channelID);
	const ClientUser *self = ClientUser::get(Global::get().uiSession);

	if (listenerEntry && channel && self) {
		listenerEntry->setDisplayString(UserModel::createDisplayString(*self, true, channel));
	}
}