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

SearchDialog.cpp « mumble « src - github.com/mumble-voip/mumble.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: dfc228b2cc6da4fe7c27cdd747ccb13fa7b45799 (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
// Copyright 2021-2022 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 "SearchDialog.h"
#include "Channel.h"
#include "ClientUser.h"
#include "MainWindow.h"
#include "SearchDialogItemDelegate.h"
#include "ServerHandler.h"
#include "UserModel.h"
#include "Global.h"

#include <QContextMenuEvent>
#include <QFontMetrics>
#include <QHash>
#include <QHideEvent>
#include <QIcon>
#include <QKeyEvent>
#include <QReadLocker>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QShowEvent>
#include <QTreeWidgetItem>

#include <stack>

namespace Search {

QString SearchDialog::toString(UserAction action) {
	switch (action) {
		case UserAction::NONE:
			return SearchDialog::tr("None");
		case UserAction::JOIN:
			return SearchDialog::tr("Join");
	}

	throw "Function incomplete or invalid enum value passed";
}

QString SearchDialog::toString(ChannelAction action) {
	switch (action) {
		case ChannelAction::NONE:
			return SearchDialog::tr("None");
		case ChannelAction::JOIN:
			return SearchDialog::tr("Join");
	}

	throw "Function incomplete or invalid enum value passed";
}

class SearchResultItem : public QTreeWidgetItem {
	Q_DISABLE_COPY(SearchResultItem);

public:
	template< typename parent_t >
	SearchResultItem(const SearchResult &result, unsigned int id, parent_t parent,
					 QTreeWidgetItem *precedingItem = nullptr)
		: QTreeWidgetItem(parent, precedingItem), m_result(result), m_id(id) {
		constexpr int TYPE_COLUMN  = 0;
		constexpr int MATCH_COLUMN = 1;

		if (m_result.type == SearchType::User) {
			QIcon userIcon = QIcon(QLatin1String("skin:talking_off.svg"));
			setIcon(TYPE_COLUMN, userIcon);
		}

		setChildIndicatorPolicy(QTreeWidgetItem::DontShowIndicator);

		QString matchText =
			m_result.fullText.replace(m_result.begin, m_result.length,
									  "<b>" + m_result.fullText.midRef(m_result.begin, m_result.length) + "</b>");

		setData(MATCH_COLUMN, Qt::DisplayRole, std::move(matchText));
		setData(MATCH_COLUMN, SearchDialogItemDelegate::CHANNEL_TREE_ROLE, m_result.channelHierarchy);

		setTextAlignment(MATCH_COLUMN, Qt::AlignLeft | Qt::AlignVCenter);
	}

	unsigned int getID() const { return m_id; }

	const SearchResult &getResult() const { return m_result; }

private:
	SearchResult m_result;
	unsigned int m_id;
};

class ChannelItem : public QTreeWidgetItem {
	Q_DISABLE_COPY(ChannelItem);

public:
	template< typename parent_t >
	ChannelItem(const Channel *chan, parent_t parent = nullptr, QTreeWidgetItem *precedingItem = nullptr)
		: QTreeWidgetItem(parent, precedingItem), m_chanID(chan->iId) {
		constexpr int NAME_COLUMN = 0;

		setText(NAME_COLUMN, chan->qsName);

		setTextAlignment(NAME_COLUMN, Qt::AlignLeft | Qt::AlignVCenter);
	}

	int getChannelID() const { return m_chanID; }

private:
	int m_chanID;
};

SearchDialog::SearchDialog(QWidget *parent) : QWidget(parent), m_itemDelegate(new SearchDialogItemDelegate()) {
	setupUi(this);

	// Make the search dialog be always on top and is shown as a Window
	setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint | Qt::Window);

	// Set the correct icon for the options button
	toggleOptions->setIcon(QIcon("skin:config_basic.png"));

	// We can only init this after the UI has been set up
	m_searchFieldStyleWrapper = MultiStyleWidgetWrapper(searchField);

	// Init options
	userOption->setChecked(Global::get().s.searchForUsers);
	channelOption->setChecked(Global::get().s.searchForChannels);
	caseSensitiveOption->setChecked(Global::get().s.searchCaseSensitive);
	regexOption->setChecked(Global::get().s.searchAsRegex);

	searchOptionBox->setVisible(Global::get().s.searchOptionsShown);

	// This makes sure that our contextMenuEvent function gets called for creating the context menu
	searchResultTree->setContextMenuPolicy(Qt::DefaultContextMenu);

	// We have to use a custom ItemDelegate in order to be able to display rich text
	searchResultTree->setItemDelegate(m_itemDelegate.get());

	searchResultTree->setItemsExpandable(false);
	// Remove icons for expanding items
	searchResultTree->setRootIsDecorated(false);
	searchResultTree->header()->setMinimumSectionSize(0);
	searchResultTree->header()->hide();

	QFontMetrics metric(searchResultTree->font());
	searchResultTree->header()->resizeSection(0, metric.height() * 1.2);
	searchResultTree->setIconSize(QSize(metric.ascent(), metric.ascent()));

	if (Global::get().mw) {
		QObject::connect(Global::get().mw, &MainWindow::serverSynchronized, this,
						 &SearchDialog::on_serverConnectionSynchronized);

		// Add the action to toggle the search dialog to this dialof as well in order to make sure that
		// toggling it off again also works when the search dialog has focus.
		addAction(Global::get().mw->qaSearch);
	}
	if (Global::get().sh) {
		QObject::connect(Global::get().sh.get(), &ServerHandler::disconnected, this,
						 &SearchDialog::on_serverDisconnected);
	}
}

void SearchDialog::on_toggleOptions_clicked() {
	// Toggle the search option's visibility
	Global::get().s.searchOptionsShown = !searchOptionBox->isVisible();

	searchOptionBox->setVisible(Global::get().s.searchOptionsShown);
}

void SearchDialog::on_searchField_returnPressed() {
	// Then focus the search results (but only if there are actually
	// search results available)
	if (searchResultTree->topLevelItemCount() > 0) {
		searchResultTree->setFocus();

		if (!searchResultTree->currentItem()) {
			// Select the first result
			searchResultTree->setCurrentItem(searchResultTree->topLevelItem(0));
		}

		SearchResultItem *selectedItem = static_cast< SearchResultItem * >(searchResultTree->currentItem());

		if (selectedItem) {
			performDefaultAction(*selectedItem);
		}
	}
}

void SearchDialog::on_searchField_textChanged(const QString &text) {
	// Reset the search field's background color (might have been changed to indicate an error)
	m_searchFieldStyleWrapper.clearBackgroundColor();

	search(text);
}

void SearchDialog::on_userOption_clicked(bool checked) {
	Global::get().s.searchForUsers = checked;

	searchAgain();
}

void SearchDialog::on_channelOption_clicked(bool checked) {
	Global::get().s.searchForChannels = checked;

	searchAgain();
}

void SearchDialog::on_caseSensitiveOption_clicked(bool checked) {
	Global::get().s.searchCaseSensitive = checked;

	searchAgain();
}

void SearchDialog::on_regexOption_clicked(bool checked) {
	Global::get().s.searchAsRegex = checked;

	searchAgain();
}

void SearchDialog::on_searchResultTree_currentItemChanged(QTreeWidgetItem *c, QTreeWidgetItem *) {
	if (!c || Global::get().uiSession == 0) {
		return;
	}

	SearchResultItem &item = static_cast< SearchResultItem & >(*c);
	if (item.getResult().type == SearchType::User) {
		const ClientUser *user = ClientUser::get(item.getID());

		if (user) {
			// Only try to select the user if (s)he still exists
			Global::get().mw->pmModel->setSelectedUser(user->uiSession);
		}
	} else {
		const Channel *channel = Channel::get(static_cast< int >(item.getID()));

		if (channel) {
			// Only try to select the channel if it still exists
			Global::get().mw->pmModel->setSelectedChannel(channel->iId);
		}
	}
}

void SearchDialog::on_searchResultTree_itemActivated(QTreeWidgetItem *item, int) {
	if (item) {
		const SearchResultItem &activatedItem = static_cast< SearchResultItem & >(*item);

		performDefaultAction(activatedItem);
	}
}

void SearchDialog::searchAgain() {
	search(searchField->text());
}

void SearchDialog::clearSearchResults() {
	searchResultTree->clear();
}

SearchResult regularSearch(const QString &source, const QString &searchTerm, SearchType type, bool caseSensitive) {
	constexpr int FROM = 0;
	int startIndex     = source.indexOf(searchTerm, FROM, caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive);

	if (startIndex >= 0) {
		int length = searchTerm.size();

		return { startIndex, length, type, source, "" };
	} else {
		// Not found
		return {};
	}
}

SearchResult regexSearch(const QString &source, const QRegularExpression &regex, SearchType type) {
	QRegularExpressionMatch match = regex.match(source);

	if (match.hasMatch()) {
		// Found
		int startIndex = match.capturedStart();
		int length     = match.capturedEnd() - startIndex;

		return { startIndex, length, type, source, "" };
	} else {
		// Not found
		return {};
	}
}

QString getChannelHierarchy(const Channel &channel, bool includeSource) {
	std::stack< const Channel * > channels;

	if (includeSource) {
		channels.push(&channel);
	}

	const Channel *currentChannel = &channel;
	;
	while ((currentChannel = currentChannel->cParent)) {
		channels.push(currentChannel);
	}

	const QString separator = Global::get().s.qsHierarchyChannelSeparator;

	QString hierarchy;
	while (!channels.empty()) {
		hierarchy += channels.top()->qsName;
		channels.pop();

		if (!channels.empty()) {
			hierarchy += separator;
		}
	}

	return hierarchy;
}

void SearchDialog::search(const QString &searchTerm) {
	if (searchTerm.size() == 0 || Global::get().uiSession == 0) {
		// The search bar is either empty or there is no (fully synchronized) server connection
		clearSearchResults();

		return;
	}

	// Copy the values from the settings to ensure that the following code is not affected by
	// settings changing mid-execution.
	const bool searchUsers    = Global::get().s.searchForUsers;
	const bool searchChannels = Global::get().s.searchForChannels;
	const bool caseSensitive  = Global::get().s.searchCaseSensitive;
	const bool useRegEx       = Global::get().s.searchAsRegex;

	// Build and validate the RegEx if required
	QRegularExpression regex;
	if (useRegEx) {
		regex.setPattern(searchTerm);

		QRegularExpression::PatternOptions options = QRegularExpression::UseUnicodePropertiesOption;
		if (!caseSensitive) {
			options |= QRegularExpression::CaseInsensitiveOption;
		}
		regex.setPatternOptions(options);

		// Check that the provided RegEx is actually valid and usable
		if (!regex.isValid()) {
			// Indicate that there is an error by changing the search field's background color
			m_searchFieldStyleWrapper.setBackgroundColor("#fc5555");

			clearSearchResults();

			return;
		}
	}

	SearchResultMap matches;

	// Start by searching for users
	if (searchUsers) {
		QReadLocker userLock(&ClientUser::c_qrwlUsers);

		QHash< unsigned int, ClientUser * >::const_iterator it = ClientUser::c_qmUsers.constBegin();
		while (it != ClientUser::c_qmUsers.constEnd()) {
			const ClientUser *currentUser = it.value();

			SearchResult result;
			if (useRegEx) {
				result = regexSearch(currentUser->qsName, regex, SearchType::User);
			} else {
				result = regularSearch(currentUser->qsName, searchTerm, SearchType::User, caseSensitive);
			}

			if (result) {
				result.channelHierarchy = getChannelHierarchy(*currentUser->cChannel, true);
				matches.insert({ result, currentUser->uiSession });
			}

			it++;
		}
	}

	// Continue doing the same for channels
	if (searchChannels) {
		QReadLocker userLock(&Channel::c_qrwlChannels);

		QHash< int, Channel * >::const_iterator it = Channel::c_qhChannels.constBegin();
		while (it != Channel::c_qhChannels.constEnd()) {
			const Channel *currentChannel = it.value();

			SearchResult result;
			if (useRegEx) {
				result = regexSearch(currentChannel->qsName, regex, SearchType::Channel);
			} else {
				result = regularSearch(currentChannel->qsName, searchTerm, SearchType::Channel, caseSensitive);
			}

			if (result) {
				result.channelHierarchy = getChannelHierarchy(*currentChannel, false);
				// As the channel ID is never negative, we can safely cast it to an unsigned int
				matches.insert({ result, static_cast< unsigned int >(currentChannel->iId) });
			}

			it++;
		}
	}

	setSearchResults(matches);
}

void SearchDialog::on_serverConnectionSynchronized() {
	searchAgain();

	if (Global::get().sh) {
		// Connect signal for clearing all search results on disconnect
		QObject::connect(Global::get().sh.get(), &ServerHandler::disconnected, this,
						 &SearchDialog::on_serverDisconnected);
	}
}

void SearchDialog::on_serverDisconnected() {
	clearSearchResults();
}

void SearchDialog::on_clientDisconnected(unsigned int userSession) {
	removeSearchResult(userSession, true);
}

void SearchDialog::on_channelRemoved(int channelID) {
	removeSearchResult(channelID, false);
}

void SearchDialog::setSearchResults(const SearchResultMap &results) {
	// First clear all existing results
	clearSearchResults();

	if (results.size() > 0) {
		SearchResultMap::const_iterator it = results.cbegin();

		SearchResultItem *previousItem = nullptr;
		while (it != results.cend()) {
			// Move the SearchResult out of the map
			const SearchResult currentResult = std::move(it->first);
			const unsigned int currentID     = it->second;

			// Constructing this instance is enough to set everything up and adding it to the tree
			// We have to add a pointer to the previous item so that this item is actually appended after
			// the preceding one and thus the order of the map is preserved. Without this, the order would
			// be reversed.
			previousItem = new SearchResultItem(currentResult, currentID, searchResultTree, previousItem);

			it++;
		}
	}
}

void SearchDialog::hideEvent(QHideEvent *event) {
	QWidget::hideEvent(event);

	if (!event->spontaneous()) {
		// Clear results and search string
		clearSearchResults();
		searchField->clear();
	}
}

void SearchDialog::showEvent(QShowEvent *event) {
	QWidget::showEvent(event);

	// We have to activate the window to make sure that it currently has focus and (more importantly)
	// is able to receive keyboard events. Without this function the window will appear but keyboard
	// events will still be sent to whatever window had focus at the time this was made visible (at
	// least of that previously focused window was not Mumble).
	//
	// Note however that this DOES NOT WORK on Windows!
	// Citing from https://doc.qt.io/qt-5/qwidget.html#activateWindow:
	// "On Windows, if you are calling this when the application is not currently the active one then it will not make
	// it the active window. It will change the color of the taskbar entry to indicate that the window has changed in
	// some way. This is because Microsoft does not allow an application to interrupt what the user is currently doing
	// in another application."
	activateWindow();

	// Focus the search box so that the user can directly start typing
	searchField->setFocus();
}

void SearchDialog::keyPressEvent(QKeyEvent *event) {
	auto it = m_relayedKeyEvents.find(event);
	if (it != m_relayedKeyEvents.cend()) {
		// This is an KeyEvent that we relayed, but that did not get accepted by the TreeWidget and thus it is
		// proagating back to us. Thus we will accept it here in order to keep it from propagating further up
		// but we don't act on it since this here is not the originally intended target anyways.
		event->accept();

		m_relayedKeyEvents.erase(it);
		return;
	}

	if (event->matches(QKeySequence::Cancel)) {
		event->accept();
		// Mimic behavior of dialogs (close on Esc)
		close();
	}

	if (event->key() == Qt::Key_Up || event->key() == Qt::Key_Down || event->key() == Qt::Key_PageUp
		|| event->key() == Qt::Key_PageDown) {
		QKeyEvent *copy = new QKeyEvent(event->type(), event->key(), event->modifiers(), event->nativeScanCode(),
										event->nativeVirtualKey(), event->nativeScanCode(), event->text(),
										event->isAutoRepeat(), event->count());

		m_relayedKeyEvents.insert(copy);

		qApp->postEvent(searchResultTree, copy);
	}
}

void SearchDialog::contextMenuEvent(QContextMenuEvent *event) {
	if (Global::get().mw && searchResultTree->currentIndex().isValid() && Global::get().uiSession > 0) {
		// 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.
		// As we synchronize the selection from the search dialog to the MainWindow, this will already be what we want
		// it to be.
		QMetaObject::invokeMethod(Global::get().mw, "on_qtvUsers_customContextMenuRequested", Qt::QueuedConnection,
								  Q_ARG(QPoint, Global::get().mw->qtvUsers->mapFromGlobal(event->globalPos())),
								  Q_ARG(bool, false));

		event->accept();
	}
}

void SearchDialog::performDefaultAction(const SearchResultItem &item) {
	MainWindow *mainWindow = Global::get().mw;
	if (!mainWindow) {
		return;
	}

	if (item.getResult().type == SearchType::User) {
		ClientUser *selectedUser = mainWindow->pmModel->getSelectedUser();

		if (selectedUser) {
			mainWindow->cuContextUser = selectedUser;

			switch (Global::get().s.searchUserAction) {
				case UserAction::NONE:
					break;
				case UserAction::JOIN:
					mainWindow->on_qaUserJoin_triggered();
					break;
			}

			// Reset to avoid side-effects
			mainWindow->cuContextUser = nullptr;
		}
	} else {
		Channel *selectedChannel = mainWindow->pmModel->getSelectedChannel();

		if (selectedChannel) {
			mainWindow->cContextChannel = selectedChannel;

			switch (Global::get().s.searchChannelAction) {
				case ChannelAction::NONE:
					break;
				case ChannelAction::JOIN:
					mainWindow->on_qaChannelJoin_triggered();
					break;
			}

			// Reset to avoid side-effects
			mainWindow->cContextChannel = nullptr;
		}
	}

	// Close dialog after the default action
	close();
}

bool SearchDialog::removeSearchResult(unsigned int id, bool isUser) {
	for (int i = 0; i < searchResultTree->topLevelItemCount(); i++) {
		SearchResultItem *item = static_cast< SearchResultItem * >(searchResultTree->topLevelItem(i));

		if (item) {
			bool typeMatches = (isUser && item->getResult().type == SearchType::User)
							   || (!isUser && item->getResult().type == SearchType::Channel);

			if (typeMatches && item->getID() == id) {
				// Remove this item
				QTreeWidgetItem *removedItem = searchResultTree->takeTopLevelItem(i);

				delete removedItem;

				return true;
			}
		}
	}

	return false;
}

}; // namespace Search