Debian Codegraph @

src/tests/itemtests/itemtests.cpp

raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 #include "itemtests.h"
4
5 #include <QAbstractItemView>
6 #include <QCheckBox>
7 #include <QDrag>
8 #include <QItemSelectionModel>
9 #include <QLoggingCategory>
10 #include <QRegularExpression>
11 #include <QTest>
12 #include <QTimer>
13
14 namespace {
15
16 Q_DECLARE_LOGGING_CATEGORY(plugin)
17 Q_LOGGING_CATEGORY(plugin, "copyq.keys")
18
19 /// Selected items texts for item views: {item1}{item2}...
20 QString selectedItemsTexts(QWidget *widget)
21 {
22 const auto view = qobject_cast<QAbstractItemView*>(widget);
23 if (!view)
24 return {};
25
26 const auto sel = view->selectionModel();
27 if (!sel)
28 return {};
29
30 QString items;
31 for (const QModelIndex &ind : sel->selectedIndexes()) {
32 const QString text = ind.data().toString().replace("\n", "\\n");
33 items.append(QStringLiteral("{%1}").arg(text));
34 }
35 return items;
36 }
37
38 /// A text visible in the widget
39 QString widgetText(QWidget *widget)
40 {
41 QString text = widget->property("text").toString()
42 .remove('&')
43 // Remove HTML tags
44 .remove(QRegularExpression(QStringLiteral("</?[^>]*>")));
45
46 if ( text.isEmpty() && widget->isWindow() )
47 text = widget->windowTitle();
48
49 return text.isEmpty() ? QString() : QStringLiteral("'%1'").arg(text);
50 }
51
52 /// Widget's full address string.
53 /// Examples:
54 /// :QPushButton'OK'<qt_msgbox_buttonbox:QDialogButtonBox<:QMessageBox'Change Password'<MainWindow
55 /// tableView:QTableView{selected_item_text1}{selected_item_text2}<ActionHandlerDialog:QDialog'Process Manager'<MainWindow
56 QString widgetAddress(QWidget *widget)
57 {
58 if (!widget)
59 return QStringLiteral("<null>");
60
61 QString result;
62 QWidget *current = widget;
63 while (current) {
64 const QString className = current->metaObject()->className();
65 const QString objectName = current->objectName();
66 const QString name = className == objectName
67 ? className : QStringLiteral("%1:%2").arg(objectName, className);
68 // Skip some default widgets.
69 if ( name != QLatin1String(":QWidget")
70 && !name.startsWith(QLatin1String("qt_scrollarea_viewport:QWidget")) )
71 {
72 if (!result.isEmpty())
73 result.append('<');
74 result.append(name);
75 result.append(widgetText(current));
76 result.append(selectedItemsTexts(current));
77 }
78 current = current->parentWidget();
79 }
80 return result;
81 }
82
83 bool matchesProperties(QObject *object, const QStringList &properties)
84 {
85 for (auto it = properties.cbegin(); it != properties.cend(); ++it) {
86 const QString key = it->section('=', 0, 0);
87 const QString value = it->section('=', 1, 1);
88 if ( value.isEmpty() ) {
89 if ( object->objectName() != key && object->metaObject()->className() != key )
90 return false;
91 }
92
93 const QVariant propValue = object->property(key.toUtf8());
94 if ( propValue.toString() != value )
95 return false;
96 }
97
98 return true;
99 }
100
101 QWidget *findWidgetWithProperties(const QString &properties, QWidget *parent)
102 {
103 QStringList names = properties.split('<');
104 return std::accumulate(
105 names.cbegin(), names.cend(), parent,
106 [](QWidget *parent, const QString &name) -> QWidget* {
107 if (parent == nullptr)
108 return nullptr;
109
110 const QStringList props = name.split('|', Qt::SkipEmptyParts);
111 for (QWidget *child : parent->findChildren<QWidget*>()) {
112 if (child->isVisible() && matchesProperties(child, props)) {
113 qCDebug(plugin) << "Found target:" << widgetAddress(child);
114 return child;
115 }
116 }
117 qCCritical(plugin) << "Failed to find mouse action target:" << name;
118 return nullptr;
119 });
120 }
121
122 bool checkEventTarget(
123 QWidget *target, const QString &keys, const QString &widgetName, const char *event)
124 {
125 if (target && target->isVisible())
126 return true;
127
128 qCCritical(plugin) << "Failed to send postponed" << event
129 << keys << "to" << widgetName << ";"
130 << (target ? "Target widget is no longer visible" : "Target widget no longer exists");
131 return false;
132 }
133
134 } // namespace
135
136 class KeyClicker final : public QObject {
137 public:
138 enum Status {
139 Pending,
140 Success,
141 Failed
142 };
143
144 KeyClicker(QObject *parent)
145 : QObject(parent)
146 {
147 for (const auto w : qApp->topLevelWidgets()) {
148 if (w->objectName() == QLatin1String("MainWindow")) {
149 m_wnd = w;
150 break;
151 }
152 }
153 if (m_wnd == nullptr)
154 qCCritical(plugin) << "Failed to find MainWindow";
155 }
156
157 void keyClicksRetry(const QRegularExpression &expectedWidgetName, const QString &keys, int delay, int retry)
158 {
159 if (retry > 0)
160 sendKeyClicks(expectedWidgetName, keys, delay + 100, retry - 1);
161 else
162 keyClicksFailed();
163 }
164
165 void keyClicksFailed()
166 {
167 qCCritical(plugin) << "Failed to send key press to target widget";
168
169 const auto actual = keyClicksTarget();
170 const auto popup = QApplication::activePopupWidget();
171 const auto widget = QApplication::focusWidget();
172 const auto window = QApplication::activeWindow();
173 const auto modal = QApplication::activeModalWidget();
174 const auto state = qApp->applicationState();
175
176 if (state == Qt::ApplicationActive)
177 qCCritical(plugin) << "App is INACTIVE! State:" << state;
178
179 qCCritical(plugin).noquote().nospace()
180 << "Expected: /" + m_expectedWidgetName.pattern() + "/"
181 << "\nActual: " + widgetAddress(actual)
182 << "\nPopup: " + widgetAddress(popup)
183 << "\nWidget: " + widgetAddress(widget)
184 << "\nWindow: " + widgetAddress(window)
185 << "\nModal: " + widgetAddress(modal);
186
187 m_status = Failed;
188 }
189
190 void keyClicks(const QString &keys, int delay, int retry)
191 {
192 auto widget = keyClicksTarget();
193 if (!widget) {
194 keyClicksRetry(m_expectedWidgetName, keys, delay, retry);
195 return;
196 }
197
198 #if defined(Q_OS_MAC)
199 // WORKAROUND for focusing back to the main window on macOS.
200 if (qApp->applicationState() != Qt::ApplicationActive && m_wnd->isVisible()) {
201 qCDebug(plugin) << "Re-activating the main window (macOS)";
202 m_wnd->activateWindow();
203 m_wnd->raise();
204 }
205 #endif
206
207 if (qApp->applicationState() != Qt::ApplicationActive) {
208 qCDebug(plugin) << "Waiting for application to become active";
209 keyClicksRetry(m_expectedWidgetName, keys, delay, retry);
210 return;
211 }
212
213 const QString widgetName = widgetAddress(widget);
214 if ( !m_expectedWidgetName.pattern().isEmpty()
215 && !m_expectedWidgetName.match(widgetName).hasMatch() )
216 {
217 keyClicksRetry(m_expectedWidgetName, keys, delay, retry);
218 return;
219 }
220
221 // Only verified focused widget.
222 if ( keys.isEmpty() ) {
223 m_status = Success;
224 return;
225 }
226
227 // There could be some animation/transition effect on check boxes
228 // so wait for checkbox to be set.
229 if ( qobject_cast<QCheckBox*>(widget) )
230 QTest::qWait(100);
231
232 qCDebug(plugin) << "Sending" << keys << "to" << widgetName;
233
234 static const auto keyClicksPrefix = QLatin1String(":");
235 static const auto mousePrefix = QLatin1String("mouse|");
236 static const auto dragPrefix = QLatin1String("isDraggingFrom|");
237 if ( keys.startsWith(keyClicksPrefix) ) {
238 const auto text = keys.mid(keyClicksPrefix.size());
239 QTest::keyClicks(widget, text, Qt::NoModifier);
240 } else if ( keys.startsWith(mousePrefix) ) {
241 const QString action = keys.section('|', 1, 1);
242 const QString properties = keys.section('|', 2);
243 static const auto mousePress = QStringLiteral("PRESS");
244 static const auto mouseRelease = QStringLiteral("RELEASE");
245 static const auto mouseClick = QStringLiteral("CLICK");
246 static const auto mouseDrag = QStringLiteral("DRAG");
247 static const QStringList validActions = {
248 mousePress, mouseRelease, mouseClick, mouseDrag};
249 if ( !validActions.contains(action) ) {
250 qCCritical(plugin) << "Failed to match mouse action:" << keys;
251 qCCritical(plugin) << "Valid mouse actions are:" << validActions;
252 m_status = Failed;
253 return;
254 }
255 QPointer<QWidget> source = findWidgetWithProperties(properties, m_wnd);
256 if (!source) {
257 m_status = Failed;
258 return;
259 }
260 // Don't block while processing the events.
261 runAfterInterval(delay, [=](){
262 if (!checkEventTarget(source, keys, widgetName, "mouse"))
263 return;
264
265 // Send the event to window instead - it works better.
266 QWidget *windowWidget = source->window();
267 if (!windowWidget || !source->window()->windowHandle()) {
268 qCCritical(plugin) << "Target widget has no window handle";
269 return;
270 }
271 QWindow *window = windowWidget->windowHandle();
272 const QPoint pos = source->mapTo(windowWidget, source->rect().center());
273
274 if (action == mousePress) {
275 QTest::mousePress(window, Qt::LeftButton, {}, pos);
276 } else if (action == mouseRelease) {
277 QTest::mouseRelease(window, Qt::LeftButton, {}, pos);
278 } else if (action == mouseClick) {
279 QTest::mouseClick(window, Qt::LeftButton, {}, pos);
280 } else if (action == mouseDrag) {
281 // This should trigger creating a QDrag in a parent widget.
282 QTest::mouseMove(source, source->rect().topLeft());
283 QTest::mouseMove(source, source->rect().bottomRight());
284 }
285 });
286 } else if ( keys.startsWith(dragPrefix) ) {
287 const QObject *drag = m_wnd->findChild<QDrag*>();
288 if (!drag) {
289 qCCritical(plugin) << "QDrag not started";
290 m_status = Failed;
291 return;
292 }
293 qCDebug(plugin) << "QDrag started with parent:" << widgetAddress(qobject_cast<QWidget*>(drag->parent()));
294 const QString properties = keys.section('|', 1);
295 QWidget* source = findWidgetWithProperties(properties, m_wnd);
296 if (!source) {
297 m_status = Failed;
298 return;
299 }
300 if (drag->parent() != source) {
301 qCCritical(plugin) << "Unexpected QDrag parent; Expected:" << properties
302 << "; Actual:" << widgetAddress(qobject_cast<QWidget*>(drag->parent()));
303 m_status = Failed;
304 return;
305 }
306 } else {
307 const QKeySequence shortcut(keys, QKeySequence::PortableText);
308 if ( shortcut.isEmpty() ) {
309 qCCritical(plugin) << "Failed to parse shortcut" << keys;
310 m_status = Failed;
311 return;
312 }
313
314 const auto key = static_cast<uint>(shortcut[0].toCombined());
315 const QPointer<QWidget> target = widget;
316 // Avoid blocking on modal dialogs
317 runAfterInterval(0, [=](){
318 if (!target || !target->isVisible()) {
319 qCCritical(plugin) << "Target no longer valid:" << widgetName;
320 return;
321 }
322 QTest::keyClick(
323 target,
324 Qt::Key(key & ~Qt::KeyboardModifierMask),
325 Qt::KeyboardModifiers(key & Qt::KeyboardModifierMask));
326 });
327 }
328
329 m_status = Success;
330 qCDebug(plugin) << "Sent" << keys << "to" << widgetName;
331 }
332
333 void sendKeyClicks(const QRegularExpression &expectedWidgetName, const QString &keys, int delay, int retry)
334 {
335 m_status = Pending;
336 m_expectedWidgetName = expectedWidgetName;
337
338 // Don't stop when modal window is open.
339 runAfterInterval(delay, [=](){ keyClicks(keys, delay, retry); });
340 }
341
342 int status(bool forceRetrieve) {
343 if (m_status == Pending && forceRetrieve) {
344 keyClicksFailed();
345 return Failed;
346 }
347 return m_status;
348 }
349
350 private:
351 template <typename Callable>
352 void runAfterInterval(int delay, Callable func)
353 {
354 auto t = new QTimer(m_wnd);
355 t->setSingleShot(true);
356 QObject::connect(t, &QTimer::timeout, m_wnd, func);
357 QObject::connect(t, &QTimer::timeout, t, &QTimer::deleteLater);
358 t->start(delay);
359 }
360
361 QWidget *keyClicksTarget()
362 {
363 auto popup = QApplication::activePopupWidget();
364 if (popup)
365 return popup;
366
367 auto widget = QApplication::focusWidget();
368 if (widget)
369 return widget;
370
371 auto window = QApplication::activeWindow();
372 if (window)
373 return window->focusWidget();
374
375 auto modal = QApplication::activeModalWidget();
376 if (modal)
377 return modal->focusWidget();
378
379 #ifdef Q_OS_MAC
380 return m_wnd->focusWidget();
381 #else
382 return nullptr;
383 #endif
384 }
385
386 QWidget *m_wnd = nullptr;
387 Status m_status = Success;
388 QRegularExpression m_expectedWidgetName;
389 };
390
391 void ItemTestsScriptable::keys()
392 {
393 bool ok;
394
395 // Wait interval after shortcut pressed or text typed.
396 const auto waitValue = qgetenv("COPYQ_TESTS_KEYS_WAIT");
397 int wait = waitValue.toInt(&ok);
398 if (!ok)
399 wait = 0;
400
401 // Delay while typing.
402 const auto delayValue = qgetenv("COPYQ_TESTS_KEY_DELAY");
403 int delay = delayValue.toInt(&ok);
404 if (!ok)
405 delay = 0;
406
407 QString expectedWidgetName;
408
409 const auto focusPrefix = QLatin1String("focus:");
410 bool interrupted = false;
411 for (const auto &arg : currentArguments()) {
412 if (interrupted) {
413 const auto message =
414 "Client was interrupted."
415 " This is allowed to happen only when processing the last key event.";
416 qCCritical(plugin) << message;
417 throwError(message);
418 return;
419 }
420
421 const QString keys = arg.toString();
422
423 if (keys.startsWith(focusPrefix)) {
424 expectedWidgetName = keys.mid(focusPrefix.size());
425 call("callPlugin", {"itemtests", "sendKeys", expectedWidgetName, QString(), 0});
426 } else {
427 call("sleep", {wait});
428 call("callPlugin", {"itemtests", "sendKeys", expectedWidgetName, keys, delay});
429 QTest::qWait(qMax(5, delay));
430 }
431
432 // Make sure all keys are send (shortcuts are postponed because they can be blocked by modal windows).
433 for (int i = 1; ; ++i) {
434 const QVariant result = call("callPlugin", {"itemtests", "sendKeysStatus", i > 15});
435 bool ok = false;
436 const int status = result.toInt(&ok);
437 if (!ok) {
438 qCDebug(plugin) << "Client interrupted, got status:" << result;
439 interrupted = true;
440 break;
441 }
442
443 if (status == KeyClicker::Success)
444 break;
445
446 if (status == KeyClicker::Failed) {
447 throwError("Failed to send key presses");
448 return;
449 }
450
451 const int waitMs = 8 * i * i;
452 QTest::qWait(qMin(1000, waitMs));
453 }
454 }
455 }
456
457 ItemScriptable *ItemTestsLoader::scriptableObject()
458 {
459 return new ItemTestsScriptable();
460 }
461
462 QVariant ItemTestsLoader::scriptCallback(const QVariantList &arguments)
463 {
464 const auto cmd = arguments[0].toString();
465
466 if (cmd == "sendKeys") {
467 const QString expectedWidgetName = arguments.value(1).toString();
468 const QString keys = arguments.value(2).toString();
469 const int delay = arguments.value(3).toInt();
470 const QRegularExpression re = QRegularExpression(
471 QString(expectedWidgetName)
472 .replace(QLatin1String("<"), QLatin1String(".*<.*"))
473 );
474 keyClicker()->sendKeyClicks(re, keys, delay, 10);
475 return {};
476 }
477
478 if (cmd == "sendKeysStatus")
479 return keyClicker()->status(arguments.value(1).toBool());
480
481 return QStringLiteral("Unexpected command: %1").arg(cmd);
482 }
483
484 KeyClicker *ItemTestsLoader::keyClicker()
485 {
486 if (!m_keyClicker)
487 m_keyClicker = new KeyClicker(this);
488 return m_keyClicker;
489 }