forked from luebking/qarma
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGarma.cpp
2000 lines (1869 loc) · 82.2 KB
/
Garma.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
/*
* Garma - a Zenity clone for Qt4 and Qt5
* Copyright 2014 by Thomas Lübking <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "Garma.h"
#include "define_global.h"
#include <QHeaderView>
#include <iostream>
#include <QAction>
#include <QBoxLayout>
#include <QCalendarWidget>
#include <QCheckBox>
#include <QColorDialog>
#include <QComboBox>
#include <QDate>
#include <QDBusConnection>
#include <QDBusConnectionInterface>
#include <QDBusInterface>
#include <QDialogButtonBox>
#include <QEvent>
#include <DFileDialog>
#include <QFontDialog>
#include <QFormLayout>
#include <QIcon>
#include <QInputDialog>
#include <QLabel>
#include <QLocale>
#include <QLineEdit>
#include <QMessageBox>
#include <QProcess>
#include <QProgressDialog>
#include <QPropertyAnimation>
#include <QPushButton>
#include <QScreen>
#include <QScrollBar>
#include <QSettings>
#include <QSlider>
#include <QSocketNotifier>
#include <QStringBuilder>
#include <QStringList>
#include <QTextBrowser>
#include <QTimer>
#include <QTimerEvent>
#include <QTreeWidget>
#include <QTreeWidgetItem>
#include <dmainwindow.h>
#include <ddialog.h>
#include <DApplication>
#include <dinputdialog.h>
#include "inputguard.h"
#include "gmessagebox.h"
#include "gprogressdialog.h"
#include "dfiledialog.h"
#include "dimagebutton.h"
#include "dialogmanager.h"
#if QT_VERSION >= 0x050000
// this is to hack access to the --title parameter in Qt5
#include <QWindow>
#endif
#include <QtDebug>
#include <cfloat>
#ifdef Q_OS_UNIX
#include <signal.h>
#include <unistd.h>
#endif
InputGuard *InputGuard::s_instance = NULL;
#ifdef WS_X11
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
#include <QGuiApplication>
#else
#include <QX11Info>
#endif
#include <X11/Xlib.h>
#endif
typedef QPair<QString, QString> Help;
typedef QList<Help> HelpList;
typedef QPair<QString, HelpList> CategoryHelp;
typedef QMap<QString, CategoryHelp> HelpDict;
Garma::Garma(int &argc, char **argv) : DApplication(argc, argv)
, m_modal(false)
, m_selectableLabel(false)
, m_popup(false)
, m_parentWindow(0)
, m_timeout(0)
, m_notificationId(0)
, m_dialog(NULL)
, m_type(Invalid)
{
// 加载翻译
this->loadTranslator();
m_pos = QPoint(INT_MAX, INT_MAX); // invalid
QStringList argList = QCoreApplication::arguments(); // arguments() is slow
const QString binary = argList.at(0);
m_zenity = binary.endsWith("zenity");
// make canonical list
QStringList args;
if (argList.at(0).endsWith("-askpass")) {
argList.removeFirst();
args << "--title" << tr("Enter Password") << "--password" << "--prompt" << argList.join(' ');
} else {
for (int i = 1; i < argList.count(); ++i) {
if (argList.at(i).startsWith("--")) {
int split = argList.at(i).indexOf('=');
if (split > -1) {
args << argList.at(i).left(split) << argList.at(i).mid(split+1);
} else {
args << argList.at(i);
}
} else {
args << argList.at(i);
}
}
}
argList.clear();
if (!readGeneral(args))
return;
// set application class
if (!m_class.isNull())
QCoreApplication::setApplicationName(m_class);
// set application name
if (!m_name.isNull())
// Qt intercepts "--name name" but fails to process "--name=name"
// Workaround this by setting the RESOURCE_NAME environment variable
// which ends up being used to populate the WM_CLASS name on X11.
qputenv("RESOURCE_NAME", m_name.toLocal8Bit());
// 创建一个不显示的 DMainWindow 以便能正常显示对话框
DMainWindow *window = new DMainWindow();
window->hide();
char error = 1;
foreach (const QString &arg, args) {
if (arg == "--calendar") {
m_type = Calendar;
error = showCalendar(args);
} else if (arg == "--entry") {
m_type = Entry;
error = showEntry(args);
} else if (arg == "--error") {
m_type = Error;
error = showMessage(args, 'e');
} else if (arg == "--info") {
m_type = Info;
error = showMessage(args, 'i');
} else if (arg == "--file-selection") {
m_type = FileSelection;
error = showFileSelection(args);
} else if (arg == "--list") {
m_type = List;
error = showList(args);
} else if (arg == "--notification") {
m_type = Notification;
error = showNotification(args);
} else if (arg == "--progress") {
m_type = Progress;
error = showProgress(args);
} else if (arg == "--question") {
m_type = Question;
error = showMessage(args, 'q');
} else if (arg == "--warning") {
m_type = Warning;
error = showMessage(args, 'w');
} else if (arg == "--scale") {
m_type = Scale;
error = showScale(args);
} else if (arg == "--text-info") {
m_type = TextInfo;
error = showText(args);
} else if (arg == "--color-selection") {
m_type = ColorSelection;
error = showColorSelection(args);
} else if (arg == "--font-selection") {
m_type = FontSelection;
error = showFontSelection(args);
} else if (arg == "--password") {
m_type = Password;
error = showPassword(args);
} else if (arg == "--forms") {
m_type = Forms;
error = showForms(args);
} else if (arg == "--dzen") {
m_type = Dzen;
error = showDzen(args);
} else if (arg == "--about") {
m_type = About;
error = showAbout(args);
}
if (error != 1) {
break;
}
}
if (error) {
QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection);
return;
}
if (m_dialog) {
#if QT_VERSION >= 0x050000
/* Stage #1 one of "Setting a window title should be easy but Qt5 is dumb"
Qt5 sucks away "--title foo" but not "--title=foo" and then stumbles
over itself when trying to set it
So #1 we seek to get ourselfs access to the window title to get some
control over it
since it's set on showing the first QWindow, we just create one here
and copy the title
*/
/// @todo: remove once this is fixed in Qt5 - ie. "never"
const bool qt5title = m_caption.isNull(); // otherwise we read it in the general options
if (qt5title) {
QWindow *w = new QWindow;
w->setVisible(true);
m_caption = w->title();
delete w;
m_dialog->setWindowTitle("");
}
m_dialog->setWindowTitle(m_caption);
// so much for stage one, see below for more on Qt5 being dumb...
#endif
// close on ctrl+return in addition to ctrl+enter
QAction *shortAccept = new QAction(m_dialog);
m_dialog->addAction(shortAccept);
QList<QKeySequence> cuts;
cuts << QKeySequence(Qt::CTRL|Qt::Key_Return) << QKeySequence(Qt::CTRL|Qt::Key_Enter);
shortAccept->setShortcuts(cuts);
connect (shortAccept, SIGNAL(triggered()), m_dialog, SLOT(accept()));
// workaround for #21 - since QWidget is now merely bitrot, QDialog closes,
// but does not reject on the escape key (unlike announced in the specific section of the API)
QAction *shortReject = new QAction(m_dialog);
m_dialog->addAction(shortReject);
shortReject->setShortcut(QKeySequence(Qt::Key_Escape));
connect (shortReject, SIGNAL(triggered()), m_dialog, SLOT(reject()));
if (!m_size.isNull()) {
m_dialog->adjustSize();
//DDialog *dl = static_cast<DDialog*>(m_dialog);
QSize sz = m_dialog->size();
if (m_size.width() > 0)
sz.setWidth(m_size.width());
if (m_size.height() > 0)
sz.setHeight(m_size.height());
m_dialog->resize(sz);
}
if (m_pos.x() < INT_MAX) {
QRect desktop = QGuiApplication::screens().at(0)->availableGeometry();
if (m_pos.x() < 0)
m_pos.rx() = desktop.right() + m_pos.x() - m_dialog->width();
if (m_pos.y() < 0)
m_pos.ry() = desktop.bottom() + m_pos.y() - m_dialog->height();
m_dialog->move(m_pos);
}
m_dialog->setWindowModality(m_modal ? Qt::ApplicationModal : Qt::NonModal);
/* Stage #2 one of "Setting a window title should be easy but Qt5 is dumb"
Errhemmm... Fuck! This! Shit!
Not only is Qt5 too dumb to set the window title by parameter, if one
does it, at least on X11 Qt5 doesn't set the property on the platform
window *before* mapping it, but *while* - causing an IPC race condition
with the WMs that will pick up the "old" title, but also miss the property
update because it can happen while they're configuring the window.
Awesome.
Because we can't retroactively preceed the mapping, we at least need to
make sure that the title gets updated after the window is mapped and
configured - what we can only guess witha timer... *grrrrr*
Since setting the same title is idempotent and skipped in ::setWindowTitle
(what would be great if the entire thing wasn't broken to begin with)
We need two steps to first clear and second reset the title - maximzing
the server roundtrips...
But hey, abstract and wayland and QML... FUCK! THIS! SHIT! *grrrrrrrr*
*/
// We do this after the dialog creation, because the setup can take varying times
if (!(m_caption.isNull() || binary.endsWith(m_caption)))
QTimer::singleShot(10, this, [=]() {m_dialog->setWindowTitle(""); m_dialog->setWindowTitle(m_caption);});
// so much for setting the window title - despite Qt trying to do it by itself
if (!m_icon.isNull())
m_dialog->setWindowIcon(QIcon(m_icon));
QDialogButtonBox *box = m_dialog->findChild<QDialogButtonBox*>();
if (box && !m_ok.isNull()) {
if (QPushButton *btn = box->button(QDialogButtonBox::Ok))
btn->setText(m_ok);
}
if (box && !m_cancel.isNull()) {
if (QPushButton *btn = box->button(QDialogButtonBox::Cancel))
btn->setText(m_cancel);
}
if (m_parentWindow) {
#ifdef WS_X11
m_dialog->setAttribute(Qt::WA_X11BypassTransientForHint);
Display *dpy;
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
dpy = QGuiApplication::nativeInterface<QNativeInterface::QX11Application>()->display();
#else
dpy = QX11Info::display();
#endif
XSetTransientForHint(dpy, m_dialog->winId(), m_parentWindow);
#endif
}
}
}
bool Garma::error(const QString message)
{
printf("Error: %s", qPrintable(message));
QMetaObject::invokeMethod(this, "quitOnError", Qt::QueuedConnection);
return true;
}
static QString value(const QWidget *w, const QString &pattern)
{
if (!w)
return QString();
IF_IS(QLineEdit) {
return t->text();
} else IF_IS(QTreeWidget) {
QString s;
foreach (QTreeWidgetItem *item, t->selectedItems()) {
for (int i = 0; i < t->columnCount(); ++i)
s += item->text(i);
}
return s;
} else IF_IS(QComboBox) {
return t->currentText();
} else IF_IS(QCalendarWidget) {
if (pattern.isNull())
return QLocale::system().toString(t->selectedDate(), QLocale::ShortFormat);
return t->selectedDate().toString(pattern);
} else IF_IS(QCheckBox) {
return t->isChecked() ? "true" : "false";
}
return QString();
}
void Garma::dialogFinished(int status)
{
if (m_type == FileSelection) {
DFileDialog *dlg = static_cast<DFileDialog*>(sender());
QVariantList l;
for (int i = 0; i < dlg->sidebarUrls().count(); ++i)
l << dlg->sidebarUrls().at(i);
QSettings settings("Garma");
settings.setValue("Bookmarks", l);
settings.setValue("FileDetails", dlg->viewMode() == DFileDialog::Detail);
}
if (!(status == QDialog::Accepted || status == GMessageBox::Ok || status == GMessageBox::Yes)) {
#ifdef Q_OS_UNIX
if (sender()->property("Garma_autokill_parent").toBool()) {
::kill(getppid(), 9); // 使用 9 可以强制关闭进程
// 等效于 kill -9 xxx
}
#endif
exit(1);
return;
}
switch (m_type) {
case Question:
case Warning:
case Info:
case Error:
case Progress:
case Notification:
break;
case Calendar: {
QString format = sender()->property("Garma_date_format").toString();
QDate date = sender()->findChild<QCalendarWidget*>()->selectedDate();
if (format.isEmpty())
printf("%s\n", qPrintable(QLocale::system().toString(date, QLocale::ShortFormat)));
else
printf("%s\n", qPrintable(date.toString(format)));
break;
}
case Entry: {
DInputDialog *dlg = static_cast<DInputDialog*>(sender());
if (dlg->inputMode() == DInputDialog::DoubleInput) {
printf("%s\n", qPrintable(QLocale::c().toString(dlg->doubleValue(), 'f', 2)));
} else if (dlg->inputMode() == DInputDialog::IntInput) {
printf("%d\n", dlg->intValue());
} else {
printf("%s\n", qPrintable(dlg->textValue()));
}
break;
}
case Password: {
QLineEdit *username = sender()->findChild<QLineEdit*>("Garma_username"),
*password = sender()->findChild<QLineEdit*>("Garma_password");
QString result;
if (username)
result = username->text() + '|';
if (password)
result += password->text();
printf("%s\n", qPrintable(result));
break;
}
case FileSelection: {
QStringList files = static_cast<DFileDialog*>(sender())->selectedFiles();
printf("%s\n", qPrintable(files.join(sender()->property("Garma_separator").toString())));
break;
}
case ColorSelection: {
QColorDialog *dlg = static_cast<QColorDialog*>(sender());
printf("%s\n", qPrintable(dlg->selectedColor().name()));
QVariantList l;
for (int i = 0; i < dlg->customCount(); ++i)
l << dlg->customColor(i).rgba();
QSettings("Garma").setValue("CustomPalette", l);
break;
}
case FontSelection: {
QFontDialog *dlg = static_cast<QFontDialog*>(sender());
QFont fnt = dlg->selectedFont();
int size = fnt.pointSize();
if (size < 0)
size = fnt.pixelSize();
// crude mapping of Qt's random enum to xft's random category
QString weight = "medium";
if (fnt.weight() < 35) weight = "light";
else if (fnt.weight() > 85) weight = "black";
else if (fnt.weight() > 70) weight = "bold";
else if (fnt.weight() > 60) weight = "demibold";
QString slant = "roman";
if (fnt.style() == QFont::StyleItalic) slant = "italic";
else if (fnt.style() == QFont::StyleOblique) slant = "oblique";
QString font = sender()->property("Garma_fontpattern").toString();
font = font.arg(fnt.family()).arg(size).arg(weight).arg(slant);
printf("%s\n", qPrintable(font));
break;
}
case TextInfo: {
QTextEdit *te = sender()->findChild<QTextEdit*>();
if (te && !te->isReadOnly()) {
printf("%s\n", qPrintable(te->toPlainText()));
}
break;
}
case Scale: {
QSlider *sld = sender()->findChild<QSlider*>();
if (sld) {
printf("%s\n", qPrintable(QString::number(sld->value())));
}
break;
}
case List: {
QTreeWidget *tw = sender()->findChild<QTreeWidget*>();
QStringList result;
if (tw && m_listPrintColumn == -1) {
bool done(false);
if (m_listCheckable) {
for (int i = 0; i < tw->topLevelItemCount(); ++i) {
const QTreeWidgetItem *twi = tw->topLevelItem(i);
if (twi->checkState(0) == Qt::Checked)
result << twi->text(1);
}
}
else {
foreach (const QTreeWidgetItem *twi, tw->selectedItems()) {
result << twi->text(0);
}
}
}
else if (tw && m_listPrintColumn >= 0) {
if (m_listCheckable) {
for (int i = 0; i < tw->topLevelItemCount(); ++i) {
const QTreeWidgetItem *twi = tw->topLevelItem(i);
if (twi->checkState(0) == Qt::Checked) {
// 添加空格以便正常识别
std::cout << qPrintable(twi->text(m_listPrintColumn)) << " ";
}
}
}
else {
for (auto i: tw->selectedItems()) {
std::cout << qPrintable(i->text(m_listPrintColumn)) << " ";
}
}
std::cout << std::endl;
}
if (m_listPrintColumn == -1) {
printf("%s\n", qPrintable(result.join(sender()->property("Garma_separator").toString())));
}
break;
}
case Forms: {
QFormLayout *fl = sender()->findChild<QFormLayout*>();
QStringList result;
QString format = sender()->property("Garma_date_format").toString();
for (int i = 0; i < fl->count(); ++i) {
if (QLayoutItem *li = fl->itemAt(i, QFormLayout::FieldRole))
result << value(li->widget(), format);
}
printf("%s\n", qPrintable(result.join(sender()->property("Garma_separator").toString())));
break;
}
default:
qDebug() << "unhandled output" << m_type;
break;
}
exit (0);
}
void Garma::quitOnError()
{
exit(1);
}
bool Garma::readGeneral(QStringList &args) {
QStringList remains;
for (int i = 0; i < args.count(); ++i) {
if (args.at(i) == "--title") {
m_caption = NEXT_ARG;
} else if (args.at(i) == "--window-icon") {
m_icon = NEXT_ARG;
} else if (args.at(i) == "--width") {
READ_INT(w, UInt, "--width must be followed by a positive number");
m_size.setWidth(w);
} else if (args.at(i) == "--height") {
READ_INT(h, UInt, "--height must be followed by a positive number");
m_size.setHeight(h);
} else if (args.at(i) == "--pos") {
QString pos = NEXT_ARG;
QRegularExpressionMatch m = QRegularExpression("([+-]*[0-9]+)([+-][0-9]+)?").match(pos);
if (m.lastCapturedIndex() > 0 && m.lastCapturedIndex() < 3) {
m_pos.setX(m.captured(1).toInt());
m_pos.setY(m.lastCapturedIndex() == 2 ? m.captured(2).toInt() : 0);
} else {
return !error("--pos must be followed by a position [+-]x[(+-)y]");
}
} else if (args.at(i) == "--timeout") {
READ_INT(t, UInt, "--timeout must be followed by a positive number");
QTimer::singleShot(t*1000, this, SLOT(quit()));
} else if (args.at(i) == "--ok-label") {
m_ok = NEXT_ARG;
} else if (args.at(i) == "--cancel-label") {
m_cancel = NEXT_ARG;
} else if (args.at(i) == "--modal") {
m_modal = true;
} else if (args.at(i) == "--popup") {
m_popup = true;
} else if (args.at(i) == "--attach") {
READ_INT(w, UInt, "--attach must be followed by a positive number");
m_parentWindow = w;
} else if (args.at(i) == "--class") {
m_class = NEXT_ARG;
} else if (args.at(i) == "--name") {
m_name = NEXT_ARG;
} else {
remains << args.at(i);
}
}
args = remains;
return true;
}
char Garma::showCalendar(const QStringList &args)
{
NEW_DIALOG
QDate date = QDate::currentDate();
int d,m,y;
date.getDate(&y, &m, &d);
bool ok;
for (int i = 0; i < args.count(); ++i) {
if (args.at(i) == "--text") {
vl->addWidget(new QLabel(NEXT_ARG, dlg));
} else if (args.at(i) == "--day") {
d = NEXT_ARG.toUInt(&ok);
if (!ok)
return !error("--day must be followed by a positive number");
} else if (args.at(i) == "--month") {
m = NEXT_ARG.toUInt(&ok);
if (!ok)
return !error("--month must be followed by a positive number");
} else if (args.at(i) == "--year") {
y = NEXT_ARG.toUInt(&ok);
if (!ok)
return !error("--year must be followed by a positive number");
} else if (args.at(i) == "--date-format") {
dlg->setProperty("Garma_date_format", NEXT_ARG);
} else { WARN_UNKNOWN_ARG("--calendar") }
}
date.setDate(y, m, d);
QCalendarWidget *cal = new QCalendarWidget(dlg);
cal->setSelectedDate(date);
vl->addWidget(cal);
connect(cal, SIGNAL(activated(const QDate&)), dlg, SLOT(accept()));
if (!m_popup) {
FINISH_OK_CANCEL_DIALOG
}
SHOW_DIALOG
return 0;
}
char Garma::showEntry(const QStringList &args)
{
DInputDialog *dlg = new DInputDialog;
for (int i = 0; i < args.count(); ++i) {
if (args.at(i) == "--text")
qDebug() << "a";
//dlg->setLabelText(labelText(NEXT_ARG));
else if (args.at(i) == "--entry-text")
dlg->setTextValue(NEXT_ARG);
else if (args.at(i) == "--hide-text")
dlg->setTextEchoMode(QLineEdit::Password);
else if (args.at(i) == "--values") {
dlg->setComboBoxItems(NEXT_ARG.split('|'));
dlg->setComboBoxEditable(true);
} else if (args.at(i) == "--int") {
dlg->setInputMode(DInputDialog::IntInput);
dlg->setIntRange(INT_MIN, INT_MAX);
dlg->setIntValue(NEXT_ARG.toInt());
} else if (args.at(i) == "--float") {
dlg->setInputMode(DInputDialog::DoubleInput);
dlg->setDoubleRange(DBL_MIN, DBL_MAX);
dlg->setDoubleValue(NEXT_ARG.toDouble());
}
else { WARN_UNKNOWN_ARG("--entry") }
}
SHOW_DIALOG
return 0;
}
char Garma::showPassword(const QStringList &args)
{
NEW_DIALOG
QLineEdit *username(NULL), *password(NULL);
QString prompt = tr("Enter password");
for (int i = 0; i < args.count(); ++i) {
if (args.at(i) == "--username") {
vl->addWidget(new QLabel(tr("Enter username"), dlg));
vl->addWidget(username = new QLineEdit(dlg));
username->setObjectName("Garma_username");
break;
} else if (args.at(i) == "--prompt") {
prompt = NEXT_ARG;
} { WARN_UNKNOWN_ARG("--password") }
}
vl->addWidget(new QLabel(prompt, dlg));
vl->addWidget(password = new QLineEdit(dlg));
password->setObjectName("Garma_password");
password->setEchoMode(QLineEdit::Password);
InputGuard::watch(password);
if (username)
username->setFocus(Qt::OtherFocusReason);
else
password->setFocus(Qt::OtherFocusReason);
FINISH_OK_CANCEL_DIALOG
SHOW_DIALOG
return 0;
}
char Garma::showMessage(const QStringList &args, char type)
{
GMessageBox *dlg = new GMessageBox;
//dlg->setStandardButtons((type == 'q') ? GMessageBox::Yes|GMessageBox::No : GMessageBox::Ok);
QList<GMessageBox::StandardButtons> button;
if (type == 'q') {
button << GMessageBox::No << GMessageBox::Yes;
}
else {
button << GMessageBox::Ok;
}
dlg->setStandardButtonsWithList(button);
// 设置默认文本
dlg->setText(type == 'w' ? tr("Are you sure you want to proceed?") :
(type == 'q' ? tr("Are you sure you want to proceed?") :
(type == 'e' ? tr("An error has occurred.") : tr("All updates are complete."))));
bool wrap = true, html = true;
for (int i = 0; i < args.count(); ++i) {
if (args.at(i) == "--text")
dlg->setText(html ? labelText(NEXT_ARG) : NEXT_ARG);
else if (args.at(i) == "--icon-name")
dlg->setIconPixmap(QIcon(NEXT_ARG).pixmap(64));
else if (args.at(i) == "--no-wrap")
wrap = false;
else if (args.at(i) == "--ellipsize")
wrap = true;
else if (args.at(i) == "--no-markup")
html = false;
else if (args.at(i) == "--default-cancel")
qDebug() << "a";
//dlg->setDefaultButton(GMessageBox::Cancel);
else if (args.at(i) == "--selectable-labels")
m_selectableLabel = true;
else if (args.at(i).startsWith("--") && args.at(i) != "--info" && args.at(i) != "--question" &&
args.at(i) != "--warning" && args.at(i) != "--error")
qDebug() << "unspecific argument" << args.at(i);
}
if (QLabel *l = dlg->findChild<QLabel*>("qt_msgbox_label")) {
l->setWordWrap(wrap);
l->setTextFormat(html ? Qt::RichText : Qt::PlainText);
if (m_selectableLabel)
l->setTextInteractionFlags(l->textInteractionFlags()|Qt::TextSelectableByMouse);
}
dlg->setIcon(type == 'w' ? GMessageBox::Warning :
(type == 'q' ? GMessageBox::Question :
(type == 'e' ? GMessageBox::Critical : GMessageBox::Information)));
SHOW_DIALOG
return 0;
}
char Garma::showFileSelection(const QStringList &args)
{
DFileDialog *dlg = new DFileDialog;
QSettings settings("Garma");
dlg->setViewMode(settings.value("FileDetails", false).toBool() ? DFileDialog::Detail : DFileDialog::List);
dlg->setFileMode(DFileDialog::ExistingFile);
dlg->setOption(DFileDialog::DontConfirmOverwrite, false);
dlg->setProperty("Garma_separator", "|");
QVariantList l = settings.value("Bookmarks").toList();
QList<QUrl> bookmarks;
for (int i = 0; i < l.count(); ++i)
bookmarks << l.at(i).toUrl();
if (!bookmarks.isEmpty())
dlg->setSidebarUrls(bookmarks);
QStringList mimeFilters;
for (int i = 0; i < args.count(); ++i) {
if (args.at(i) == "--filename") {
QString path = NEXT_ARG;
if (path.endsWith("/."))
dlg->setDirectory(path);
else
dlg->selectFile(path);
}
else if (args.at(i) == "--multiple")
dlg->setFileMode(DFileDialog::ExistingFiles);
else if (args.at(i) == "--directory") {
dlg->setFileMode(DFileDialog::Directory);
dlg->setOption(DFileDialog::ShowDirsOnly);
} else if (args.at(i) == "--save") {
dlg->setFileMode(DFileDialog::AnyFile);
dlg->setAcceptMode(DFileDialog::AcceptSave);
}
else if (args.at(i) == "--separator")
dlg->setProperty("Garma_separator", NEXT_ARG);
else if (args.at(i) == "--confirm-overwrite")
dlg->setOption(DFileDialog::DontConfirmOverwrite);
else if (args.at(i) == "--file-filter") {
QString mimeFilter = NEXT_ARG;
const int idx = mimeFilter.indexOf('|');
if (idx > -1)
mimeFilter = mimeFilter.left(idx).trimmed() + " (" + mimeFilter.mid(idx+1).trimmed() + ")";
mimeFilters << mimeFilter;
}
else { WARN_UNKNOWN_ARG("--file-selection") }
}
dlg->setNameFilters(mimeFilters);
SHOW_DIALOG
return 0;
}
void Garma::toggleItems(QTreeWidgetItem *item, int column)
{
if (column)
return; // not the checkmark
static bool recursion = false;
if (recursion)
return;
recursion = true;
QTreeWidget *tw = item->treeWidget();
for (int i = 0; i < tw->topLevelItemCount(); ++i) {
QTreeWidgetItem *twi = tw->topLevelItem(i);
if (twi != item)
twi->setCheckState(0, Qt::Unchecked);
}
recursion = false;
}
static void addItems(QTreeWidget *tw, QStringList &values, bool editable, bool checkable, bool icons)
{
for (int i = 0; i < values.count(); ) {
QStringList itemValues;
for (int j = 0; j < tw->columnCount(); ++j) {
itemValues << values.at(i++);
if (i == values.count())
break;
}
QTreeWidgetItem *item = new QTreeWidgetItem(tw, itemValues);
Qt::ItemFlags flags = item->flags();
if (editable)
flags |= Qt::ItemIsEditable;
if (checkable) {
flags |= Qt::ItemIsUserCheckable;
// 如果每一项的第一个参数为 true,则代表默认勾选
// 反之 false 则默认不勾选
// 该参数不区分大小写
Qt::CheckState checkState = Qt::Unchecked;
if (itemValues.first().toLower() == "true") {
checkState = Qt::Checked;
}
item->setCheckState(0, checkState);
}
if (icons)
item->setIcon(0, QPixmap(item->text(0)));
if (checkable || icons) {
item->setData(0, Qt::EditRole, item->text(0));
item->setText(0, QString());
}
item->setFlags(flags);
tw->addTopLevelItem(item);
}
}
char Garma::showList(const QStringList &args)
{
NEW_DIALOG
QLabel *lbl;
vl->addWidget(lbl = new QLabel(dlg));
QTreeWidget *tw;
vl->addWidget(tw = new QTreeWidget(dlg));
tw->setSelectionBehavior(QAbstractItemView::SelectRows);
tw->setSelectionMode(QAbstractItemView::SingleSelection);
tw->setRootIsDecorated(false);
tw->setAllColumnsShowFocus(true);
// 自动根据内容自适应宽度
tw->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
bool editable(false), checkable(false), exclusive(false), icons(false), ok, needFilter(true);
QStringList columns;
QStringList values;
QList<int> hiddenCols;
dlg->setProperty("Garma_separator", "|");
for (int i = 0; i < args.count(); ++i) {
if (args.at(i) == "--text")
lbl->setText(labelText(NEXT_ARG));
else if (args.at(i) == "--multiple")
tw->setSelectionMode(QAbstractItemView::ExtendedSelection);
else if (args.at(i) == "--column") {
columns << NEXT_ARG;
} else if (args.at(i) == "--editable")
editable = true;
else if (args.at(i) == "--hide-header")
tw->setHeaderHidden(true);
else if (args.at(i) == "--separator")
dlg->setProperty("Garma_separator", NEXT_ARG);
else if (args.at(i) == "--hide-column") {
int v = NEXT_ARG.toInt(&ok);
if (ok)
hiddenCols << v-1;
} else if (args.at(i) == "--print-column") {
m_listPrintColumn = NEXT_ARG.toInt() - 1;
} else if (args.at(i) == "--checklist") {
tw->setSelectionMode(QAbstractItemView::NoSelection);
tw->setAllColumnsShowFocus(false);
checkable = true;
} else if (args.at(i) == "--radiolist") {
tw->setSelectionMode(QAbstractItemView::NoSelection);
tw->setAllColumnsShowFocus(false);
checkable = true;
exclusive = true;
} else if (args.at(i) == "--imagelist") {
icons = true;
} else if (args.at(i) == "--mid-search") {
if (needFilter) {
needFilter = false;
QLineEdit *filter;
vl->addWidget(filter = new QLineEdit(dlg));
filter->setPlaceholderText(tr("Filter"));
connect (filter, &QLineEdit::textChanged, this, [=](const QString &match){
for (int i = 0; i < tw->topLevelItemCount(); ++i)
tw->topLevelItem(i)->setHidden(!tw->topLevelItem(i)->text(0).contains(match, Qt::CaseInsensitive));
});
}
} else if (args.at(i) != "--list") {
values << args.at(i);
}
}
if (values.isEmpty())
listenToStdIn();
if (checkable)
editable = false;
m_listCheckable = checkable;
// 在非勾选框模式下,允许双击确认
if (!checkable) {
connect(tw, &QTreeWidget::doubleClicked, [dlg](){dlg->done(QDialog::Accepted);});
}
tw->setProperty("Garma_list_flags", int(editable | checkable << 1 | icons << 2));
int columnCount = qMax(columns.count(), 1);
tw->setColumnCount(columnCount);
tw->setHeaderLabels(columns);
foreach (const int &i, hiddenCols)
tw->setColumnHidden(i, true);
addItems(tw, values, editable, checkable, icons);
if (exclusive) {
connect (tw, SIGNAL(itemChanged(QTreeWidgetItem*, int)), SLOT(toggleItems(QTreeWidgetItem*, int)));
}
for (int i = 0; i < columns.count(); ++i)
tw->resizeColumnToContents(i);
if (!m_size.isNull()) {
QSize sz = tw->size();
if (m_size.width() > 0)
sz.setWidth(m_size.width());
if (m_size.height() > 0)
sz.setHeight(m_size.height());
tw->setFixedSize(m_size.width(), m_size.height());
}
FINISH_OK_CANCEL_DIALOG
SHOW_DIALOG
return 0;
}
void Garma::notify(const QString message, bool noClose)
{
if (QDBusConnection::sessionBus().interface()->isServiceRegistered("org.freedesktop.Notifications")) {
QDBusInterface notifications("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications");
const QString summary = (message.length() < 32) ? message : message.left(25) + "...";
QVariantMap hintMap;
QStringList hintList = m_notificationHints.split(':');
for (int i = 0; i < hintList.count() - 1; i+=2)
hintMap.insert(hintList.at(i), hintList.at(i+1));
QDBusMessage msg = notifications.call("Notify", "Garma", m_notificationId, "dialog-information", summary, message,
QStringList() /*actions*/, hintMap, m_timeout);
if (msg.arguments().count())
m_notificationId = msg.arguments().at(0).toUInt();
return;
}
GMessageBox *dlg = static_cast<GMessageBox*>(m_dialog);
if (!dlg) {
dlg = new GMessageBox;
/*dlg->setIcon(GMessageBox::Information);
dlg->setStandardButtons(noClose ? GMessageBox::NoButton : GMessageBox::Ok);*/
dlg->setWindowFlags(Qt::ToolTip);
dlg->setWindowOpacity(0.8);
if (QLabel *l = dlg->findChild<QLabel*>("qt_msgbox_label")) {
l->setWordWrap(true);
if (m_selectableLabel)
l->setTextInteractionFlags(l->textInteractionFlags()|Qt::TextSelectableByMouse);
}
}
dlg->setText(labelText(message));
SHOW_DIALOG
dlg->adjustSize();
dlg->move(QGuiApplication::screens().at(0)->availableGeometry().topRight() - QPoint(dlg->width() + 20, -20));
}
char Garma::showNotification(const QStringList &args)
{
QString message;
bool listening(false);
for (int i = 0; i < args.count(); ++i) {
if (args.at(i) == "--text") {
message = NEXT_ARG;
} else if (args.at(i) == "--listen") {
listening = true;
listenToStdIn();