forked from luebking/qarma
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Qarma.cpp
1486 lines (1379 loc) · 58.6 KB
/
Qarma.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
/*
* Qarma - a Zenity clone for Qt4 and Qt5
* Copyright 2014 by Thomas Lübking <thomas.luebking@gmail.com>
*
* 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 "Qarma.h"
#include <QAction>
#include <QBoxLayout>
#include <QCalendarWidget>
#include <QCheckBox>
#include <QColorDialog>
#include <QComboBox>
#include <QDate>
#include <QDBusConnection>
#include <QDBusConnectionInterface>
#include <QDBusInterface>
#include <QDesktopWidget>
#include <QDialogButtonBox>
#include <QEvent>
#include <QFileDialog>
#include <QFormLayout>
#include <QIcon>
#include <QInputDialog>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include <QProgressDialog>
#include <QPropertyAnimation>
#include <QPushButton>
#include <QScrollBar>
#include <QSettings>
#include <QSlider>
#include <QSocketNotifier>
#include <QStringBuilder>
#include <QStringList>
#include <QTextEdit>
#include <QTimer>
#include <QTimerEvent>
#include <QTreeWidget>
#include <QTreeWidgetItem>
#if QT_VERSION >= 0x050000
// this is to hack access to the --title parameter in Qt5
#include <QWindow>
#endif
#include <QtDebug>
#ifdef Q_OS_UNIX
#include <signal.h>
#include <unistd.h>
#endif
class InputGuard : public QObject
{
public:
InputGuard() : QObject(), m_guardedWidget(NULL), m_checkTimer(0) {}
static void watch(QWidget *w) {
#if QT_VERSION >= 0x050000
if (qApp->platformName() == "wayland")
return;
#endif
if (!s_instance)
s_instance = new InputGuard;
w->installEventFilter(s_instance);
}
protected:
bool eventFilter(QObject *o, QEvent *e) {
QWidget *w = static_cast<QWidget*>(o);
switch (e->type()) {
case QEvent::FocusIn:
case QEvent::WindowActivate:
if (hasActiveFocus(w))
guard(w);
break;
case QEvent::FocusOut:
case QEvent::WindowDeactivate:
if (w == m_guardedWidget && !hasActiveFocus(w))
unguard(w);
break;
default:
break;
}
return false;
}
void timerEvent(QTimerEvent *te) {
if (te->timerId() == m_checkTimer && m_guardedWidget)
check(m_guardedWidget);
else
QObject::timerEvent(te);
}
private:
bool check(QWidget *w) {
#if QT_VERSION >= 0x050000
// try to re-grab
if (!w->window()->windowHandle()->setKeyboardGrabEnabled(true))
w->releaseKeyboard();
#endif
if (w == QWidget::keyboardGrabber()) {
w->setPalette(QPalette());
return true;
}
w->setPalette(QPalette(Qt::white, Qt::red, Qt::white, Qt::black, Qt::gray,
Qt::white, Qt::white, Qt::red, Qt::red));
return false;
}
void guard(QWidget *w) {
w->grabKeyboard();
if (check(w))
m_guardedWidget = w;
if (!m_checkTimer)
m_checkTimer = startTimer(500);
}
bool hasActiveFocus(QWidget *w) {
return w == QApplication::focusWidget() && w->isActiveWindow();
}
void unguard(QWidget *w) {
Q_ASSERT(m_guardedWidget == w);
killTimer(m_checkTimer);
m_checkTimer = 0;
m_guardedWidget = NULL;
w->releaseKeyboard();
}
private:
QWidget *m_guardedWidget;
int m_checkTimer;
static InputGuard *s_instance;
};
InputGuard *InputGuard::s_instance = NULL;
#ifdef WS_X11
#include <QX11Info>
#include <X11/Xlib.h>
#endif
typedef QPair<QString, QString> Help;
typedef QList<Help> HelpList;
typedef QPair<QString, HelpList> CategoryHelp;
typedef QMap<QString, CategoryHelp> HelpDict;
Qarma::Qarma(int &argc, char **argv) : QApplication(argc, argv)
, m_modal(false)
, m_selectableLabel(false)
, m_parentWindow(0)
, m_timeout(0)
, m_notificationId(0)
, m_dialog(NULL)
, m_type(Invalid)
{
QStringList argList = QCoreApplication::arguments(); // arguments() is slow
m_zenity = argList.at(0).endsWith("zenity");
// make canonical list
QStringList args;
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;
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 == "--password") {
m_type = Password;
error = showPassword(args);
} else if (arg == "--forms") {
m_type = Forms;
error = showForms(args);
}
if (error != 1) {
break;
}
}
if (error) {
QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection);
return;
}
if (m_dialog) {
#if QT_VERSION >= 0x050000
// this hacks access to the --title parameter in Qt5
// for some reason it's not set on the dialog.
// 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
QWindow *w = new QWindow;
w->setVisible(true);
m_dialog->setWindowTitle(w->title());
delete w;
#endif
// close on ctrl+return in addition to ctrl+enter
QAction *shortAccept = new QAction(m_dialog);
m_dialog->addAction(shortAccept);
shortAccept->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Return));
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();
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);
}
m_dialog->setWindowModality(m_modal ? Qt::ApplicationModal : Qt::NonModal);
if (!m_caption.isNull())
m_dialog->setWindowTitle(m_caption);
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);
XSetTransientForHint(QX11Info::display(), m_dialog->winId(), m_parentWindow);
#endif
}
}
}
bool Qarma::error(const QString message)
{
printf("Error: %s", qPrintable(message));
QMetaObject::invokeMethod(this, "quitOnError", Qt::QueuedConnection);
return true;
}
#define IF_IS(_TYPE_) if (const _TYPE_ *t = qobject_cast<const _TYPE_*>(w))
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 t->selectedDate().toString(Qt::SystemLocaleShortDate);
return t->selectedDate().toString(pattern);
} else IF_IS(QCheckBox) {
return t->isChecked() ? "true" : "false";
}
return QString();
}
void Qarma::dialogFinished(int status)
{
if (m_type == FileSelection) {
QFileDialog *dlg = static_cast<QFileDialog*>(sender());
QVariantList l;
for (int i = 0; i < dlg->sidebarUrls().count(); ++i)
l << dlg->sidebarUrls().at(i);
QSettings settings("qarma");
settings.setValue("Bookmarks", l);
settings.setValue("FileDetails", dlg->viewMode() == QFileDialog::Detail);
}
if (!(status == QDialog::Accepted || status == QMessageBox::Ok || status == QMessageBox::Yes)) {
#ifdef Q_OS_UNIX
if (sender()->property("qarma_autokill_parent").toBool()) {
::kill(getppid(), 15);
}
#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("qarma_date_format").toString();
QDate date = sender()->findChild<QCalendarWidget*>()->selectedDate();
if (format.isEmpty())
printf("%s\n", qPrintable(date.toString(Qt::SystemLocaleShortDate)));
else
printf("%s\n", qPrintable(date.toString(format)));
break;
}
case Entry: {
printf("%s\n", qPrintable(static_cast<QInputDialog*>(sender())->textValue()));
break;
}
case Password: {
QLineEdit *username = sender()->findChild<QLineEdit*>("qarma_username"),
*password = sender()->findChild<QLineEdit*>("qarma_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<QFileDialog*>(sender())->selectedFiles();
printf("%s\n", qPrintable(files.join(sender()->property("qarma_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("qarma").setValue("CustomPalette", l);
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) {
bool done(false);
foreach (const QTreeWidgetItem *twi, tw->selectedItems()) {
done = true;
result << twi->text(0);
}
if (!done) { // checkable
for (int i = 0; i < tw->topLevelItemCount(); ++i) {
const QTreeWidgetItem *twi = tw->topLevelItem(i);
if (twi->checkState(0) == Qt::Checked)
result << twi->text(1);
}
}
}
printf("%s\n", qPrintable(result.join(sender()->property("qarma_separator").toString())));
break;
}
case Forms: {
QFormLayout *fl = sender()->findChild<QFormLayout*>();
QStringList result;
QString format = sender()->property("qarma_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("qarma_separator").toString())));
break;
}
default:
qDebug() << "unhandled output" << m_type;
break;
}
exit (0);
}
void Qarma::quitOnError()
{
exit(1);
}
#define NEXT_ARG QString((++i < args.count()) ? args.at(i) : QString())
#define WARN_UNKNOWN_ARG(_KNOWN_) if (args.at(i).startsWith("--") && args.at(i) != _KNOWN_) qDebug() << "unspecific argument" << args.at(i);
#define SHOW_DIALOG m_dialog = dlg; connect(dlg, SIGNAL(finished(int)), SLOT(dialogFinished(int))); dlg->show();
bool Qarma::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") {
bool ok;
const int w = NEXT_ARG.toUInt(&ok);
if (!ok)
return !error("--width must be followed by a positive number");
m_size.setWidth(w);
} else if (args.at(i) == "--height") {
bool ok;
const int h = NEXT_ARG.toUInt(&ok);
if (!ok)
return !error("--height must be followed by a positive number");
m_size.setHeight(h);
} else if (args.at(i) == "--timeout") {
bool ok;
const int t = NEXT_ARG.toUInt(&ok);
if (!ok)
return !error("--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) == "--attach") {
bool ok;
const int w = NEXT_ARG.toUInt(&ok, 0);
if (!ok)
return !error("--attach must be followed by a positive number");
m_parentWindow = w;
} else {
remains << args.at(i);
}
}
args = remains;
return true;
}
#define NEW_DIALOG QDialog *dlg = new QDialog; QVBoxLayout *vl = new QVBoxLayout(dlg);
#define FINISH_DIALOG(_BTNS_) QDialogButtonBox *btns = new QDialogButtonBox(_BTNS_, Qt::Horizontal, dlg);\
vl->addWidget(btns);\
connect(btns, SIGNAL(accepted()), dlg, SLOT(accept()));\
connect(btns, SIGNAL(rejected()), dlg, SLOT(reject()));
char Qarma::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("qarma_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()));
FINISH_DIALOG(QDialogButtonBox::Ok|QDialogButtonBox::Cancel);
SHOW_DIALOG
return 0;
}
char Qarma::showEntry(const QStringList &args)
{
QInputDialog *dlg = new QInputDialog;
for (int i = 0; i < args.count(); ++i) {
if (args.at(i) == "--text")
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 { WARN_UNKNOWN_ARG("--entry") }
}
SHOW_DIALOG
return 0;
}
char Qarma::showPassword(const QStringList &args)
{
NEW_DIALOG
QLineEdit *username(NULL), *password(NULL);
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("qarma_username");
break;
} else { WARN_UNKNOWN_ARG("--password") }
}
vl->addWidget(new QLabel(tr("Enter password"), dlg));
vl->addWidget(password = new QLineEdit(dlg));
password->setObjectName("qarma_password");
password->setEchoMode(QLineEdit::Password);
InputGuard::watch(password);
if (username)
username->setFocus(Qt::OtherFocusReason);
else
password->setFocus(Qt::OtherFocusReason);
FINISH_DIALOG(QDialogButtonBox::Ok|QDialogButtonBox::Cancel);
SHOW_DIALOG
return 0;
}
char Qarma::showMessage(const QStringList &args, char type)
{
QMessageBox *dlg = new QMessageBox;
dlg->setStandardButtons((type == 'q') ? QMessageBox::Yes|QMessageBox::No : QMessageBox::Ok);
dlg->setDefaultButton(QMessageBox::Ok);
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) == "--no-markup")
html = false;
else if (args.at(i) == "--default-cancel")
dlg->setDefaultButton(QMessageBox::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);
}
if (dlg->iconPixmap().isNull())
dlg->setIcon(type == 'w' ? QMessageBox::Warning :
(type == 'q' ? QMessageBox::Question :
(type == 'e' ? QMessageBox::Critical : QMessageBox::Information)));
SHOW_DIALOG
return 0;
}
char Qarma::showFileSelection(const QStringList &args)
{
QFileDialog *dlg = new QFileDialog;
QSettings settings("qarma");
dlg->setViewMode(settings.value("FileDetails", false).toBool() ? QFileDialog::Detail : QFileDialog::List);
dlg->setFileMode(QFileDialog::ExistingFile);
dlg->setOption(QFileDialog::DontConfirmOverwrite, false);
dlg->setProperty("qarma_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")
dlg->selectFile(NEXT_ARG);
else if (args.at(i) == "--multiple")
dlg->setFileMode(QFileDialog::ExistingFiles);
else if (args.at(i) == "--directory") {
dlg->setFileMode(QFileDialog::Directory);
dlg->setOption(QFileDialog::ShowDirsOnly);
} else if (args.at(i) == "--save") {
dlg->setFileMode(QFileDialog::AnyFile);
dlg->setAcceptMode(QFileDialog::AcceptSave);
}
else if (args.at(i) == "--separator")
dlg->setProperty("qarma_separator", NEXT_ARG);
else if (args.at(i) == "--confirm-overwrite")
dlg->setOption(QFileDialog::DontConfirmOverwrite);
else if (args.at(i) == "--file-filter")
mimeFilters << NEXT_ARG.split(" ");
else if (args.at(i) == "--initial")
dlg->setDirectory(NEXT_ARG);
else { WARN_UNKNOWN_ARG("--file-selection") }
}
dlg->setNameFilters(mimeFilters);
SHOW_DIALOG
return 0;
}
void Qarma::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;
}
char Qarma::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);
bool editable(false), checkable(false), exclusive(false), icons(false), ok;
QStringList columns;
QStringList values;
QList<int> hiddenCols;
dlg->setProperty("qarma_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("qarma_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") {
qWarning("TODO: --print-column");
} 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) != "--list") {
values << args.at(i);
}
}
if (checkable)
editable = false;
int columnCount = qMax(columns.count(), 1);
tw->setColumnCount(columnCount);
tw->setHeaderLabels(columns);
foreach (const int &i, hiddenCols)
tw->setColumnHidden(i, true);
for (int i = 0; i < values.count(); ) {
QStringList itemValues;
for (int j = 0; j < 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;
item->setCheckState(0, Qt::Unchecked);
}
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);
}
if (exclusive) {
connect (tw, SIGNAL(itemChanged(QTreeWidgetItem*, int)), SLOT(toggleItems(QTreeWidgetItem*, int)));
}
for (int i = 0; i < columns.count(); ++i)
tw->resizeColumnToContents(i);
FINISH_DIALOG(QDialogButtonBox::Ok|QDialogButtonBox::Cancel);
SHOW_DIALOG
return 0;
}
void Qarma::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", "Qarma", m_notificationId, "dialog-information", summary, message,
QStringList() /*actions*/, hintMap, m_timeout);
if (msg.arguments().count())
m_notificationId = msg.arguments().at(0).toUInt();
return;
}
QMessageBox *dlg = static_cast<QMessageBox*>(m_dialog);
if (!dlg) {
dlg = new QMessageBox;
dlg->setIcon(QMessageBox::Information);
dlg->setStandardButtons(noClose ? QMessageBox::NoButton : QMessageBox::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(QApplication::desktop()->availableGeometry().topRight() - QPoint(dlg->width() + 20, -20));
}
char Qarma::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();
} else if (args.at(i) == "--hint") {
m_notificationHints = NEXT_ARG;
} else if (args.at(i) == "--selectable-labels") {
m_selectableLabel = true;
} else { WARN_UNKNOWN_ARG("--notification") }
}
if (!message.isEmpty())
notify(message, listening);
if (!(listening || m_dialog))
QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection);
return 0;
}
static QFile *gs_stdin = 0;
void Qarma::finishProgress()
{
Q_ASSERT(m_type == Progress);
QProgressDialog *dlg = static_cast<QProgressDialog*>(m_dialog);
if (dlg->property("qarma_autoclose").toBool())
QTimer::singleShot(250, this, SLOT(quit()));
else {
dlg->setRange(0, 101);
dlg->setValue(100);
disconnect (dlg, SIGNAL(canceled()), dlg, SLOT(reject()));
connect (dlg, SIGNAL(canceled()), dlg, SLOT(accept()));
dlg->setCancelButtonText(m_ok.isNull() ? tr("Ok") : m_ok);
if (QPushButton *btn = dlg->findChild<QPushButton*>())
btn->show();
}
}
void Qarma::readStdIn()
{
QSocketNotifier *notifier = qobject_cast<QSocketNotifier*>(sender());
if (notifier)
notifier->setEnabled(false);
QByteArray ba = gs_stdin->readLine();
if (ba.isEmpty() && notifier) {
gs_stdin->close();
// gs_stdin->deleteLater(); // hello segfault...
// gs_stdin = NULL;
notifier->deleteLater();
return;
}
static QString cachedText;
QString newText = QString::fromLocal8Bit(ba);
if (newText.isEmpty() && cachedText.isEmpty()) {
if (notifier)
notifier->setEnabled(true);
return;
}
QStringList input;
if (m_type != TextInfo)
input = newText.split('\n');
if (m_type == Progress) {
QProgressDialog *dlg = static_cast<QProgressDialog*>(m_dialog);
if (dlg->maximum() == 0)
return; // no input for pulsating progress
const int oldValue = dlg->value();
bool ok;
foreach (QString line, input) {
static QRegExp nondigit("[^0-9]");
int u = line.section(nondigit,0,0).toInt(&ok);
if (ok)
dlg->setValue(qMin(100,u));
}
if (dlg->value() == 100) {
finishProgress();
} else if (oldValue == 100) {
disconnect (dlg, SIGNAL(canceled()), dlg, SLOT(accept()));
connect (dlg, SIGNAL(canceled()), dlg, SLOT(reject()));
dlg->setCancelButtonText(m_cancel.isNull() ? tr("Cancel") : m_cancel);
}
} else if (m_type == TextInfo) {
if (QTextEdit *te = m_dialog->findChild<QTextEdit*>()) {
cachedText += newText;
static QPropertyAnimation *animator = NULL;
if (!animator || animator->state() != QPropertyAnimation::Running) {
const int oldValue = te->verticalScrollBar() ? te->verticalScrollBar()->value() : 0;
te->setText(te->toPlainText() + cachedText);
cachedText.clear();
if (te->verticalScrollBar() && te->property("qarma_autoscroll").toBool()) {
te->verticalScrollBar()->setValue(oldValue);
if (!animator) {
animator = new QPropertyAnimation(te->verticalScrollBar(), "value", this);
animator->setEasingCurve(QEasingCurve::InOutCubic);
connect(animator, SIGNAL(finished()), SLOT(readStdIn()));
}
const int diff = te->verticalScrollBar()->maximum() - oldValue;
if (diff > 0) {
animator->setDuration(qMin(qMax(200, diff), 2500));
animator->setEndValue(te->verticalScrollBar()->maximum());
animator->start();
}
}
}
}
} else if (m_type == Notification) {
bool userNeedsHelp = true;
foreach (QString line, input) {
int split = line.indexOf(':');
if (split < 0)
continue;
if (line.left(split) == "icon") {
userNeedsHelp = false;
// TODO: some icon filename, seems gnome specific and i've no idea how to handle this atm.
qWarning("'icon' command not yet supported - if you know what this is supposed to do, please file a bug");
} else if (line.left(split) == "message" || line.left(split) == "tooltip") {
userNeedsHelp = false;
notify(line.mid(split+1));
} else if (line.left(split) == "visible") {
userNeedsHelp = false;
if (m_dialog)
m_dialog->setVisible(line.mid(split+1).trimmed().compare("false", Qt::CaseInsensitive) &&
line.mid(split+1).trimmed().compare("0", Qt::CaseInsensitive));
else
qWarning("'visible' command only supported for failsafe dialog notification");
} else if (line.left(split) == "hints") {
m_notificationHints = line.mid(split+1);
}
}
if (userNeedsHelp)
qDebug() << "icon: <filename>\nmessage: <UTF-8 encoded text>\ntooltip: <UTF-8 encoded text>\nvisible: <true|false>";
}
if (notifier)
notifier->setEnabled(true);
}
void Qarma::listenToStdIn()
{
if (gs_stdin)
return;
gs_stdin = new QFile;
if (gs_stdin->open(stdin, QIODevice::ReadOnly)) {
QSocketNotifier *snr = new QSocketNotifier(gs_stdin->handle(), QSocketNotifier::Read, gs_stdin);
connect (snr, SIGNAL(activated(int)), SLOT(readStdIn()));
} else {
delete gs_stdin;
gs_stdin = NULL;
}
}
char Qarma::showProgress(const QStringList &args)
{
QProgressDialog *dlg = new QProgressDialog;
dlg->setRange(0, 101);
for (int i = 0; i < args.count(); ++i) {
if (args.at(i) == "--text")
dlg->setLabelText(labelText(NEXT_ARG));
else if (args.at(i) == "--percentage")
dlg->setValue(NEXT_ARG.toUInt());
else if (args.at(i) == "--pulsate")