Debian Codegraph @

src/tests/tests_other.cpp

raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 #include "test_utils.h"
4 #include "tests.h"
5 #include "tests_common.h"
6
7 #include "common/commandstatus.h"
8 #include "common/mimetypes.h"
9 #include "common/sleeptimer.h"
10 #include "common/version.h"
11
12 #include <QProcess>
13
14 #include <algorithm>
15
16 namespace {
17
18 QString copyqUserAgent()
19 {
20 return QStringLiteral("CopyQ/%1").arg(versionString);
21 }
22
23 bool waitWhileFileExists(const QFile &file)
24 {
25 SleepTimer t(2000);
26 while (file.exists() && t.sleep()) {}
27 return !file.exists();
28 }
29
30 QVariantMap secretData(const QByteArray &text)
31 {
32 #ifdef Q_OS_WIN
33 const QString format("application/x-qt-windows-mime;value=\"Clipboard Viewer Ignore\"");
34 const QByteArray value("");
35 #elif defined(Q_OS_MACOS)
36 const QString format("application/x-nspasteboard-concealed-type");
37 const QByteArray value("secret");
38 #elif defined(Q_OS_UNIX)
39 const QString format("x-kde-passwordManagerHint");
40 const QByteArray value("secret");
41 #endif
42
43 return QVariantMap{
44 {format, value},
45 {mimeText, text},
46 };
47 }
48
49 } // namespace
50
51
52 void CoreTests::pipingCommands()
53 {
54 const auto tab = testTab(1);
55 const Args args = Args("tab") << tab << "separator" << ",";
56
57 RUN(args << "action"
58 << "copyq print HELLO | copyq print(str(input()).toLowerCase())", "");
59 WAIT_ON_OUTPUT(args << "read" << "0" << "1", "hello,");
60
61 RUN(args << "action"
62 << "copyq print TEST"
63 " | copyq 'print(str(input()) + 1)'"
64 " | copyq 'print(str(input()) + 2)'"
65 " | copyq 'print(str(input()) + 3)'"
66 , "");
67 WAIT_ON_OUTPUT(args << "read" << "0" << "1", "TEST123,hello");
68 }
69
70 void CoreTests::copyPasteCommands()
71 {
72 const QByteArray commands =
73 "[Commands]\n"
74 "1\\Name=Test 1\n"
75 "2\\Name=Test 2\n"
76 "size=2";
77
78 KEYS(clipboardBrowserId << "F6");
79 TEST( m_test->setClipboard(commands) );
80 KEYS(commandDialogListId << keyNameFor(QKeySequence::Paste));
81
82 TEST( m_test->setClipboard(QByteArray()) );
83 KEYS(commandDialogListId << keyNameFor(QKeySequence::Copy));
84 WAIT_FOR_CLIPBOARD(commands);
85
86 KEYS(commandDialogListId << "Enter" << clipboardBrowserId);
87 RUN("commands().length", "2\n");
88 }
89
90 void CoreTests::toggleClipboardMonitoring()
91 {
92 const QByteArray data1 = generateData();
93 TEST( m_test->setClipboard(data1) );
94 RUN("clipboard", data1);
95 WAIT_ON_OUTPUT("read" << "0", data1);
96
97 RUN("disable", "");
98 RUN("monitoring", "false\n");
99 WAIT_ON_OUTPUT("isClipboardMonitorRunning", "false\n");
100
101 const QByteArray data2 = generateData();
102 TEST( m_test->setClipboard(data2) );
103 RUN("clipboard", data2);
104 WAIT_ON_OUTPUT("read" << "0", data1);
105
106 RUN("enable", "");
107 RUN("monitoring", "true\n");
108 WAIT_ON_OUTPUT("isClipboardMonitorRunning", "true\n");
109
110 const QByteArray data3 = generateData();
111 TEST( m_test->setClipboard(data3) );
112 RUN("clipboard", data3);
113 WAIT_ON_OUTPUT("read" << "0", data3);
114 }
115
116 void CoreTests::clipboardToItem()
117 {
118 TEST( m_test->setClipboard("TEXT1") );
119 RUN("clipboard", "TEXT1");
120 WAIT_ON_OUTPUT("read" << "0", "TEXT1");
121 RUN("read" << "?" << "0", "text/plain\n");
122
123 TEST( m_test->setClipboard("DATA1", "DATA") );
124 WAIT_ON_OUTPUT("clipboard" << "DATA", "DATA1");
125
126 // Unicode test.
127 const auto test = QString::fromUtf8(QByteArray("Zkouška s různými českými znaky!"));
128 const auto bytes = test.toUtf8();
129 TEST( m_test->setClipboard(bytes) );
130 RUN("clipboard", bytes);
131 WAIT_ON_OUTPUT("read" << "0", bytes);
132 }
133
134 void CoreTests::clipboardMimeSizeLimit()
135 {
136 // Restart server with size limits: text/plain max 10 bytes, all other text/* rejected.
137 // Use text/plain.* to also match text/plain;charset=utf-8 (synthesized on Windows/macOS).
138 TEST( m_test->stopServer() );
139 m_test->setEnv("COPYQ_CLIPBOARD_MIME_SIZE_LIMIT", "text/plain.*:10;text/.*:0");
140 TEST( m_test->startServer() );
141
142 // Data under the limit should be stored.
143 TEST( m_test->setClipboard("SHORT") );
144 WAIT_ON_OUTPUT("read" << "0", "SHORT");
145
146 // Oversized text/plain should be skipped.
147 // Use the QVariantMap overload to set clipboard without server-side verification,
148 // since the size limit also affects the clipboard scripting command.
149 const QVariantMap oversizedData{{"text/plain", "THIS TEXT IS OVER TEN BYTES"}};
150 TEST( m_test->setClipboard(oversizedData) );
151
152 // Set another small item; if the oversized data were stored it would
153 // appear between SHORT and AFTER, changing item count to 3.
154 TEST( m_test->setClipboard("AFTER") );
155 WAIT_ON_OUTPUT("read" << "0" << "1" << "2", "AFTER\nSHORT\n");
156
157 // HTML with plain text: HTML should be rejected (text/.*:0), plain text kept.
158 const QVariantMap htmlData{{mimeHtml, "<b>hello</b>"}, {mimeText, "hello"}};
159 TEST( m_test->setClipboard(htmlData) );
160 WAIT_ON_OUTPUT("read" << "0" << "1" << "2" << "3", "hello\nAFTER\nSHORT\n");
161 RUN("read" << mimeHtml << "0", "");
162 }
163
164 void CoreTests::clipboardMimeSizeLimitConfig()
165 {
166 // Config option path: under-limit stored, over-limit skipped.
167 // Use text/plain.* to also match text/plain;charset=utf-8 (synthesized on Windows/macOS).
168 RUN("config" << "clipboard_mime_size_limit" << "text/plain.*:10;text/.*:0", "text/plain.*:10;text/.*:0\n");
169
170 TEST( m_test->setClipboard("SHORT") );
171 WAIT_ON_OUTPUT("read" << "0", "SHORT");
172
173 // Oversized text/plain skipped.
174 const QVariantMap oversizedData{{"text/plain", "THIS TEXT IS OVER TEN BYTES"}};
175 TEST( m_test->setClipboard(oversizedData) );
176 TEST( m_test->setClipboard("AFTER") );
177 WAIT_ON_OUTPUT("read" << "0" << "1" << "2", "AFTER\nSHORT\n");
178
179 // Blocked format with allowed format: first-match-wins.
180 RUN("config" << "clipboard_mime_size_limit" << "text/uri-list:0;.*:100M", "text/uri-list:0;.*:100M\n");
181 const QVariantMap uriData{{"text/uri-list", "https://example.com"}, {"text/plain", "URI_KEPT"}};
182 TEST( m_test->setClipboard(uriData) );
183 WAIT_ON_OUTPUT("read" << "0", "URI_KEPT");
184 RUN("read" << "text/uri-list" << "0", "");
185
186 // Restore default.
187 RUN("config" << "clipboard_mime_size_limit" << "", "\n");
188 }
189
190 void CoreTests::itemToClipboard()
191 {
192 RUN("add" << "TESTING2" << "TESTING1", "");
193 RUN("read" << "0" << "1", "TESTING1\nTESTING2");
194
195 RUN("select" << "0", "");
196
197 WAIT_FOR_CLIPBOARD("TESTING1");
198 RUN("clipboard", "TESTING1");
199
200 // select second item and move to top
201 RUN("config" << "move" << "true", "true\n");
202 RUN("select" << "1", "");
203 RUN("read" << "0" << "1", "TESTING2\nTESTING1");
204
205 WAIT_FOR_CLIPBOARD("TESTING2");
206 RUN("clipboard", "TESTING2");
207
208 // select without moving
209 RUN("config" << "move" << "0", "false\n");
210 RUN("select" << "1", "");
211 RUN("read" << "0" << "1", "TESTING2\nTESTING1");
212
213 WAIT_FOR_CLIPBOARD("TESTING1");
214 RUN("clipboard", "TESTING1");
215 }
216
217 void CoreTests::tabAdd()
218 {
219 const QString tab = testTab(1);
220 const Args args = Args("tab") << tab << "separator" << " ";
221
222 QVERIFY( !hasTab(tab) );
223 RUN(args, "");
224 RUN(args << "size", "0\n");
225 RUN(args << "add" << "ghi" << "def" << "abc", "");
226 QVERIFY( hasTab(tab) );
227
228 // Restart server.
229 TEST( m_test->stopServer() );
230 TEST( m_test->startServer() );
231
232 QVERIFY( hasTab(tab) );
233
234 RUN(args << "size", "3\n");
235 RUN(args << "read" << "0" << "1" << "2", "abc def ghi");
236 }
237
238 void CoreTests::tabRemove()
239 {
240 const QString tab = testTab(1);
241 const Args args = Args("tab") << tab << "separator" << " ";
242
243 RUN(args << "add" << "", "");
244 QVERIFY( hasTab(tab) );
245 RUN(Args() << "removetab" << tab, "");
246 QVERIFY( !hasTab(tab) );
247
248 RUN_EXPECT_ERROR("removetab" << tab, CommandException);
249 }
250
251 void CoreTests::tabIcon()
252 {
253 const QString tab0 = testTab(1);
254 const QString tab = testTab(2);
255 const QString icon = ":/images/icon";
256
257 RUN("tab" << tab << "add" << "", "");
258 RUN("tabIcon" << tab, "\n");
259 RUN("tabicon" << tab0, "\n");
260 RUN("tabicon" << tab << icon, "");
261 RUN("tabIcon" << tab, icon + "\n");
262 RUN("tabicon" << tab0, "\n");
263 RUN("tabIcon" << tab << "", "");
264 RUN("tabicon" << tab, "\n");
265 }
266
267 void CoreTests::action()
268 {
269 const Args args = Args("tab") << testTab(1);
270 const Args argsAction = Args(args) << "action";
271 const QString action = QString::fromLatin1("copyq %1 %2").arg(args.join(" "));
272
273 // action with size
274 RUN(argsAction << action.arg("size") << "", "");
275 WAIT_ON_OUTPUT(args << "size", "1\n");
276 RUN(args << "read" << "0", "0\n");
277
278 // action with size
279 RUN(argsAction << action.arg("size") << "", "");
280 WAIT_ON_OUTPUT(args << "size", "2\n");
281 RUN(args << "read" << "0", "1\n");
282
283 // action with eval print
284 RUN(argsAction << action.arg("eval 'print(\"A,B,C\")'") << "", "");
285 WAIT_ON_OUTPUT(args << "size", "3\n");
286 RUN(args << "read" << "0", "A,B,C");
287
288 // action with read and comma separator for new items
289 RUN(argsAction << action.arg("read 0") << ",", "");
290 WAIT_ON_OUTPUT(args << "size", "6\n");
291 RUN(args << "read" << "0" << "1" << "2", "C\nB\nA");
292 }
293
294 void CoreTests::renameTab()
295 {
296 const QString tab1 = testTab(1);
297 const QString tab2 = testTab(2);
298
299 RUN("tab" << tab1 << "add" << "ghi" << "def" << "abc", "");
300
301 RUN("renametab" << tab1 << tab2, "");
302 RUN("tab" << tab2 << "size", "3\n");
303 RUN("tab" << tab2 << "read" << "0" << "1" << "2", "abc\ndef\nghi");
304 QVERIFY( !hasTab(tab1) );
305
306 // Rename non-existing tab.
307 RUN_EXPECT_ERROR("renametab" << tab1 << tab2, CommandException);
308
309 // Rename to same name.
310 RUN_EXPECT_ERROR("renametab" << tab2 << tab2, CommandException);
311
312 // Rename to empty name.
313 RUN_EXPECT_ERROR("renametab" << tab2 << "", CommandException);
314
315 // Rename to existing tab.
316 RUN_EXPECT_ERROR("renametab" << tab2 << clipboardTabName, CommandException);
317
318 QVERIFY( !hasTab(tab1) );
319 QVERIFY( hasTab(tab2) );
320
321 RUN("renametab" << tab2 << tab1, "");
322 RUN("tab" << tab1 << "read" << "0" << "1" << "2", "abc\ndef\nghi");
323
324 QVERIFY( hasTab(tab1) );
325 QVERIFY( !hasTab(tab2) );
326 }
327
328 void CoreTests::renameClipboardTab()
329 {
330 const QString newClipboardTabName = clipboardTabName + QStringLiteral("2");
331 RUN("config" << "tray_tab" << clipboardTabName, clipboardTabName + QStringLiteral("\n"));
332 const QString icon = ":/images/icon";
333 RUN("tabicon" << clipboardTabName << icon, "");
334
335 RUN("renametab" << clipboardTabName << newClipboardTabName, "");
336 RUN("tab", newClipboardTabName + "\n");
337 RUN("config" << "clipboard_tab", newClipboardTabName + QStringLiteral("\n"));
338 RUN("config" << "tray_tab", newClipboardTabName + QStringLiteral("\n"));
339 RUN("tabicon" << newClipboardTabName, icon + QStringLiteral("\n"));
340
341 TEST( m_test->setClipboard("test1") );
342 WAIT_ON_OUTPUT("tab" << newClipboardTabName << "read" << "0", "test1");
343 RUN("tab", newClipboardTabName + "\n");
344
345 WAIT_ON_OUTPUT("read" << "0", "test1");
346 RUN("tab", newClipboardTabName + "\n");
347 }
348
349 void CoreTests::importExportTab()
350 {
351 const QString tab = testTab(1);
352 const Args args = Args("tab") << tab << "separator" << " ";
353
354 RUN(args << "add" << "ghi" << "def" << "abc", "");
355
356 TemporaryFile tmp;
357 RUN(args << "exporttab" << tmp.fileName(), "");
358
359 RUN("removetab" << tab, "");
360 QVERIFY( !hasTab(tab) );
361
362 RUN(args << "importtab" << tmp.fileName(), "");
363 RUN(args << "read" << "0" << "1" << "2", "abc def ghi");
364 RUN(args << "size", "3\n");
365
366 // Export with relative path.
367 TemporaryFile tmp2;
368
369 // Change back to original working directory once finished.
370 struct CurrentDirectoryGuard {
371 CurrentDirectoryGuard() : oldDir(QDir::currentPath()) {}
372 ~CurrentDirectoryGuard() { QDir::setCurrent(oldDir); }
373 const QString oldDir;
374 } currentDirectoryGuard;
375
376 QDir::setCurrent( QDir::cleanPath(tmp2.fileName() + "/..") );
377
378 const QString fileName = QFileInfo( tmp2.fileName() ).fileName();
379
380 RUN(args << "add" << "012", "");
381 RUN(args << "exporttab" << fileName, "");
382
383 RUN("removetab" << tab, "");
384 QVERIFY( !hasTab(tab) );
385
386 RUN(args << "importtab" << fileName, "");
387 RUN(args << "read" << "0" << "1" << "2" << "3", "012 abc def ghi");
388 }
389
390 void CoreTests::removeAllFoundItems()
391 {
392 auto args = Args("add");
393 for (int i = 0; i < 50; ++i) {
394 args << QString::fromLatin1("a%1").arg(i);
395 args << QString::fromLatin1("b%1").arg(i);
396 }
397
398 RUN(args, "");
399 RUN("size", "100\n");
400
401 RUN("filter" << "a", "");
402 KEYS("CTRL+A" << m_test->shortcutToRemove());
403
404 RUN("size", "50\n");
405 RUN("read" << "49" << "48" << "47", "b0\nb1\nb2");
406 RUN("read" << "0" << "1" << "2", "b49\nb48\nb47");
407 }
408
409 void CoreTests::nextPrevious()
410 {
411 const QString tab = testTab(1);
412 const Args args = Args("tab") << tab;
413 RUN(args << "add" << "C" << "B" << "A", "");
414 RUN("setCurrentTab" << tab, "");
415
416 RUN(args << "next", "");
417 WAIT_FOR_CLIPBOARD("B");
418
419 RUN(args << "next", "");
420 WAIT_FOR_CLIPBOARD("C");
421
422 RUN(args << "next", "");
423 WAIT_FOR_CLIPBOARD("C");
424
425 RUN(args << "previous", "");
426 WAIT_FOR_CLIPBOARD("B");
427
428 RUN(args << "previous", "");
429 WAIT_FOR_CLIPBOARD("A");
430
431 RUN(args << "previous", "");
432 WAIT_FOR_CLIPBOARD("A");
433 }
434
435 void CoreTests::externalEditor()
436 {
437 const QString tab = testTab(1);
438 const Args args = Args("tab") << tab;
439 const QString editorTab = testTab(2);
440 const Args editorArgs = Args("tab") << editorTab;
441 const Args editorFileNameArgs = Args(editorArgs) << "read" << "0";
442 const Args editorEndArgs = Args(editorArgs) << "remove" << "0";
443
444 // Set editor command which add file name to edit to special editor tab.
445 // The command finishes when the special tab is emptied by this test.
446 // File to edit is removed by application when the command finished.
447 const auto cmd = QString(
448 R"(copyq tab "%1" eval "add(arguments[1]); while(length()) sleep(100);" --)"
449 ).arg(editorTab) + " %1";
450 RUN("config" << "editor" << cmd, cmd + "\n");
451
452 // Set clipboard with mimeOwner to avoid adding new item
453 // (this should trigger Scriptable::onOwnClipboardChanged)
454 const QByteArray data1 = generateData();
455 TEST( m_test->setClipboard({{mimeText, data1}, {mimeOwner, "TEST"}}) );
456 RUN("clipboard", data1);
457
458 #define EDIT(DATA1, DATA2) \
459 do { \
460 WAIT_ON_OUTPUT(editorArgs << "size", "1\n"); \
461 QByteArray out; \
462 QByteArray err; \
463 run(editorFileNameArgs, &out, &err); \
464 QVERIFY2( testStderr(err), err ); \
465 QFile file(out); \
466 QVERIFY( file.exists() ); \
467 QVERIFY( file.open(QIODevice::ReadWrite) ); \
468 QVERIFY( file.readAll() == (DATA1) ); \
469 file.write(DATA2); \
470 file.close(); \
471 RUN(editorEndArgs, ""); \
472 waitWhileFileExists(file); \
473 } while(false)
474
475 // Edit clipboard.
476 RUN("edit" << "-1", "");
477 const QByteArray data2 = generateData();
478 EDIT(data1, data2);
479
480 // Check if clipboard changed.
481 WAIT_ON_OUTPUT("read" << "0", data1 + data2);
482 WAIT_FOR_CLIPBOARD(data1 + data2);
483
484 // Edit existing item.
485 const QString text =
486 "Some text to edit,\n"
487 "with second line!\n"
488 + generateData();
489 RUN(args << "add" << text, "");
490
491 // Modify first item.
492 RUN(args << "edit" << "0", "");
493 const QByteArray data3 = generateData();
494 EDIT(text.toUtf8(), data3);
495
496 // Check first item.
497 WAIT_ON_OUTPUT(args << "read" << "0", text.toUtf8() + data3);
498
499 // Edit new item.
500 RUN(args << "edit", "");
501 const QByteArray data4 = generateData();
502 EDIT(QByteArray(), data4);
503
504 // Check first item.
505 WAIT_ON_OUTPUT(args << "read" << "0", data4);
506
507 #undef EDIT
508 }
509
510 void CoreTests::nextPreviousTab()
511 {
512 const auto tab1 = testTab(1);
513 const auto tab2 = testTab(2);
514 const auto setTabsCommand =
515 QStringLiteral("config('tabs', ['%1','%2'])").arg(tab1, tab2);
516 RUN(setTabsCommand, tab1 + "\n" + tab2 + "\n");
517
518 using KeyPair = QPair<QString, QString>;
519 const QList<KeyPair> keyPairs = QList<KeyPair>()
520 << KeyPair(keyNameFor(QKeySequence::NextChild), keyNameFor(QKeySequence::PreviousChild))
521 << KeyPair("RIGHT", "LEFT");
522
523 for (const auto &keyPair : keyPairs) {
524 for (const auto &optionValue : {"false", "true"}) {
525 RUN("config" << "tab_tree" << optionValue, QString(optionValue) + "\n");
526
527 KEYS(keyPair.first);
528 TEST_SELECTED(tab1 + "\n");
529 KEYS(keyPair.first);
530 TEST_SELECTED(tab2 + "\n");
531 KEYS(keyPair.first);
532
533 KEYS(keyPair.second);
534 TEST_SELECTED(tab2 + "\n");
535 KEYS(keyPair.second);
536 TEST_SELECTED(tab1 + "\n");
537 KEYS(keyPair.second);
538 }
539 }
540 }
541
542 void CoreTests::itemPreview()
543 {
544 const auto tab1 = testTab(1);
545 RUN("tab" << tab1 << "add" << "def" << "abc", "");
546 RUN("setCurrentTab" << tab1, "");
547
548 RUN("preview", "false\n");
549 KEYS(clipboardBrowserId << "F7");
550 RUN("preview", "true\n");
551
552 KEYS(clipboardBrowserId << "TAB" << itemPreviewId);
553 KEYS(itemPreviewId << "HOME");
554 KEYS(itemPreviewId << "RIGHT");
555 KEYS(itemPreviewId << "SHIFT+RIGHT");
556 KEYS(itemPreviewId << keyNameFor(QKeySequence::Copy));
557 WAIT_FOR_CLIPBOARD("b");
558
559 KEYS(itemPreviewId << "F7" << clipboardBrowserId);
560
561 RUN("preview" << "true", "false\n");
562 RUN("preview" << "false", "true\n");
563 RUN("preview" << "1", "false\n");
564 RUN("preview" << "0", "true\n");
565 RUN("preview(true)", "false\n");
566 RUN("preview(false)", "true\n");
567 RUN("preview", "false\n");
568 }
569
570 void CoreTests::openAndSavePreferences()
571 {
572 #ifdef Q_OS_MAC
573 SKIP("Can't focus configuration checkboxes on OS X");
574 #endif
575
576 RUN("config" << "check_clipboard" << "false", "false\n");
577
578 // Open preferences dialog.
579 KEYS("Ctrl+P" << configurationDialogId);
580
581 // Focus and set wrap text option.
582 // This behavior could differ on some systems and in other languages.
583 KEYS(configurationDialogId << "ALT+1");
584 KEYS(configurationDialogId << "ENTER" << clipboardBrowserId);
585 WAIT_ON_OUTPUT("config" << "check_clipboard", "true\n");
586 }
587
588 void CoreTests::pasteFromMainWindow()
589 {
590 RUN("config"
591 << "activate_closes" << "true"
592 << "activate_focuses" << "true"
593 << "activate_pastes" << "true"
594 ,
595 "activate_closes=true\n"
596 "activate_focuses=true\n"
597 "activate_pastes=true\n"
598 );
599
600 RUN("add" << "TEST", "");
601 RUN("hide", "");
602 RUN_MULTIPLE(
603 [&]{ RUN("dialog('text')", "TEST\n"); },
604 [&]{
605 KEYS("focus::QLineEdit<.*:QDialog");
606
607 QTest::qWait(250);
608 RUN("show", "");
609 QTest::qWait(250);
610 KEYS(clipboardBrowserId << "ENTER");
611
612 WAIT_FOR_CLIPBOARD("TEST");
613 KEYS("focus::QLineEdit'TEST'<.*:QDialog" << "ENTER");
614 }
615 );
616 }
617
618 void CoreTests::pasteNext()
619 {
620 const auto tab1 = testTab(1);
621 RUN("setCurrentTab" << tab1, "");
622 KEYS(clipboardBrowserId << "CTRL+N" << editorId << ":NEW ");
623
624 const auto tab2 = testTab(2);
625 RUN("tab" << tab2 << "add" << "test3" << "test2" << "test1", "");
626 RUN("tab" << tab2 << "next(); paste(); next()", "");
627 waitFor(250);
628 KEYS(editorId);
629 WAIT_FOR_CLIPBOARD("test3");
630 KEYS(editorId << "F2");
631 RUN("tab" << tab1 << "read" << "0", "NEW test2");
632 }
633
634 void CoreTests::configAutostart()
635 {
636 SKIP_ON_ENV("COPYQ_TESTS_NO_AUTOSTART");
637 RUN("config" << "autostart" << "true", "true\n");
638 RUN("config" << "autostart", "true\n");
639 RUN("config" << "autostart" << "false", "false\n");
640 RUN("config" << "autostart", "false\n");
641 }
642
643 void CoreTests::envVariablePaths()
644 {
645 {
646 const auto path = QDir::home().absoluteFilePath("copyq-settings");
647 const auto environment = QStringList("COPYQ_SETTINGS_PATH=" + path);
648
649 QByteArray out;
650 QByteArray err;
651 run(Args() << "info" << "config", &out, &err, QByteArray(), environment);
652 QVERIFY2( testStderr(err), err );
653
654 const auto expectedOut = path.toUtf8();
655 QCOMPARE( out.left(expectedOut.size()), expectedOut );
656 }
657
658 {
659 const auto path = QDir::home().absoluteFilePath("copyq-data");
660 const auto environment = QStringList("COPYQ_ITEM_DATA_PATH=" + path);
661
662 QByteArray out;
663 QByteArray err;
664 run(Args() << "info" << "data", &out, &err, QByteArray(), environment);
665 QVERIFY2( testStderr(err), err );
666
667 const auto expectedOut = path.toUtf8();
668 QCOMPARE( out.left(expectedOut.size()), expectedOut );
669 }
670 }
671
672 void CoreTests::configTabs()
673 {
674 const QString sep = QStringLiteral("\n");
675 RUN("config" << "tabs", clipboardTabName + sep);
676
677 const QString tab1 = testTab(1);
678 RUN("tab" << tab1 << "add" << "test", "");
679 RUN("config" << "tabs", clipboardTabName + sep + tab1 + sep);
680
681 const QString tab2 = testTab(2);
682 RUN(QString("config('tabs', ['%1', '%2'])").arg(clipboardTabName, tab2), clipboardTabName + sep + tab2 + sep);
683 RUN("config" << "tabs", clipboardTabName + sep + tab2 + sep + tab1 + sep);
684 RUN("tab", clipboardTabName + sep + tab2 + sep + tab1 + sep);
685
686 RUN(QString("config('tabs', ['%1', '%2'])").arg(tab1, tab2), tab1 + sep + tab2 + sep);
687 RUN("config" << "tabs", tab1 + sep + tab2 + sep + clipboardTabName + sep);
688 RUN("tab", tab1 + sep + tab2 + sep + clipboardTabName + sep);
689 }
690
691 void CoreTests::selectedItems()
692 {
693 const auto tab1 = testTab(1);
694 const Args args = Args("tab") << tab1;
695
696 RUN("selectedTab", "CLIPBOARD\n");
697 RUN("selectedItems", "");
698
699 RUN(args << "add" << "D" << "C" << "B" << "A", "");
700 RUN(args << "setCurrentTab" << tab1 << "selectItems" << "1" << "2", "true\n");
701 RUN("selectedTab", tab1 + "\n");
702 RUN(args << "selectedItems", "1\n2\n");
703 RUN(args << "currentItem", "2\n");
704
705 const auto print = R"(
706 tab(selectedTab());
707 print([selectedTab(), "c:" + currentItem(), "s:" + selectedItems()]);
708 print("\\n")
709 )";
710
711 // Selection stays consistent when moving items
712 RUN(print << "move(0)" << print, tab1 + ",c:2,s:1,2\n" + tab1 + ",c:1,s:0,1\n");
713 RUN(print, tab1 + ",c:1,s:0,1\n");
714
715 RUN(print << "plugins.itemtests.keys('HOME', 'CTRL+DOWN')" << print, tab1 + ",c:1,s:0,1\n" + tab1 + ",c:0,s:1,0\n");
716 RUN(print, tab1 + ",c:1,s:1\n");
717
718 // Selection stays consistent when removing items
719 RUN(args << "setCurrentTab" << tab1 << "selectItems" << "1" << "2" << "3", "true\n");
720 RUN(print << "remove(2)" << print, tab1 + ",c:3,s:1,2,3\n" + tab1 + ",c:2,s:1,-1,2\n");
721 RUN(print, tab1 + ",c:2,s:1,2\n");
722
723 // Renaming tab invalidates selection and all items because the tab
724 // underlying data needs to be loaded again using plugins.
725 const QString tab2 = testTab(2);
726 const auto rename = QString("renameTab('%1', '%2')").arg(tab1, tab2);
727 RUN(print << rename << print, tab1 + ",c:2,s:1,2\n" + tab1 + ",c:-1,s:\n");
728
729 RUN(print, tab2 + ",c:0,s:0\n");
730 }
731
732 void CoreTests::synchronizeInternalCommands()
733 {
734 // Keep internal commands synced with the latest version
735 // but allow user to change some attributes.
736 const auto script = R"(
737 setCommands([
738 {
739 internalId: 'copyq_global_toggle',
740 enable: false,
741 icon: 'icon.png',
742 shortcuts: ['Ctrl+F1'],
743 globalShortcuts: ['Ctrl+F2'],
744 name: 'Old name',
745 cmd: 'Old command',
746 },
747 ])
748 )";
749 RUN(script, "");
750 RUN("commands()[0].internalId", "copyq_global_toggle\n");
751 RUN("commands()[0].enable", "false\n");
752 RUN("commands()[0].icon", "icon.png\n");
753 RUN("commands()[0].shortcuts", "Ctrl+F1\n");
754 RUN("commands()[0].globalShortcuts", "Ctrl+F2\n");
755 RUN("commands()[0].name", "Show/hide main window\n");
756 RUN("commands()[0].cmd", "copyq: toggle()\n");
757 }
758
759 void CoreTests::utilityCommands()
760 {
761 // queryKeyboardModifiers
762 RUN("queryKeyboardModifiers()", "");
763
764 // pointerPosition
765 QCursor::setPos(1, 2);
766 RUN("pointerPosition", "1\n2\n");
767 QCursor::setPos(2, 3);
768 RUN("pointerPosition", "2\n3\n");
769
770 // setPointerPosition
771 RUN("setPointerPosition(1,2)", "");
772 QCOMPARE(QPoint(1, 2), QCursor::pos());
773 RUN("setPointerPosition(2,3)", "");
774 QCOMPARE(QPoint(2, 3), QCursor::pos());
775 }
776
777 void CoreTests::setTabName()
778 {
779 const auto script = R"(
780 tab('1')
781 add(1)
782 tab1Size = size()
783
784 tab('2')
785 tab2Size = size()
786
787 print(tab1Size + ',' + tab2Size)
788 )";
789 RUN(script, "1,0");
790 }
791
792 void CoreTests::abortInputReader()
793 {
794 QProcess p;
795 p.start(
796 m_test->executable(),
797 {"afterMilliseconds(250, abort); input(); print('DONE'); 'DONE'"}
798 );
799 QVERIFY2( p.waitForStarted(10000), "Process failed to start" );
800 QVERIFY2( p.waitForFinished(5000), "Process failed to finish" );
801 QCOMPARE( p.readAllStandardOutput(), "" );
802 }
803
804 void CoreTests::changeAlwaysOnTop()
805 {
806 // The window should be still visible and focused after changing always-on-top flag.
807 RUN("visible", "true\n");
808 RUN("focused", "true\n");
809 RUN("config" << "always_on_top", "false\n");
810
811 RUN("config" << "always_on_top" << "true", "true\n");
812 WAIT_ON_OUTPUT("visible", "true\n");
813 // There is a problem activating the window again after
814 // changing the always-on-top flag on macOS with Qt 6.
815 #if !defined(Q_OS_MAC)
816 WAIT_ON_OUTPUT("focused", "true\n");
817 #endif
818
819 RUN("config" << "always_on_top" << "false", "false\n");
820 WAIT_ON_OUTPUT("visible", "true\n");
821 #if !defined(Q_OS_MAC)
822 WAIT_ON_OUTPUT("focused", "true\n");
823 #endif
824
825 RUN("hide", "");
826 RUN("visible", "false\n");
827 RUN("focused", "false\n");
828
829 RUN("config" << "always_on_top" << "true", "true\n");
830 WAIT_ON_OUTPUT("visible", "false\n");
831 WAIT_ON_OUTPUT("focused", "false\n");
832
833 RUN("config" << "always_on_top" << "false", "false\n");
834 WAIT_ON_OUTPUT("visible", "false\n");
835 WAIT_ON_OUTPUT("focused", "false\n");
836 }
837
838 void CoreTests::networkTests()
839 {
840 // networkHeaders (no network needed)
841 RUN("print(NetworkRequest().headers['User-Agent'])", copyqUserAgent());
842 RUN("r = NetworkRequest(); r.headers['X'] = 'Y'; r.headers['X']", "Y\n");
843
844 // networkGetPostAsync (no network needed)
845 RUN("r = networkGetAsync('copyq-test://example.com'); print([r.finished,r.error,r.finished])",
846 "false,Protocol \"copyq-test\" is unknown,true");
847 RUN("r = networkPostAsync('copyq-test://example.com'); print([r.finished,r.error,r.finished])",
848 "false,Protocol \"copyq-test\" is unknown,true");
849
850 if (qgetenv("COPYQ_TESTS_NO_NETWORK") == "1")
851 return;
852
853 // networkGet
854 RUN("r = networkGet('https://httpcan.org'); r.status", "200\n");
855
856 // networkPost
857 {
858 const auto script = R"(
859 r = NetworkRequest();
860 r.headers['Content-Type'] = 'text/plain';
861 s = r.request('POST', 'https://httpcan.org/post?hello=1', 'Hello');
862 json = s.data;
863 try {
864 data = JSON.parse(str(json));
865 userAgent = data.headers['user-agent'].replace(/\\/.*/, '/xyz');
866 [data.data, JSON.stringify(data.args), userAgent, s.status];
867 } catch (e) {
868 [`Error parsing JSON response: ${e}\n`, json, s.status];
869 }
870 )";
871 RUN(script, "Hello\n{\"hello\":\"1\"}\nCopyQ/xyz\n200\n");
872 }
873
874 // networkRedirects
875 RUN("r = networkGet('https://httpcan.org/redirect-to?url=https://httpcan.org'); r.status", "302\n");
876 {
877 const auto script = R"(
878 r = NetworkRequest();
879 r.maxRedirects = 1;
880 s = r.request('GET', 'https://httpcan.org');
881 [s.status, s.url]
882 )";
883 RUN(script, "200\nhttps://httpcan.org\n");
884 }
885 }
886
887 void CoreTests::pluginNotInstalled()
888 {
889 RUN_EXPECT_ERROR_WITH_STDERR(
890 "plugins.bad_plugin", CommandException,
891 "Plugin \"bad_plugin\" is not installed"
892 );
893 }
894
895 void CoreTests::startServerAndRunCommand()
896 {
897 RUN("--start-server" << "tab" << testTab(1) << "write('TEST');read(0)", "TEST");
898
899 TEST( m_test->stopServer() );
900
901 QByteArray stdoutActual;
902 QByteArray stderrActual;
903
904 QCOMPARE( run(Args("--start-server") << "tab" << testTab(1) << "read" << "0", &stdoutActual, &stderrActual), 0 );
905 QVERIFY2( testStderr(stderrActual), stderrActual );
906 QCOMPARE(stdoutActual, "TEST");
907
908 QCOMPARE( run(Args() << "tab" << testTab(1) << "read" << "0", &stdoutActual, &stderrActual), 0 );
909 QVERIFY2( testStderr(stderrActual), stderrActual );
910 QCOMPARE(stdoutActual, "TEST");
911
912 // The sleep() call ensures that the server finishes and terminates the
913 // client connection.
914 QCOMPARE( run(Args("--start-server") << "exit();sleep(10000)", &stdoutActual, &stderrActual), 0 );
915 QCOMPARE(stdoutActual, "");
916 QVERIFY2( stderrActual.contains("Terminating server.\n"), stderrActual );
917
918 // Try to start new client.
919 SleepTimer t(10000);
920 while ( run(Args("exit();sleep(10000)")) == 0 && t.sleep() ) {}
921 }
922
923 void CoreTests::avoidStoringPasswords()
924 {
925 TEST( m_test->setClipboard(secretData("secret")) );
926 WAIT_ON_OUTPUT("clipboard", "secret");
927 RUN("read" << "0" << "1" << "2", "\n\n");
928 RUN("count", "0\n");
929
930 KEYS(clipboardBrowserId << keyNameFor(QKeySequence::Paste));
931 WAIT_ON_OUTPUT("count", "1\n");
932 RUN("read" << "0" << "1" << "2", "secret\n\n");
933 }
934
935 void CoreTests::scriptsForPasswords()
936 {
937 const auto script = R"(
938 setCommands([{
939 isScript: true,
940 cmd: `global.onSecretClipboardChanged = function() {
941 add("SECRET");
942 }`
943 }])
944 )";
945 RUN(script, "");
946 WAIT_ON_OUTPUT("commands().length", "1\n");
947 TEST( m_test->setClipboard(secretData("secret")) );
948 WAIT_ON_OUTPUT("read" << "0" << "1" << "2", "SECRET\n\n");
949 RUN("count", "1\n");
950 }
951
952 void CoreTests::currentClipboardOwner()
953 {
954 const auto script = R"(
955 setCommands([
956 {
957 isScript: true,
958 cmd: 'global.currentClipboardOwner = function() { return settings("clipboard_owner"); }'
959 },
960 {
961 automatic: true,
962 input: mimeWindowTitle,
963 cmd: 'copyq: setData("application/x-copyq-owner-test", input())',
964 },
965 {
966 automatic: true,
967 wndre: '.*IGNORE',
968 cmd: 'copyq ignore; copyq add IGNORED',
969 },
970 ])
971 )";
972 RUN("settings" << "clipboard_owner" << "TEST1", "");
973 RUN(script, "");
974
975 TEST( m_test->setClipboard("test1") );
976 WAIT_ON_OUTPUT("read(0)", "test1");
977 RUN("read('application/x-copyq-owner-test', 0)", "TEST1");
978
979 RUN("settings" << "clipboard_owner" << "TEST2", "");
980 RUN("config" << "update_clipboard_owner_delay_ms" << "10000", "10000\n");
981 TEST( m_test->setClipboard("test2") );
982 WAIT_ON_OUTPUT("read(0)", "test2");
983 RUN("read('application/x-copyq-owner-test', 0)", "TEST2");
984
985 RUN("settings" << "clipboard_owner" << "TEST3", "");
986 TEST( m_test->setClipboard("test3") );
987 WAIT_ON_OUTPUT("read(0)", "test3");
988 RUN("read('application/x-copyq-owner-test', 0)", "TEST2");
989
990 RUN("settings" << "clipboard_owner" << "TEST4_IGNORE", "");
991 RUN("config" << "update_clipboard_owner_delay_ms" << "0", "0\n");
992 TEST( m_test->setClipboard("test4") );
993 WAIT_ON_OUTPUT("read(0)", "IGNORED");
994
995 RUN("settings" << "clipboard_owner" << "TEST5", "");
996 TEST( m_test->setClipboard("test5") );
997 WAIT_ON_OUTPUT("read(0)", "test5");
998 RUN("read('application/x-copyq-owner-test', 0)", "TEST5");
999 }
1000
1001 void CoreTests::saveLargeItem()
1002 {
1003 const auto tab = testTab(1);
1004 const auto args = Args("tab") << tab;
1005
1006 const auto script = R"(
1007 write(0, [{
1008 'text/plain': '1234567890'.repeat(10000),
1009 'application/x-copyq-test-data': 'abcdefghijklmnopqrstuvwxyz'.repeat(10000),
1010 }])
1011 )";
1012 RUN(args << script, "");
1013
1014 for (int i = 0; i < 2; ++i) {
1015 RUN(args << "read(0).left(20)", "12345678901234567890");
1016 RUN(args << "read(0).length", "100000\n");
1017 RUN(args << "getItem(0)[mimeText].length", "100000\n");
1018 RUN(args << "getItem(0)[mimeText].left(20)", "12345678901234567890");
1019 RUN(args << "getItem(0)['application/x-copyq-test-data'].left(26)", "abcdefghijklmnopqrstuvwxyz");
1020 RUN(args << "getItem(0)['application/x-copyq-test-data'].length", "260000\n");
1021 RUN(args << "ItemSelection().selectAll().itemAtIndex(0)[mimeText].length", "100000\n");
1022 RUN("unload" << tab, tab + "\n");
1023 }
1024
1025 RUN("show" << tab, "");
1026 KEYS(clipboardBrowserId << keyNameFor(QKeySequence::Copy));
1027 WAIT_ON_OUTPUT("clipboard().left(20)", "12345678901234567890");
1028 RUN("clipboard('application/x-copyq-test-data').left(26)", "abcdefghijklmnopqrstuvwxyz");
1029 RUN("clipboard('application/x-copyq-test-data').length", "260000\n");
1030
1031 const auto tab2 = testTab(2);
1032 const auto args2 = Args("tab") << tab2;
1033 RUN("show" << tab2, "");
1034 waitFor(250);
1035 KEYS(clipboardBrowserId << keyNameFor(QKeySequence::Paste));
1036 RUN(args2 << "read(0).left(20)", "12345678901234567890");
1037 RUN(args2 << "read(0).length", "100000\n");
1038 RUN(args << "getItem(0)['application/x-copyq-test-data'].left(26)", "abcdefghijklmnopqrstuvwxyz");
1039 RUN(args << "getItem(0)['application/x-copyq-test-data'].length", "260000\n");
1040 }
1041
1042 void CoreTests::clipboardUriList()
1043 {
1044 const auto script = R"(
1045 setCommands([
1046 {
1047 isScript: true,
1048 cmd: 'global.clipboardFormatsToSave = function() { return [mimeUriList] }'
1049 },
1050 ])
1051 )";
1052
1053 RUN(script, "");
1054 WAIT_ON_OUTPUT("commands().length", "1\n");
1055
1056 const QByteArray uri = "https://test1.example.com";
1057 TEST( m_test->setClipboard(uri, mimeUriList) );
1058 WAIT_ON_OUTPUT("clipboard(mimeUriList)", uri);
1059 }
1060
1061 void CoreTests::singleClipboardProvider()
1062 {
1063 // Start multiple provider processes. The server should stop all but
1064 // the last one that registers.
1065 std::array<QProcess, 3> providers;
1066 const QStringList args{"--clipboard-access", "provideClipboard"};
1067 for (auto &p : providers)
1068 QVERIFY2(m_test->startClient(&p, args), "Failed to start provider");
1069
1070 // Wait until all but one have exited.
1071 const auto isRunning = [](const QProcess &p) {
1072 return p.state() != QProcess::NotRunning;
1073 };
1074 QVERIFY(QTest::qWaitFor(
1075 [&]() { return 1 == std::count_if(std::begin(providers), std::end(providers), isRunning); },
1076 10000));
1077
1078 // Take clipboard ownership so the surviving provider detects the
1079 // change and exits on its own (tests the self-termination path).
1080 RUN("copy" << "TEST", "true\n");
1081 for (auto &p : providers) {
1082 if (p.state() != QProcess::NotRunning) {
1083 QVERIFY2(p.waitForFinished(10000),
1084 "Provider did not exit after clipboard ownership change");
1085 }
1086 }
1087 }