-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathApplication.cpp
More file actions
1020 lines (934 loc) · 30.6 KB
/
Application.cpp
File metadata and controls
1020 lines (934 loc) · 30.6 KB
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
/*
* QDigiDoc4
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#define NOMINMAX
#include "Application.h"
#include "Common.h"
#include "Configuration.h"
#include "CDocSupport.h"
#include "MainWindow.h"
#include "QSigner.h"
#include "QSmartCard.h"
#include "DigiDoc.h"
#include "Settings.h"
#ifdef Q_OS_MAC
#include "MacMenuBar.h"
#else
class MacMenuBar {};
#endif
#include "TokenData.h"
#include "Utils.h"
#include "dialogs/FirstRun.h"
#include "dialogs/SettingsDialog.h"
#include "dialogs/WaitDialog.h"
#include "dialogs/WarningDialog.h"
#include "effects/Overlay.h"
#include <optional>
#include <digidocpp/Container.h>
#include <digidocpp/XmlConf.h>
#include <digidocpp/crypto/X509Cert.h>
#include <qtsingleapplication/src/qtlocalpeer.h>
#include <QAction>
#include <QtCore/QFileInfo>
#include <QtCore/QJsonArray>
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonObject>
#include <QtCore/QProcess>
#include <QtCore/QRegularExpression>
#include <QtCore/QTimer>
#include <QtCore/QTranslator>
#include <QtCore/QUrl>
#include <QtCore/QUrlQuery>
#include <QtCore/QVersionNumber>
#include <QtCore/QXmlStreamReader>
#include <QtGui/QDesktopServices>
#include <QtGui/QFileOpenEvent>
#include <QtGui/QFontDatabase>
#include <QtGui/QScreen>
#include <QtNetwork/QNetworkProxy>
#include <QtNetwork/QSslCertificate>
#include <QtNetwork/QSslConfiguration>
#include <QtWidgets/QAccessibleWidget>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QProgressBar>
#include <QtWidgets/QProgressDialog>
#include <QtWidgets/QToolTip>
#ifdef Q_OS_WIN32
#include <QtCore/QLibrary>
#include <qt_windows.h>
#include <MAPI.h>
#endif
using namespace std::chrono;
const QStringList Application::CONTAINER_EXT {
QStringLiteral("asice"), QStringLiteral("sce"),
QStringLiteral("asics"), QStringLiteral("scs"),
QStringLiteral("bdoc"), QStringLiteral("edoc"), QStringLiteral("adoc"),
};
class DigidocConf final: public digidoc::XmlConfCurrent
{
public:
DigidocConf()
{
enableLog(Settings::LIBDIGIDOCPP_DEBUG);
Settings::LIBDIGIDOCPP_DEBUG = false;
Settings::LIBDIGIDOCPP_DEBUG.registerCallback([this](const bool &value) { enableLog(value); });
#ifndef Q_OS_DARWIN
setTSLOnlineDigest(true);
#endif
#ifdef CONFIG_URL
reload();
Configuration::connect(qApp->conf(), &Configuration::finished, [](bool changed, const QString & /*error*/){
if(changed)
reload();
});
#endif
SettingsDialog::loadProxy(this);
}
int logLevel() const final
{
return log.has_value() ? 4 : digidoc::XmlConfCurrent::logLevel();
}
std::string logFile() const final
{
return log.or_else([this] { return make_optional(digidoc::XmlConfCurrent::logFile()); }).value();
}
std::string proxyHost() const final
{
return proxyConf(&QNetworkProxy::hostName,
Settings::PROXY_HOST, [this] { return digidoc::XmlConfCurrent::proxyHost(); });
}
std::string proxyPort() const final
{
return proxyConf([](const QNetworkProxy &systemProxy) { return QString::number(systemProxy.port()); },
Settings::PROXY_PORT, [this] { return digidoc::XmlConfCurrent::proxyPort(); });
}
std::string proxyUser() const final
{
return proxyConf(&QNetworkProxy::user,
Settings::PROXY_USER, [this] { return digidoc::XmlConfCurrent::proxyUser(); });
}
std::string proxyPass() const final
{
return proxyConf(&QNetworkProxy::password,
Settings::PROXY_PASS, [this] { return digidoc::XmlConfCurrent::proxyPass(); });
}
#ifdef Q_OS_MAC
std::string TSLCache() const final
{
return Application::groupContainerPath().toStdString();
}
#endif
std::vector<digidoc::X509Cert> TSCerts() const final
{
std::vector<digidoc::X509Cert> list = toCerts(QLatin1String("CERT-BUNDLE"));
if(digidoc::X509Cert cert = toCert(fromBase64(Settings::TSA_CERT)))
list.push_back(std::move(cert));
list.emplace_back(); // Make sure that TSA cert pinning is enabled
return list;
}
std::string TSUrl() const final
{
return valueUserScope(Settings::TSA_URL_CUSTOM, Settings::TSA_URL, digidoc::XmlConfCurrent::TSUrl());
}
std::string TSLUrl() const final
{ return valueSystemScope(QLatin1String("TSL-URL"), digidoc::XmlConfCurrent::TSLUrl()); }
std::vector<digidoc::X509Cert> TSLCerts() const final
{
std::vector<digidoc::X509Cert> tslcerts = toCerts(QLatin1String("TSL-CERTS"));
return tslcerts.empty() ? digidoc::XmlConfCurrent::TSLCerts() : std::move(tslcerts);
}
digidoc::X509Cert verifyServiceCert() const final
{
QByteArray cert = fromBase64(Settings::SIVA_CERT);
return cert.isEmpty() ? digidoc::XmlConfCurrent::verifyServiceCert() : toCert(cert);
}
std::vector<digidoc::X509Cert> verifyServiceCerts() const final
{
std::vector<digidoc::X509Cert> list = toCerts(QLatin1String("CERT-BUNDLE"));
if(digidoc::X509Cert cert = verifyServiceCert())
list.push_back(std::move(cert));
list.emplace_back(); // Make sure that TSA cert pinning is enabled
return list;
}
std::string verifyServiceUri() const final
{
return valueUserScope(Settings::SIVA_URL_CUSTOM, Settings::SIVA_URL, digidoc::XmlConfCurrent::verifyServiceUri());
}
bool TSLAllowExpired() const final
{
if(static std::atomic_bool isShown(false); !isShown.exchange(true))
{
dispatchToMain([] {
WarningDialog::create()
->withTitle(Application::tr("The renewal of Trust Service status List has failed"))
->withText(Application::tr(
"Trust Service status List is used for digital signature validation. "
"Please check your internet connection and make sure you have the latest ID-software version "
"installed. An expired Trust Service List (TSL) will be used for signature validation. "
"<a href=\"https://www.id.ee/en/article/digidoc4-message-updating-the-list-of-trusted-certificates-was-unsuccessful/\">Additional information</a>"))
->open();
});
}
return true;
}
private:
#ifdef CONFIG_URL
static void reload()
{
if(Settings::TSA_URL == Application::confValue(Settings::TSA_URL.KEY).toString())
Settings::TSA_URL.clear(); // Cleanup user conf if it is default url
}
#endif
void enableLog(bool enable)
{
if(enable) {
log = QStringLiteral("%1/libdigidocpp.log").arg(QDir::tempPath()).toStdString();
DDCDocLogger::setLogLevel(libcdoc::LEVEL_DEBUG);
} else {
log.reset();
DDCDocLogger::setLogLevel(libcdoc::LEVEL_WARNING);
}
}
template<class T>
static std::string valueSystemScope(const T &key, std::string &&defaultValue)
{
if(auto value = Application::confValue(key); value.isString())
return value.toString().toStdString();
return std::move(defaultValue);
}
template<typename Option>
static std::string valueUserScope(bool custom, const Option &option, std::string &&defaultValue)
{
return custom && option.isSet() ? option : valueSystemScope(option.KEY, std::move(defaultValue));
}
template<typename System, typename Config, class Option>
static std::string proxyConf(System &&system, const Option &option, Config &&config)
{
switch(Settings::PROXY_CONFIG)
{
case Settings::ProxyNone: return {};
case Settings::ProxySystem: return std::invoke(system, [] {
for(const QNetworkProxy &proxy: QNetworkProxyFactory::systemProxyForQuery())
{
if(proxy.type() == QNetworkProxy::HttpProxy)
return proxy;
}
return QNetworkProxy{};
}()).toStdString();
default: return option.isSet() ? option : config();
}
}
template<class T>
static QByteArray fromBase64(const T &data)
{
if constexpr (std::is_convertible_v<T, QByteArray>)
return QByteArray::fromBase64(data);
else
return QByteArray::fromBase64(data.toString().toLatin1());
}
static digidoc::X509Cert toCert(const QByteArray &der)
{
return digidoc::X509Cert((const unsigned char*)der.constData(), size_t(der.size()));
}
static std::vector<digidoc::X509Cert> toCerts(QLatin1String key)
{
std::vector<digidoc::X509Cert> certs;
for(const auto list = Application::confValue(key).toArray(); auto cert: list)
{
if(QByteArray der = fromBase64(cert); !der.isEmpty())
certs.emplace_back((const unsigned char*)der.constData(), size_t(der.size()));
}
return certs;
}
std::optional<std::string> log;
};
class Application::Private
{
public:
Configuration *conf {};
QAction *closeAction {}, *newClientAction {}, *helpAction {};
std::unique_ptr<MacMenuBar> bar;
QSigner *signer {};
QTranslator appTranslator, qtTranslator;
QString lang;
QTimer lastWindowTimer;
volatile bool ready = false;
#ifdef Q_OS_WIN
QStringList tempFiles;
#endif // Q_OS_WIN
};
Application::Application( int &argc, char **argv )
: BaseApplication(argc, argv)
, d(new Private)
{
setApplicationName(QStringLiteral("qdigidoc4"));
setApplicationVersion(QStringLiteral(VERSION_STR));
setOrganizationDomain(QStringLiteral("ria.ee"));
setOrganizationName(QStringLiteral("RIA"));
setWindowIcon(QIcon(QStringLiteral(":/images/Icon.svg")));
if(QFile::exists(QStringLiteral("%1/%2.log").arg(QDir::tempPath(), applicationName())))
qInstallMessageHandler(msgHandler);
#if defined(Q_OS_WIN)
AllowSetForegroundWindow( ASFW_ANY );
#ifdef NDEBUG
setLibraryPaths({ applicationDirPath() });
#endif
#elif defined(Q_OS_MAC)
qputenv("OPENSSL_CONF", applicationDirPath().toUtf8() + "../Resources/openssl.cnf");
#ifdef NDEBUG
setLibraryPaths({ applicationDirPath() + "/../PlugIns" });
#endif
#endif
QStringList args = arguments();
args.removeFirst();
#ifndef Q_OS_MAC
if( isRunning() )
{
sendMessage(args.join(QStringLiteral("\", \"")));
return;
}
connect(this, &Application::messageReceived, this, qOverload<const QString&>(&Application::parseArgs));
#endif
QPalette p = palette();
p.setBrush(QPalette::Link, QBrush("#2F70B6"));
p.setBrush(QPalette::LinkVisited, QBrush("#2F70B6"));
setPalette(p);
setStyleSheet(QStringLiteral(
"QDialogButtonBox { dialogbuttonbox-buttons-have-icons: 0; }\n"));
QNetworkProxyFactory::setUseSystemConfiguration(true);
QFontDatabase::addApplicationFont(QStringLiteral(":/fonts/Roboto-Bold.ttf"));
QFontDatabase::addApplicationFont(QStringLiteral(":/fonts/Roboto-Regular.ttf"));
QFont f(QStringLiteral("Roboto, Helvetica"));
f.setPixelSize(14);
QToolTip::setFont(f);
#ifdef CONFIG_URL
d->conf = new Configuration(this);
QMetaObject::invokeMethod(this, [this] {
auto lessThanVersion = [](QLatin1String key) {
return QVersionNumber::fromString(applicationVersion()) <
QVersionNumber::fromString(confValue(key).toString());
};
WarningDialog *dlg{};
if(lessThanVersion(QLatin1String("QDIGIDOC4-UNSUPPORTED")))
{
dlg = WarningDialog::create()
->withTitle(tr("This version of ID-software on your computer is unsupported"))
->withText(tr("DigiDoc4 Client cannot be used until you update ID-software. "
"Install new ID-software from <a href=\"https://www.id.ee/en/article/install-id-software/\">www.id.ee</a>. "
"macOS users can download the latest ID-software version from the "
"<a href=\"https://itunes.apple.com/ee/developer/ria/id556524921?mt=12\">Mac App Store</a>."));
connect(dlg, &WarningDialog::finished, this, &Application::quit);
}
else if(lessThanVersion(QLatin1String("QDIGIDOC4-SUPPORTED")))
{
dlg = WarningDialog::create()
->withTitle(tr("Your ID-software has expired"))
->withText(tr("To download the latest software version, go to the "
"<a href=\"https://www.id.ee/en/article/install-id-software/\">id.ee</a> website. "
"macOS users can download the latest ID-software version from the "
"<a href=\"https://itunes.apple.com/ee/developer/ria/id556524921?mt=12\">Mac App Store</a>."));
}
connect(d->conf, &Configuration::finished, this, [lessThanVersion](bool changed, const QString &){
if(changed && lessThanVersion(QLatin1String("QDIGIDOC4-LATEST")))
{
auto *dlg = WarningDialog::create(activeWindow())
->withTitle(tr("An ID-software update has been found"))
->withText(tr("To download the update, go to the "
"<a href=\"https://www.id.ee/en/article/install-id-software/\">id.ee</a> website. "
"macOS users can download the update from the "
"<a href=\"https://itunes.apple.com/ee/developer/ria/id556524921?mt=12\">Mac App Store</a>."));
new Overlay(dlg, activeWindow());
dlg->exec();
}
});
if(dlg)
{
#ifdef Q_OS_WIN
dlg->addButton(tr("Start downloading"), QMessageBox::Ok);
connect(dlg, &WarningDialog::accepted, this, [] {
QString path = QApplication::applicationDirPath() + QLatin1String("/id-updater.exe");
if (QFile::exists(path))
QProcess::startDetached(path, {});
});
#endif
dlg->open();
}
}, Qt::QueuedConnection);
#endif
qRegisterMetaType<TokenData>("TokenData");
qRegisterMetaType<QSmartCardData>("QSmartCardData");
qRegisterMetaType<QEventLoop*>("QEventLoop*");
QDesktopServices::setUrlHandler(QStringLiteral("browse"), this, "browse");
QDesktopServices::setUrlHandler(QStringLiteral("mailto"), this, "mailTo");
QAccessible::installFactory([](const QString &classname, QObject *object) -> QAccessibleInterface* {
if (classname == QLatin1String("QSvgWidget") && object && object->isWidgetType())
return new QAccessibleWidget(qobject_cast<QWidget *>(object), QAccessible::StaticText);
return {};
});
installTranslator( &d->appTranslator );
installTranslator( &d->qtTranslator );
loadTranslation(Settings::LANGUAGE);
// Clear obsolete registriy settings
#ifndef Q_OS_DARWIN
Settings::DEFAULT_DIR.clear();
#endif
// Actions
d->closeAction = new QAction( tr("Close Window"), this );
d->closeAction->setShortcut(Qt::CTRL | Qt::Key_W);
connect(d->closeAction, &QAction::triggered, this, &Application::closeWindow);
d->newClientAction = new QAction( tr("New Window"), this );
d->newClientAction->setShortcut(Qt::CTRL | Qt::Key_N);
connect(d->newClientAction, &QAction::triggered, this, []{ showClient({}, false, false, true); });
// This is needed to release application from memory (Windows)
setQuitOnLastWindowClosed( true );
d->lastWindowTimer.setSingleShot(true);
connect(&d->lastWindowTimer, &QTimer::timeout, this, []{ if(topLevelWindows().isEmpty()) quit(); });
connect(this, &Application::lastWindowClosed, this, [&]{ d->lastWindowTimer.start(10s); });
#ifdef Q_OS_MAC
d->bar = std::make_unique<MacMenuBar>();
d->bar->fileMenu()->addAction( d->newClientAction );
d->bar->fileMenu()->addAction( d->closeAction );
d->bar->dockMenu()->addAction( d->newClientAction );
d->helpAction = d->bar->helpMenu()->addAction(tr("DigiDoc4 Client Help"), this, &Application::openHelp);
#endif
DDCDocLogger::setUpLogger(QStringLiteral("%1/libcdoc.log").arg(QDir::tempPath()).toStdString());
try
{
digidoc::Conf::init( new DigidocConf );
d->signer = new QSigner(this);
updateTSLCache(QDateTime::currentDateTimeUtc().addDays(-7));
digidoc::initialize(applicationName().toUtf8().constData(), QStringLiteral("%1/%2 (%3)")
.arg(applicationName(), applicationVersion(), Common::applicationOs()).toUtf8().constData(),
[](const digidoc::Exception *ex) {
qDebug() << "TSL loading finished";
Q_EMIT qApp->TSLLoadingFinished();
qApp->d->ready = true;
if(ex)
dispatchToMain(showWarning, tr("Failed to initalize."), *ex);
}
);
}
catch( const digidoc::Exception &e )
{
showWarning( tr("Failed to initalize."), e );
setQuitOnLastWindowClosed( true );
return;
}
QMetaObject::invokeMethod(this, [this] {
#ifdef Q_OS_MAC
if(!Settings::PLUGINS.isSet())
{
auto *dlg = WarningDialog::create()
->withText(tr("In order to authenticate and sign in e-services with an ID-card you need to install the web browser components."))
->setCancelText(tr("Ignore forever"))
->addButton(tr("Remind later"), QMessageBox::Ignore)
->addButton(tr("Install"), QMessageBox::Open);
connect(dlg, &WarningDialog::finished, this, [](int result) {
switch(result)
{
case QMessageBox::Open: QDesktopServices::openUrl(tr("https://www.id.ee/en/article/install-id-software/")); break;
case QMessageBox::Ignore: break;
default: Settings::PLUGINS = QStringLiteral("ignore");
}
});
dlg->open();
}
#endif
if(Settings::SHOW_INTRO)
{
Settings::SHOW_INTRO = false;
auto *dlg = new FirstRun(mainWindow());
connect(dlg, &FirstRun::langChanged, this, &Application::loadTranslation);
dlg->open();
}
}, Qt::QueuedConnection);
if( !args.isEmpty() || topLevelWindows().isEmpty() )
parseArgs(std::move(args));
}
Application::~Application()
{
for(QWidget *top: topLevelWidgets())
top->close();
#ifdef Q_OS_WIN
for(const QString &file: qAsConst(d->tempFiles))
QFile::remove(file);
d->tempFiles.clear();
#endif // Q_OS_WIN
#ifndef Q_OS_MAC
if( isRunning() )
{
delete d;
return;
}
if(auto *obj = findChild<QtLocalPeer*>())
delete obj;
#else
deinitMacEvents();
#endif
QEventLoop e;
connect(this, &Application::TSLLoadingFinished, &e, &QEventLoop::quit);
if( !d->ready )
e.exec();
digidoc::terminate();
delete d;
QDesktopServices::unsetUrlHandler(QStringLiteral("browse"));
QDesktopServices::unsetUrlHandler(QStringLiteral("mailto"));
if(property("restart").toBool())
{
QStringList args = arguments();
args.removeFirst();
QProcess::startDetached(applicationFilePath(), args);
}
}
#ifndef Q_OS_MAC
void Application::addRecent( const QString & ) {}
#endif
#ifdef Q_OS_WIN
void Application::addTempFile(const QString &file)
{
d->tempFiles.append(file);
}
#endif
void Application::browse( const QUrl &url )
{
QUrl u = url;
u.setScheme(QStringLiteral("file"));
#if defined(Q_OS_WIN)
if(QProcess::startDetached(QStringLiteral("explorer"), {QStringLiteral("/select,"), QDir::toNativeSeparators(u.toLocalFile())}))
return;
#elif defined(Q_OS_MAC)
if(QProcess::startDetached(QStringLiteral("open"), {QStringLiteral("-R"), u.toLocalFile()}))
return;
#endif
QDesktopServices::openUrl( QUrl::fromLocalFile( QFileInfo( u.toLocalFile() ).absolutePath() ) );
}
void Application::closeWindow()
{
#ifndef Q_OS_MAC
if(auto *w = qobject_cast<MainWindow*>(activeWindow()))
w->close();
else
#endif
if(auto *d = qobject_cast<QDialog*>(activeWindow()))
d->reject();
else if(QWidget *w = activeWindow())
w->close();
}
Configuration* Application::conf()
{
return d->conf;
}
template<class T>
QJsonValue Application::confValue(const T &key)
{
#ifdef CONFIG_URL
return qApp->conf()->object().value(key);
#else
Q_UNUSED(key)
return {};
#endif
}
template QJsonValue Application::confValue<QString>(const QString &key);
template QJsonValue Application::confValue<QLatin1String>(const QLatin1String &key);
QVariant Application::confValue( ConfParameter parameter, const QVariant &value )
{
auto *i = static_cast<DigidocConf*>(digidoc::Conf::instance());
QByteArray r;
switch( parameter )
{
case SiVaUrl: r = i->verifyServiceUri().c_str(); break;
case TSAUrl: r = i->TSUrl().c_str(); break;
case TSLUrl: r = i->TSLUrl().c_str(); break;
case TSLCache: r = i->TSLCache().c_str(); break;
case TSLCerts:
{
QList<QSslCertificate> list;
for(const digidoc::X509Cert &cert: i->TSLCerts())
{
if(std::vector<unsigned char> v = cert; !v.empty())
list.append(QSslCertificate(QByteArray::fromRawData((const char*)v.data(), int(v.size())), QSsl::Der));
}
return QVariant::fromValue(list);
}
}
return r.isEmpty() ? value.toString() : QString::fromUtf8( r );
}
bool Application::event(QEvent *event)
{
switch(int(event->type()))
{
case REOpenEvent::Type:
if( !activeWindow() )
showClient();
return true;
case QEvent::FileOpen:
{
QString fileName = static_cast<QFileOpenEvent*>(event)->file().normalized(QString::NormalizationForm_C);
#if QT_VERSION < QT_VERSION_CHECK(6, 5, 0)
QMetaObject::invokeMethod(this, [&fileName] { parseArgs({fileName}); });
#else
QMetaObject::invokeMethod(this, qOverload<QStringList>(&Application::parseArgs), QStringList(fileName));
#endif
return true;
}
#ifdef Q_OS_MAC
// Load here because cocoa NSApplication overides events
case QEvent::ApplicationActivate:
initMacEvents();
return BaseApplication::event(event);
#endif
default: return BaseApplication::event(event);
}
}
void Application::initDiagnosticConf()
{
digidoc::Conf::init(new DigidocConf);
}
void Application::loadTranslation( const QString &lang )
{
if( d->lang == lang )
return;
Settings::LANGUAGE = d->lang = lang;
if(lang == QLatin1String("en")) QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedKingdom));
else if(lang == QLatin1String("ru")) QLocale::setDefault(QLocale( QLocale::Russian, QLocale::RussianFederation));
else QLocale::setDefault(QLocale(QLocale::Estonian, QLocale::Estonia));
void(d->appTranslator.load(QLatin1String(":/translations/%1.qm").arg(lang)));
void(d->qtTranslator.load(QLatin1String(":/translations/qtbase_%1.qm").arg(lang)));
if( d->closeAction ) d->closeAction->setText( tr("Close Window") );
if( d->newClientAction ) d->newClientAction->setText( tr("New Window") );
if(d->helpAction) d->helpAction->setText(tr("DigiDoc4 Client Help"));
}
#ifndef Q_OS_MAC
void Application::mailTo( const QUrl &url )
{
QUrlQuery q(url);
#if defined(Q_OS_WIN)
if(QLibrary lib("mapi32"); auto mapi = LPMAPISENDMAILW(lib.resolve("MAPISendMailW")))
{
QString file = q.queryItemValue( "attachment", QUrl::FullyDecoded );
QString filePath = QDir::toNativeSeparators( file );
QString fileName = QFileInfo( file ).fileName();
QString subject = q.queryItemValue( "subject", QUrl::FullyDecoded );
MapiFileDescW doc {};
doc.nPosition = -1;
doc.lpszPathName = PWSTR(filePath.utf16());
doc.lpszFileName = PWSTR(fileName.utf16());
MapiMessageW message {};
message.lpszSubject = PWSTR(subject.utf16());
message.lpszNoteText = PWSTR(L"");
message.nFileCount = 1;
message.lpFiles = lpMapiFileDescW(&doc);
switch( mapi( NULL, 0, &message, MAPI_LOGON_UI|MAPI_DIALOG, 0 ) )
{
case SUCCESS_SUCCESS:
case MAPI_E_USER_ABORT:
case MAPI_E_LOGIN_FAILURE:
return;
default: break;
}
}
#elif defined(Q_OS_UNIX)
QByteArray thunderbird;
QProcess p;
QStringList env = QProcess::systemEnvironment();
if(env.indexOf(QRegularExpression(QStringLiteral("KDE_FULL_SESSION.*"))) != -1)
{
p.start("kreadconfig", {
"--file", "emaildefaults",
"--group", "PROFILE_Default",
"--key", "EmailClient"});
p.waitForFinished();
if(QByteArray data = p.readAllStandardOutput().trimmed(); data.contains("thunderbird"))
thunderbird = std::move(data);
}
else if(env.indexOf(QRegularExpression(QStringLiteral("GNOME_DESKTOP_SESSION_ID.*"))) != -1)
{
if(QSettings(QDir::homePath() + "/.local/share/applications/mimeapps.list", QSettings::IniFormat)
.value("Default Applications/x-scheme-handler/mailto").toString().contains("thunderbird"))
thunderbird = "/usr/bin/thunderbird";
else
{
for(const QString &path: QProcessEnvironment::systemEnvironment().value("XDG_DATA_DIRS").split(":"))
{
if(QSettings(path + "/applications/defaults.list", QSettings::IniFormat)
.value("Default Applications/x-scheme-handler/mailto").toString().contains("thunderbird"))
{
thunderbird = "/usr/bin/thunderbird";
break;
}
}
}
}
bool status = false;
if( !thunderbird.isEmpty() )
{
status = p.startDetached(thunderbird, {"-compose",
QStringLiteral("subject='%1',attachment='%2'")
.arg( q.queryItemValue( "subject" ) )
.arg(QUrl::fromLocalFile(q.queryItemValue("attachment")).toString())});
}
else
{
status = p.startDetached(QStringLiteral("xdg-email"), {
"--subject", q.queryItemValue("subject"),
"--attach", q.queryItemValue("attachment")});
}
if( status )
return;
#endif
QDesktopServices::openUrl( url );
}
#endif
QWidget* Application::mainWindow()
{
if(auto *win = qobject_cast<MainWindow*>(activeWindow()))
return win;
auto list = topLevelWidgets();
// Prefer main window; on Mac also the menu is top level window
if(auto i = std::find_if(list.cbegin(), list.cend(),
[](QWidget *widget) { return qobject_cast<MainWindow*>(widget); });
i != list.cend())
return *i;
if(auto i = std::find_if(list.cbegin(), list.cend(),
[](QWidget *widget) { return qobject_cast<QDialog*>(widget); });
i != list.cend())
return *i;
return nullptr;
}
void Application::msgHandler(QtMsgType type, const QMessageLogContext &ctx, const QString &msg)
{
QFile f(QStringLiteral("%1/%2.log").arg(QDir::tempPath(), applicationName()));
if(!f.open( QFile::Append ))
return;
f.write(QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd hh:mm:ss ")).toUtf8());
switch(type)
{
case QtDebugMsg: f.write("D"); break;
case QtWarningMsg: f.write("W"); break;
case QtCriticalMsg: f.write("C"); break;
case QtFatalMsg: f.write("F"); break;
default: f.write("I"); break;
}
f.write(QStringLiteral(" %1 ").arg(QLatin1String(ctx.category)).toUtf8());
if(ctx.line > 0)
{
f.write(QStringLiteral("%1:%2 \"%3\" ")
.arg(QFileInfo(QString::fromLatin1(ctx.file)).fileName())
.arg(ctx.line)
.arg(QLatin1String(ctx.function)).toUtf8());
}
f.write(msg.toUtf8());
f.write("\n");
}
bool Application::notify(QObject *object, QEvent *event)
{
try
{
return QApplication::notify(object, event);
}
catch( const digidoc::Exception &e )
{
showWarning( tr("Caught exception!"), e );
}
catch(const std::bad_alloc &e)
{
WarningDialog::create()
->withTitle(DocumentModel::tr("Failed to add file"))
->withText(tr("Added file(s) exceeds the maximum size limit of the container(120MB)."))
->withDetails(QString::fromLocal8Bit(e.what()))
->open();
}
catch(...)
{
WarningDialog::create()->withTitle(tr("Caught exception!"))->open();
}
return false;
}
void Application::openHelp()
{
QDesktopServices::openUrl(QUrl(tr("https://www.id.ee/en/id-help/")));
}
void Application::parseArgs( const QString &msg )
{
QStringList params;
for(const QString ¶m: msg.split(QStringLiteral("\", \""), Qt::SkipEmptyParts))
{
QUrl url( param, QUrl::StrictMode );
params.append(param != QLatin1String("-crypto") && !url.toLocalFile().isEmpty() ? url.toLocalFile() : param);
}
parseArgs(std::move(params));
}
void Application::parseArgs(QStringList args)
{
bool crypto = args.removeAll(QStringLiteral("-crypto")) > 0;
bool sign = args.removeAll(QStringLiteral("-sign")) > 0;
bool newWindow = args.removeAll(QStringLiteral("-newWindow")) > 0;
if(QString suffix = args.value(0);
suffix.endsWith(QLatin1String(".cdoc"), Qt::CaseInsensitive) ||
suffix.endsWith(QLatin1String(".cdoc2"), Qt::CaseInsensitive))
crypto = true;
showClient(std::move(args), crypto, sign, newWindow);
}
uint Application::readTSLVersion(const QString &path)
{
QFile f(path);
if(!f.open(QFile::ReadOnly))
return 0;
QXmlStreamReader r(&f);
while(!r.atEnd())
{
if(r.readNextStartElement() && r.name() == QLatin1String("TSLSequenceNumber"))
{
r.readNext();
return r.text().toUInt();
}
}
return 0;
}
int Application::run()
{
#ifndef Q_OS_MAC
if( isRunning() ) return 0;
#endif
return exec();
}
void Application::showClient(QStringList files, bool crypto, bool sign, bool newWindow)
{
// Make sure all parameters are files
for(auto i = files.begin(); i != files.end(); )
{
if(QFileInfo(*i).isFile())
++i;
else
i = files.erase(i);
}
MainWindow *w = nullptr;
if(newWindow)
w = nullptr;
else if(files.isEmpty()) // If no files selected (e.g. restoring minimized window), select first
w = qobject_cast<MainWindow*>(mainWindow());
else
{
// select first window with no open files
for(auto *widget : topLevelWidgets())
{
if(auto *main = qobject_cast<MainWindow*>(widget);
main && main->windowFilePath().isEmpty())
{
w = main;
break;
}
}
}
if( !w )
{
w = new MainWindow();
QWidget *prev = [w]() -> QWidget* {
for(QWidget *top: topLevelWidgets())
{
QWidget *prev = qobject_cast<MainWindow*>(top);
if(!prev)
prev = qobject_cast<FirstRun*>(top);
if(prev && prev != w && prev->isVisible())
return prev;
}
return {};
}();
if(prev)
w->move(prev->geometry().topLeft() + QPoint(20, 20));
#ifdef Q_OS_LINUX
else
{
if(QScreen *screen = screenAt(w->pos()))
w->move(screen->availableGeometry().center() - w->frameGeometry().adjusted(0, 0, 10, 40).center());
}
#endif
}
#ifdef Q_OS_MAC
// Required for restoring minimized window on macOS
w->setWindowState(Qt::WindowActive);
#endif
w->show();
w->activateWindow();
w->raise();
if(files.isEmpty())
return;
QMetaObject::invokeMethod(w, [&] {
if(sign)
sign = files.size() != 1 || !CONTAINER_EXT.contains(QFileInfo(files.value(0)).suffix(), Qt::CaseInsensitive);
w->selectPage(crypto && !sign ? MainWindow::CryptoIntro : MainWindow::SignIntro);
w->openFiles(std::move(files), false, sign);
});
}
void Application::showWarning(const QString &title, const digidoc::Exception &e)
{
digidoc::Exception::ExceptionCode code = digidoc::Exception::General;
QStringList causes = DigiDoc::parseException(e, code);
WarningDialog::create()->withTitle(title)->withDetails(causes.join('\n'))->open();
}
QSigner* Application::signer() const { return d->signer; }
void Application::updateTSLCache(const QDateTime &tslTime)
{
QString cache = confValue(Application::TSLCache).toString();
QDir().mkpath(cache);
const QStringList tsllist = QDir(QStringLiteral(":/TSL/")).entryList();
for(const QString &file: tsllist)
{
if(QFile tl(cache + "/" + file);
readTSLVersion(":/TSL/" + file) > readTSLVersion(tl.fileName()))
{
const QStringList cleanup = QDir(cache, file + QStringLiteral("*")).entryList();
for(const QString &rm: cleanup)
QFile::remove(cache + '/' + rm);
QFile::copy(":/TSL/" + file, tl.fileName());
tl.setPermissions(QFile::Permissions(0x6444));
if(tslTime.isValid() && tl.open(QFile::Append))
tl.setFileTime(tslTime, QFileDevice::FileModificationTime);
}
}
}
void Application::waitForTSL( const QString &file )
{
if(!CONTAINER_EXT.contains(QFileInfo(file).suffix(), Qt::CaseInsensitive))
return;
if( d->ready )
return;
WaitDialogHider hider;
QProgressDialog p(tr("Loading TSL lists"), QString(), 0, 0, mainWindow());
p.setWindowFlags( (Qt::Dialog | Qt::CustomizeWindowHint | Qt::MSWindowsFixedSizeDialogHint ) & ~Qt::WindowTitleHint );
p.setWindowModality(Qt::WindowModal);