-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwindow.cpp
1971 lines (1760 loc) · 69.6 KB
/
window.cpp
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
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright © 2014 cat <cat@wolfgirl.org>
* This program is free software. It comes without any warranty, to the extent
* permitted by applicable law. You can redistribute it and/or modify it under
* the terms of the Do What The Fuck You Want To Public License, Version 2, as
* published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
*/
#include <QApplication>
#include <QCollator>
#include <QDebug>
#include <QDesktopServices>
#include <QDirIterator>
#include <QDragEnterEvent>
#include <QDragMoveEvent>
#include <QDropEvent>
#include <QFile>
#include <QFileDialog>
#include <QFileInfo>
#include <QInputDialog>
#include <QKeySequence>
#include <QLoggingCategory>
#include <QMenuBar>
#include <QMessageBox>
#include <QMimeData>
#include <QNetworkAccessManager>
#include <QNetworkProxyFactory>
#include <QNetworkReply>
#include <QProcess>
#include <QProxyStyle>
#include <QSettings>
#include <QStyle>
#include <QUrl>
#include <QVersionNumber>
#include <memory>
#include "window.h"
#include "global_enums.h"
#include "util/open_graphical_shell.h"
#include "util/command_placeholders.h"
#include "util/size.h"
#include "util/strings.h"
#include "util/misc.h"
#include "util/network.h"
#include "statistics.h"
namespace logging_category {
Q_LOGGING_CATEGORY(window, "Window")
}
#define pdbg qCDebug(logging_category::window)
#define pwarn qCWarning(logging_category::window)
#define SETT_WINDOW_GEOMETRY QStringLiteral("window/geometry")
#define SETT_WINDOW_STATE QStringLiteral("window/state")
#define SETT_LAST_DIR QStringLiteral("window/last-directory")
#define SETT_LAST_SESSION_DIR QStringLiteral("window/last-session-directory")
#define SETT_SHOW_MENU QStringLiteral("window/show-menu")
#define SETT_SHOW_STATUS QStringLiteral("window/show-statusbar")
#define SETT_SHOW_CURRENT_DIR QStringLiteral("window/show-current-directory")
#define SETT_SHOW_STATUS_MAIN QStringLiteral("window/show-status-in-main")
#define SETT_SHOW_INPUT QStringLiteral("window/show-input")
#define SETT_STYLE QStringLiteral("window/style")
#define SETT_VIEW_MODE QStringLiteral("window/view-mode")
#define SETT_EDIT_MODE QStringLiteral("window/edit-mode")
#define SETT_FIT_TO_SCREEN QStringLiteral("window/fit-to-screen")
#define SETT_NAVIGATE_BY_WHEEL QStringLiteral("window/scroll-navigation")
#define SETT_PLAY_MUTE QStringLiteral("window/video_mute")
#define SETT_REPLACE_TAGS QStringLiteral("imageboard/replace-tags")
#define SETT_RESTORE_TAGS QStringLiteral("imageboard/restore-tags")
#define SETT_FORCE_AUTHOR_FIRST QStringLiteral("imageboard/force-author-first")
#ifdef Q_OS_WIN
#define SETT_LAST_VER_CHECK QStringLiteral("last-version-check")
#define SETT_VER_CHECK_ENABLED QStringLiteral("version-check-enabled")
#define VER_CHECK_URL QUrl(QStringLiteral("https://raw.githubusercontent.com/0xb8/WiseTagger/version/current.txt"))
#endif
//------------------------------------------------------------------------------
Window::Window(QWidget *_parent) : QMainWindow(_parent)
, m_tagger( this)
, m_reverse_search( this)
, a_open_file( tr("&Open File..."), nullptr)
, a_open_dir( tr("Open &Folder..."), nullptr)
, a_open_dir_recurse(tr("Open Folder Recursi&vely..."), nullptr)
, a_delete_file( tr("&Delete Current Image"), nullptr)
, a_copy_file( tr("Copy image to clipboard"), nullptr)
, a_open_post( tr("Open Imageboard &Post..."), nullptr)
, a_iqdb_search( tr("&Reverse Search Image..."), nullptr)
, a_exit( tr("&Exit"), nullptr)
, a_hide( tr("Hide to tray"), nullptr)
, a_set_queue_filter(tr("Set &Queue Filter..."), nullptr)
, a_next_file( tr("&Next Image"), nullptr)
, a_prev_file( tr("&Previous Image"), nullptr)
, a_save_file( tr("&Save"), nullptr)
, a_save_next( tr("Save and Open Next Image"), nullptr)
, a_save_prev( tr("Save and Open Previous Image"), nullptr)
, a_next_fixable( tr("Next fixable image"), nullptr)
, a_prev_fixable( tr("Previous fixable image"), nullptr)
, a_go_to_number( tr("&Go To File Number..."), nullptr)
, a_open_session( tr("Open Session"), nullptr)
, a_save_session( tr("Save Session"), nullptr)
, a_fix_tags( tr("&Apply Tag Fixes"), nullptr)
, a_fetch_tags( tr("Fetch Imageboard Tags..."), nullptr)
, a_open_loc( tr("Open &Containing Folder"), nullptr)
, a_reload_tags( tr("&Reload Tag File"), nullptr)
, a_open_tags( tr("Open Tag File &Location"), nullptr)
, a_edit_tags( tr("&Edit Tag File"), nullptr)
, a_edit_temp_tags( tr("Edit Temporary Tags..."), nullptr)
, a_edit_mode( QString{}, nullptr)
, a_ib_replace( tr("Re&place Imageboard Tags"), nullptr)
, a_ib_restore( tr("Re&store Imageboard Tags"), nullptr)
, a_tag_forcefirst( tr("&Force Author Tags First"), nullptr)
, a_fit_to_screen( tr("Fit to Screen"), nullptr)
, a_navigate_by_wheel(tr("Switch files with Mouse Wheel"))
, a_show_settings( tr("P&references..."), nullptr)
, a_view_normal( tr("Show &WiseTagger"), nullptr)
, a_view_minimal( tr("Mi&nimal View"), nullptr)
, a_view_statusbar( tr("&Statusbar"), nullptr)
, a_view_fullscreen( tr("&Fullscreen"), nullptr)
, a_exit_fullscreen( tr("Exit &Fullscreen"), nullptr)
, a_view_slideshow( tr("Slide Sho&w"), nullptr)
, a_exit_slideshow( tr("Exit Slide Sho&w"), nullptr)
, a_view_menu( tr("&Menu"), nullptr)
, a_view_input( tr("Tag &Input"), nullptr)
, a_view_sort_name( tr("By File &Name"), nullptr)
, a_view_sort_type( tr("By File &Type"), nullptr)
, a_view_sort_date( tr("By Modification &Date"), nullptr)
, a_view_sort_size( tr("By File &Size"), nullptr)
, a_view_sort_length(tr("By File Name &Length"), nullptr)
, a_view_sort_tagcnt(tr("By Tag &Count"), nullptr)
, a_play_pause( tr("Play/Pause"))
, a_play_mute( tr("Mute"))
, a_rotate_cw( tr("Rotate Clockwise"))
, a_rotate_ccw( tr("Rotate Counter-Clockwise"))
, a_about( tr("&About..."), nullptr)
, a_about_qt( tr("About &Qt..."), nullptr)
, a_help( tr("&Help..."), nullptr)
, a_stats( tr("&Statistics..."), nullptr)
, ag_sort_criteria( nullptr)
, menu_file( tr("&File"))
, menu_navigation( tr("&Navigation"))
, menu_view( tr("&View"))
, menu_play( tr("&Play"))
, menu_sort( tr("&Sort Queue"))
, menu_options( tr("&Options"))
, menu_commands( tr("&Commands"))
, menu_context_commands(tr("&Commands"))
, menu_help( tr("&Help"))
, menu_short_notification()
, menu_notifications()
, menu_tray()
, m_statusbar()
, m_statusbar_label()
, m_tray_icon()
{
setCentralWidget(&m_tagger);
setAcceptDrops(true);
updateStyle(); // NOTE: should be called before menus are created.
updateWindowTitle();
createActions();
createMenus();
createCommands();
updateMenus();
initSettings();
QTimer::singleShot(50, this, &Window::parseCommandLineArguments); // NOTE: should be called later to avoid unnecessary media resize after process launch.
#ifdef Q_OS_WIN32
QTimer::singleShot(1500, this, &Window::checkNewVersion);
#endif
}
//------------------------------------------------------------------------------
void Window::fileOpenDialog()
{
const auto supported_image_formats = util::supported_image_formats_namefilter();
const auto supported_video_formats = util::supported_video_formats_namefilter();
auto fileNames = QFileDialog::getOpenFileNames(this,
tr("Open File"),
m_last_directory,
tr("All Supported Files (%1);;Image Files (%2);;Video Files (%3)")
.arg(util::join(supported_image_formats + supported_video_formats))
.arg(util::join(supported_image_formats))
.arg(util::join(supported_video_formats)));
if(fileNames.size() == 1) {
m_tagger.open(fileNames.first(), /*recursive=*/false);
}
if(fileNames.size() > 1) {
m_tagger.queue().assign(fileNames, /*recursive=*/false);
m_tagger.openFileInQueue();
}
}
void Window::directoryOpenDialog(bool recursive)
{
auto dir = QFileDialog::getExistingDirectory(nullptr,
recursive ? tr("Open Folder Recursively") : tr("Open Folder"),
m_last_directory,
QFileDialog::ShowDirsOnly);
m_tagger.openDir(dir, recursive);
}
void Window::updateProxySettings()
{
QSettings settings;
settings.beginGroup(QStringLiteral("proxy"));
bool proxy_enabled = settings.value(QStringLiteral("enabled"), false).toBool();
bool use_system_proxy = settings.value("use_system").toBool();
if(proxy_enabled) {
if (use_system_proxy) {
QNetworkProxyFactory::setUseSystemConfiguration(true);
} else {
QNetworkProxyFactory::setUseSystemConfiguration(false);
auto protocol = settings.value(QStringLiteral("protocol")).toString();
auto host = settings.value(QStringLiteral("host")).toString();
auto port = settings.value(QStringLiteral("port")).toInt();
QUrl proxy_url;
proxy_url.setScheme(protocol);
proxy_url.setHost(host);
proxy_url.setPort(port);
bool scheme_valid = (proxy_url.scheme() == QStringLiteral("http")
|| proxy_url.scheme() == QStringLiteral("socks5"));
if(!proxy_url.isValid() || proxy_url.port() == -1 || !scheme_valid)
{
QMessageBox::warning(nullptr,
tr("Invalid proxy"),
tr("<p>Proxy URL <em><code>%1</code></em> is invalid. Proxy <b>will not</b> be used!</p>").arg(proxy_url.toString()));
return;
}
QNetworkProxy::ProxyType type = QNetworkProxy::NoProxy;
if(proxy_url.scheme() == QStringLiteral("socks5"))
type = QNetworkProxy::Socks5Proxy;
else if(proxy_url.scheme() == QStringLiteral("http"))
type = QNetworkProxy::HttpProxy;
auto port_value = static_cast<uint16_t>(proxy_url.port());
auto proxy = QNetworkProxy(type, proxy_url.host(), port_value);
QNetworkProxy::setApplicationProxy(proxy);
}
} else {
QNetworkProxyFactory::setUseSystemConfiguration(false);
}
settings.endGroup();
}
void Window::updateWindowTitle()
{
if(m_tagger.isEmpty()) {
setWindowTitle(tr(Window::MainWindowTitleEmpty)
.arg(qApp->applicationVersion()));
setWindowFilePath(QString{});
return;
}
const auto media_dimensions = m_tagger.mediaDimensions();
setWindowModified(m_tagger.fileModified());
setWindowFilePath(m_tagger.currentFile());
if (m_tagger.mediaIsVideo() || m_tagger.mediaIsAnimatedImage()) {
setWindowTitle(tr(Window::MainWindowTitleFrameRate).arg(
m_tagger.currentFileName(),
QStringLiteral("[*]"),
QString::number(media_dimensions.width()),
QString::number(media_dimensions.height()),
util::size::printable(m_tagger.mediaFileSize()),
qApp->applicationVersion(),
QString::number(m_tagger.mediaFramerate(), 'g', 2)));
} else {
setWindowTitle(tr(Window::MainWindowTitle).arg(
m_tagger.currentFileName(),
QStringLiteral("[*]"),
QString::number(media_dimensions.width()),
QString::number(media_dimensions.height()),
util::size::printable(m_tagger.mediaFileSize()),
qApp->applicationVersion()));
}
}
void Window::updateWindowTitleProgress(int progress)
{
if(m_tagger.isEmpty()) {
setWindowTitle(tr(Window::MainWindowTitleEmpty)
.arg(qApp->applicationVersion()));
return;
}
setWindowTitle(tr(Window::MainWindowTitleProgress).arg(
m_tagger.currentFileName(),
QStringLiteral("[*]"),
QString::number(m_tagger.mediaDimensions().width()),
QString::number(m_tagger.mediaDimensions().height()),
util::size::printable(m_tagger.mediaFileSize()),
qApp->applicationVersion(),
QString::number(progress)));
}
void Window::updateStatusBarText()
{
if(m_tagger.isEmpty()) {
m_statusbar_label.clear();
return;
}
QString left, right;
if(m_show_current_directory) {
auto last_modified = m_tagger.currentFileLastModified();
left = tr("Zoom: %1% Directory: %2 Modified: %3 ago (%4)").arg(
QString::number(m_tagger.mediaZoomFactor() * 100.0f, 'f', 2),
QDir::toNativeSeparators(m_tagger.currentDir()),
util::duration(last_modified.secsTo(QDateTime::currentDateTime()), false),
last_modified.toString("yyyy-MM-dd hh:mm:ss"));
statusBar()->showMessage(left);
}
const auto current = m_tagger.queue().currentIndex() + 1u;
const auto qsize = m_tagger.queue().size();
auto queue_filter = m_tagger.queueFilter();
if (queue_filter.isEmpty()) {
m_statusbar_label.setText(QStringLiteral("%1 / %2 ")
.arg(QString::number(current), QString::number(qsize)));
} else {
const bool matches = m_tagger.queue().currentFileMatchesQueueFilter();
const auto current_filtered = m_tagger.queue().currentIndexFiltered() + 1u;
const auto filtered_qsize = m_tagger.queue().filteredSize();
auto color = m_statusbar_label.palette().color(QPalette::Disabled, QPalette::WindowText);
m_statusbar_label.setText(tr(
"<a href=\"#filter\" style=\"color:#0089cc;\">"
"Queue Filter:</a> %1"
" %2 "
"%3 / %4 %5")
.arg(matches ? QStringLiteral("<b>%1</b>").arg(queue_filter) : queue_filter,
matches ? "" : (filtered_qsize ? tr("(not matched)") : tr("(no matches)")),
matches ? QString::number(current_filtered) : QString::number(current),
matches ? QString::number(filtered_qsize) : QString::number(qsize),
matches ? QStringLiteral("| <span style=\"color: %3;\">%1 / %2</span> ").arg(current).arg(qsize).arg(color.name()) : ""));
}
right = m_statusbar_label.text();
QSettings settings;
if (!m_statusbar.isVisible() && settings.value(SETT_SHOW_STATUS_MAIN, true).toBool()) {
if (a_view_slideshow.isChecked())
left.clear();
m_tagger.setStatusText(left, right);
} else {
m_tagger.setStatusText(QString{}, QString{});
}
}
void Window::updateImageboardPostURL(QString url)
{
a_open_post.setDisabled(url.isEmpty());
m_post_url = url;
}
void Window::addNotification(QString title, QString description, QString body)
{
// remove other notifications of the same type
removeNotification(title);
// we want only last notification's action to be triggered
QObject::disconnect(&m_tray_icon, &QSystemTrayIcon::messageClicked, nullptr, nullptr);
if(!body.isEmpty()) {
auto action = menu_notifications.addAction(title);
connect(action, &QAction::triggered, this, [this,title,body]() {
QMessageBox mb(QMessageBox::Information, title, body, QMessageBox::Ok, this);
mb.setTextInteractionFlags(Qt::TextBrowserInteraction);
mb.exec();
removeNotification(title);
});
connect(&m_tray_icon, &QSystemTrayIcon::messageClicked, action, &QAction::trigger);
menu_notifications.addAction(action);
++m_notification_count;
}
showNotificationsMenu();
m_tray_icon.setVisible(true);
m_tray_icon.showMessage(title, description);
}
void Window::removeNotification(QString title) {
const auto actions = menu_notifications.actions();
for(const auto a : qAsConst(actions)) {
if(a && a->text() == title) {
menu_notifications.removeAction(a);
if(m_notification_count > 0) --m_notification_count;
}
}
if(m_notification_count <= 0) {
hideNotificationsMenu();
}
m_tray_icon.setVisible(!isVisible());
}
void Window::showShortNotificationMenu(QString title)
{
menu_short_notification.setTitle(title);
m_short_notification_display_timer.setSingleShot(true);
m_short_notification_display_timer.start(8000);
}
void Window::showNotificationsMenu()
{
if(m_notification_count > 0) {
m_notification_display_timer.start(1000);
}
}
void Window::hideNotificationsMenu()
{
m_notification_display_timer.stop();
menu_notifications.setTitle(QStringLiteral(""));
}
void Window::showUploadProgress(qint64 bytesSent, qint64 bytesTotal)
{
int percent_done = static_cast<int>(util::size::percent(bytesSent, bytesTotal));
#ifdef Q_OS_WIN32
auto progress = m_win_taskbar_button.progress();
progress->setVisible(true);
progress->setMaximum(100);
progress->setValue(percent_done);
if(bytesSent == bytesTotal) {
// set indicator to indeterminate mode
progress->setMaximum(0);
progress->setValue(0);
}
#endif
if(bytesTotal == 0)
return;
updateWindowTitleProgress(percent_done);
statusBar()->showMessage(
tr("Uploading %1 to iqdb.org... %2% complete").arg(
m_tagger.currentFileName(), QString::number(percent_done)));
}
void Window::showTagFetchProgress(QString url_str)
{
#ifdef Q_OS_WIN32
auto progress = m_win_taskbar_button.progress();
progress->setVisible(true);
progress->setMaximum(0);
progress->setValue(0);
#endif
auto url = QUrl(url_str);
statusBar()->showMessage(tr("Fetching tags from %1...").arg(url.host()));
}
void Window::showFileHashingProgress(QString file, int value)
{
Q_UNUSED(file);
#ifdef Q_OS_WIN32
auto progress = m_win_taskbar_button.progress();
progress->setVisible(true);
progress->setMaximum(100);
progress->setValue(value);
#endif
updateWindowTitleProgress(value);
statusBar()->showMessage(tr("Calculating file hash... %1% complete").arg(value));
}
void Window::showCommandExecutionProgress(QString command_name)
{
#ifdef Q_OS_WIN32
auto progress = m_win_taskbar_button.progress();
progress->setVisible(true);
progress->setMaximum(0);
progress->setValue(0);
#endif
statusBar()->showMessage(tr("Running %1...").arg(command_name));
}
void Window::hideUploadProgress()
{
#ifdef Q_OS_WIN32
m_win_taskbar_button.progress()->setVisible(false);
#endif
updateWindowTitle();
statusBar()->showMessage(tr("Done."), 3000);
}
void Window::alert()
{
auto window = windowHandle();
Q_ASSERT(window != nullptr);
window->alert(2500);
}
//------------------------------------------------------------------------------
bool Window::eventFilter(QObject*, QEvent *e)
{
if(e->type() == QEvent::DragEnter) {
auto drag_event = static_cast<QDragEnterEvent*>(e);
if(!drag_event->mimeData()->hasUrls())
return true;
const auto urls = drag_event->mimeData()->urls();
if(urls.empty())
return true;
if(urls.size() == 1) {
QFileInfo dropfile(urls.first().toLocalFile());
if(!(dropfile.isDir()
|| m_tagger.queue().checkExtension(dropfile)
|| FileQueue::checkSessionFileSuffix(dropfile)))
{
return true;
}
}
drag_event->acceptProposedAction();
return true;
}
if(e->type() == QEvent::Drop) {
bool recursive_enabled = qApp->keyboardModifiers() & Qt::SHIFT;
const auto drop_event = static_cast<QDropEvent*>(e);
const auto fileurls = drop_event->mimeData()->urls();
QFileInfo dropfile;
Q_ASSERT(!fileurls.empty());
if(fileurls.size() == 1) {
dropfile.setFile(fileurls.first().toLocalFile());
m_tagger.open(dropfile.absoluteFilePath(), recursive_enabled);
return true;
}
// NOTE: allow user to choose to rename or cancel.
if(m_tagger.rename() == Tagger::RenameStatus::Cancelled)
return true;
QStringList filelist;
for(const auto& fileurl : qAsConst(fileurls)) {
filelist.push_back(fileurl.toLocalFile());
}
m_tagger.queue().assign(filelist, recursive_enabled);
m_tagger.openFileInQueue();
return true;
}
return false;
}
void Window::closeEvent(QCloseEvent *e)
{
if(m_tagger.fileModified()) {
if(Tagger::canExit(m_tagger.rename())) {
saveSettings();
QMainWindow::closeEvent(e);
return;
}
bool was_hidden = !isVisible();
if (was_hidden) show(); // BUG: ignore() doesn't work if the window is hidden.
e->ignore();
if (was_hidden) hide();
return;
}
saveSettings();
QMainWindow::closeEvent(e);
}
void Window::showEvent(QShowEvent *e)
{
#ifdef Q_OS_WIN32
// NOTE: workaround for taskbar button not working.
m_win_taskbar_button.setWindow(this->windowHandle());
#endif
m_tagger.playMedia();
e->accept();
}
void Window::hideEvent(QHideEvent *e)
{
m_tagger.pauseMedia();
e->accept();
}
void Window::mousePressEvent(QMouseEvent * ev)
{
if (ev->buttons() & Qt::ForwardButton) {
a_next_file.trigger();
ev->accept();
}
if (ev->buttons() & Qt::BackButton) {
a_prev_file.trigger();
ev->accept();
}
QMainWindow::mousePressEvent(ev);
}
void Window::wheelEvent(QWheelEvent *ev)
{
QSettings settings;
bool modifier_not_required = settings.value(SETT_NAVIGATE_BY_WHEEL, false).toBool();
if (modifier_not_required
|| ev->modifiers() & Qt::ControlModifier
|| ev->modifiers() & Qt::ShiftModifier) {
ev->accept();
auto delta = ev->angleDelta().y();
if (delta > 0) {
a_next_file.trigger();
}
if (delta < 0) {
a_prev_file.trigger();
}
}
QMainWindow::wheelEvent(ev);
}
//------------------------------------------------------------------------------
void Window::parseCommandLineArguments()
{
const auto args = qApp->arguments(); // slow
if(args.size() <= 1)
return;
QStringList paths;
bool recursive = false;
for(int i = 1; i < args.size(); ++i) {
const auto& arg = args.at(i);
if(arg.startsWith(QChar('-'))) {
if (arg == QStringLiteral("--restart")) {
readRestartData();
return;
}
if (arg == QStringLiteral("-h") || arg == QStringLiteral("--help")) {
QMessageBox::information(this,
tr("%1 Command Line Usage").arg(TARGET_PRODUCT),
tr("<h4><pre>%1 [-r | --recursive] [-h | --help] [path...]</pre></h4>"
"<table>"
"<tr><td style=\"padding: 5px 10px\"><code>-r, --recursive</code></td><td style=\"padding: 5px 10px\">Open files in subdirectories recursively.</td></tr>"
"<tr><td style=\"padding: 5px 10px\"><code>-h, --help</code></td><td style=\"padding: 5px 10px\">Display this help message.</td></tr>"
"<tr><td style=\"padding: 5px 10px\"><code>path...</code></td><td style=\"padding: 5px 10px\">One or several file/directory paths.<br/>Use \"-\" to read paths from <code>stdin</code>.</td></tr>"
"</table>").arg(TARGET_PRODUCT));
}
if (arg == QStringLiteral("-r") || arg == QStringLiteral("--recursive")) {
recursive = true;
}
continue;
}
paths.append(arg);
}
if (paths.size() == 1) {
m_tagger.open(paths[0], recursive); // may open session file or read list from stdin
return;
}
m_tagger.queue().assign(paths, recursive);
m_tagger.queue().select(0); // must select 0 before sorting to always open first argument
m_tagger.queue().sort();
m_tagger.openFileInQueue(m_tagger.queue().currentIndex()); // sorting changed the index of selected file
}
//------------------------------------------------------------------------------
void Window::initSettings()
{
QSettings settings;
m_last_directory = settings.value(SETT_LAST_DIR).toString();
m_view_mode = settings.value(SETT_VIEW_MODE).value<ViewMode>();
bool show_status = settings.value(SETT_SHOW_STATUS, false).toBool();
bool show_menu = settings.value(SETT_SHOW_MENU, true).toBool();
bool show_input = settings.value(SETT_SHOW_INPUT, true).toBool();
bool nav_wheel = settings.value(SETT_NAVIGATE_BY_WHEEL, false).toBool();
bool fit_screen = settings.value(SETT_FIT_TO_SCREEN, false).toBool();
bool restored_geo = restoreGeometry(settings.value(SETT_WINDOW_GEOMETRY).toByteArray());
bool restored_state = restoreState(settings.value(SETT_WINDOW_STATE).toByteArray());
if(!restored_state || !restored_geo) {
resize(1024,640);
move(100,100);
showNormal();
}
menuBar()->setVisible(show_menu);
m_tagger.setViewMode(m_view_mode);
m_tagger.setInputVisible(show_input);
m_statusbar.setVisible(show_status && m_view_mode != ViewMode::Minimal);
a_view_fullscreen.setChecked(isFullScreen());
a_fit_to_screen.setChecked(fit_screen);
a_view_slideshow.setChecked(isFullScreen() && !show_menu && !show_input && !show_status);
a_view_minimal.setChecked(m_view_mode == ViewMode::Minimal);
a_view_statusbar.setChecked(show_status);
a_view_menu.setChecked(show_menu);
a_view_input.setChecked(show_input);
a_navigate_by_wheel.setChecked(nav_wheel);
a_play_mute.setChecked(settings.value(SETT_PLAY_MUTE, false).toBool());
m_tagger.setMediaMuted(a_play_mute.isChecked());
a_ib_replace.setChecked(settings.value(SETT_REPLACE_TAGS, false).toBool());
a_ib_restore.setChecked(settings.value(SETT_RESTORE_TAGS, true).toBool());
a_tag_forcefirst.setChecked(settings.value(SETT_FORCE_AUTHOR_FIRST, false).toBool());
m_show_current_directory = settings.value(SETT_SHOW_CURRENT_DIR, true).toBool();
auto edit_mode = settings.value(SETT_EDIT_MODE).value<EditMode>();
setEditMode(edit_mode);
m_tagger.setUpscalingEnabled(fit_screen);
updateProxySettings();
}
void Window::saveSettings()
{
// FIXME: hack to prevent saving slideshow state
if (a_view_slideshow.isChecked())
setSlideShow(false);
QSettings settings;
settings.setValue(SETT_WINDOW_GEOMETRY, saveGeometry());
settings.setValue(SETT_WINDOW_STATE, saveState());
// NOTE: remove these after a couple of releases
settings.remove(QStringLiteral("window/size"));
settings.remove(QStringLiteral("window/position"));
settings.remove(QStringLiteral("window/show-fullscreen"));
settings.remove(QStringLiteral("window/maximized"));
}
void Window::updateSettings()
{
QSettings settings;
m_show_current_directory = settings.value(SETT_SHOW_CURRENT_DIR, true).toBool();
setViewMode(m_view_mode);
for(auto action : menu_commands.actions()) {
this->removeAction(action); // NOTE: to prevent hotkey conflicts
}
menu_commands.clear();
menu_context_commands.clear();
createCommands();
updateMenus();
}
void Window::restartProcess(QString current_text)
{
Q_ASSERT(!m_tagger.fileModified());
class DetachedProc : public QProcess {
public:
using QProcess::QProcess;
void detach() {
waitForStarted();
setProcessState(QProcess::NotRunning);
}
};
DetachedProc proc;
QStringList args;
if (!m_tagger.isEmpty()) {
args.append(QStringLiteral("--restart"));
}
proc.start(qApp->applicationFilePath(), args, QIODevice::WriteOnly);
if (!proc.waitForStarted()) {
pwarn << "could not start new process";
// restore modifications
m_tagger.setText(current_text);
return;
}
if (!m_tagger.isEmpty()) {
QByteArray header;
{
QBuffer buffer(&header);
buffer.open(QIODevice::WriteOnly);
QTextStream out(&buffer);
out.setCodec("UTF-8");
// version
out << 1 << '\n';
// current text
out << current_text << '\n';
// queue filter
out << m_tagger.queueFilter() << '\n';
// end of header
out << "--EOH--" << '\n';
out.flush();
buffer.close();
}
auto written = proc.write(header);
if (written < 0 || written != header.size()) {
pwarn << "error writing session header to process stdin";
} else {
// serialize queue and write to stdin of the process
auto data = m_tagger.queue().saveToMemory();
written = proc.write(data);
if (written < 0 || written != data.size()) {
pwarn << "error writing session data to process stdin";
}
}
proc.waitForBytesWritten();
}
proc.closeWriteChannel();
if (proc.state() == QProcess::Running && proc.error() == QProcess::UnknownError) {
bool closed = close();
Q_ASSERT(closed);
proc.detach();
}
}
void Window::readRestartData()
{
QFile in;
in.open(stdin, QIODevice::ReadOnly);
QTextStream stream(&in);
stream.setCodec("UTF-8");
auto version = stream.readLine(10);
if (version != QStringLiteral("1")) {
pwarn << "Unknown input data version:" << version;
return;
}
auto current_text = stream.readLine(10000);
auto queue_filter = stream.readLine(10000);
auto end = stream.readLine(10);
if (end != QStringLiteral("--EOH--")) {
pwarn << "No end of headers found";
return;
}
auto session_data = in.readAll();
m_tagger.openSession(session_data);
m_tagger.setQueueFilter(queue_filter);
m_tagger.setText(current_text);
updateStatusBarText();
}
void Window::scheduleRestart()
{
// remember current tags
auto current_text = m_tagger.text();
// undo tag modification to prevent rename dialog
m_tagger.resetText();
// launch process
restartProcess(current_text);
}
void Window::updateStyle()
{
qApp->setWindowIcon(QIcon(QStringLiteral(":/wisetagger.svg")));
m_tray_icon.setIcon(QPixmap(QStringLiteral(":/wisetagger.svg"))); // BUG: cannot use QIcon on linux, but QPixmap works (might be related to QTBUG-55932)
}
void Window::setViewMode(ViewMode mode)
{
if(mode == ViewMode::Minimal) {
m_statusbar.hide();
} else {
m_statusbar.setVisible(a_view_statusbar.isChecked());
}
m_tagger.setViewMode(mode);
}
void Window::setEditMode(EditMode mode)
{
m_tagger.setEditMode(mode);
auto get_mode_str = [](EditMode mode){
QString current_mode_str;
switch(mode) {
case EditMode::Naming:
current_mode_str = tr("Naming mode");
break;
case EditMode::Tagging:
current_mode_str = tr("Tagging mode");
break;
}
return current_mode_str;
};
auto get_mode_icon = [](EditMode mode){
QIcon res;
switch(mode) {
case EditMode::Naming:
break;
case EditMode::Tagging:
res = QIcon::fromTheme("tag", util::fallbackIcon("tag"));
break;
}
return res;
};
showShortNotificationMenu(get_mode_str(mode));
auto next_mode = GlobalEnums::next_edit_mode(mode);
a_edit_mode.setText(get_mode_str(next_mode));
a_edit_mode.setIcon(get_mode_icon(next_mode));
updateMenus();
}
void Window::setSlideShow(bool slide_show)
{
a_view_input.setEnabled(!slide_show);
a_view_statusbar.setEnabled(!slide_show);
a_view_fullscreen.setEnabled(!slide_show);
a_view_minimal.setEnabled(!slide_show);
a_view_menu.setChecked(!slide_show);
a_view_input.setChecked(!slide_show);
a_view_statusbar.setChecked(!slide_show);
a_view_fullscreen.setChecked(slide_show);
QSettings settings;
m_tagger.setUpscalingEnabled(slide_show || settings.value(SETT_FIT_TO_SCREEN).toBool());
}
#ifdef Q_OS_WIN
namespace logging_category {
Q_LOGGING_CATEGORY(vercheck, "Window.VersionCheck")
}
#define vcwarn qCWarning(logging_category::vercheck)
#define vcdbg qCDebug(logging_category::vercheck)
void Window::checkNewVersion()
{
QSettings settings;
auto last_checked = settings.value(SETT_LAST_VER_CHECK,QDate(2016,1,1)).toDate();
auto checking_disabled = !settings.value(SETT_VER_CHECK_ENABLED, true).toBool();
if(checking_disabled || last_checked == QDate::currentDate()) {
vcdbg << (checking_disabled ? "vercheck disabled" : "vercheck enabled") << last_checked.toString();
return;
}
connect(&m_vernam, &QNetworkAccessManager::finished, this, &Window::processNewVersion);
QNetworkRequest req{VER_CHECK_URL};
req.setHeader(QNetworkRequest::UserAgentHeader, WISETAGGER_USERAGENT);
m_vernam.get(req);
}
void Window::processNewVersion(QNetworkReply *r)
{
// use unique_ptr with custom deleter to clean up the request object
auto guard = std::unique_ptr<QNetworkReply, std::function<void(QNetworkReply*)>>(r, [](auto ptr)
{
ptr->deleteLater();
});
if(r->error() != QNetworkReply::NoError) {
vcwarn << "could not access" << r->url() << "with error:" << r->errorString();
return;
}
auto status_code = r->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if(status_code != 200) {
vcwarn << "wrong HTTP status code:" << status_code;
return;
}
QSettings settings;
settings.setValue(SETT_LAST_VER_CHECK, QDate::currentDate());
QString response = r->readAll();
auto parts = util::split(response);
if(parts.size() < 2) {
vcwarn << "not enough parts";
return;
}
auto newver = QVersionNumber::fromString(parts[0]);
if(newver.isNull()) {
vcwarn << "invalid version";
return;
}