aboutsummaryrefslogtreecommitdiffstats
path: root/src/ui/main_window/MainWindowSlotFunction.cpp
blob: b19c15e878d5f3cb36c3868f8811377c64b3152e (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
/**
 * Copyright (C) 2021-2024 Saturneric <[email protected]>
 *
 * This file is part of GpgFrontend.
 *
 * GpgFrontend is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * GpgFrontend 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 GpgFrontend. If not, see <https://www.gnu.org/licenses/>.
 *
 * The initial version of the source code is inherited from
 * the gpg4usb project, which is under GPL-3.0-or-later.
 *
 * All the source code of GpgFrontend was modified and released by
 * Saturneric <[email protected]> starting on May 12, 2021.
 *
 * SPDX-License-Identifier: GPL-3.0-or-later
 *
 */

#include "MainWindow.h"
#include "core/function/gpg/GpgKeyImportExporter.h"
#include "core/function/result_analyse/GpgDecryptResultAnalyse.h"
#include "core/function/result_analyse/GpgEncryptResultAnalyse.h"
#include "core/function/result_analyse/GpgSignResultAnalyse.h"
#include "core/model/GpgDecryptResult.h"
#include "core/model/GpgEncryptResult.h"
#include "core/model/GpgSignResult.h"
#include "core/module/ModuleManager.h"
#include "core/typedef/GpgTypedef.h"
#include "core/utils/BuildInfoUtils.h"
#include "core/utils/CommonUtils.h"
#include "core/utils/GpgUtils.h"
#include "ui/UIModuleManager.h"
#include "ui/UserInterfaceUtils.h"
#include "ui/dialog/SignersPicker.h"
#include "ui/dialog/help/AboutDialog.h"
#include "ui/dialog/import_export/KeyUploadDialog.h"
#include "ui/function/GpgOperaHelper.h"
#include "ui/function/SetOwnerTrustLevel.h"
#include "ui/struct/GpgOperaResult.h"
#include "ui/widgets/FindWidget.h"
#include "ui/widgets/KeyList.h"
#include "ui/widgets/TextEdit.h"

namespace GpgFrontend::UI {

void MainWindow::slot_find() {
  if (edit_->TabCount() == 0 || edit_->CurTextPage() == nullptr) {
    return;
  }

  // At first close verifynotification, if existing
  edit_->CurPageTextEdit()->CloseNoteByClass("FindWidget");

  auto* fw = new FindWidget(this, edit_->CurTextPage());
  edit_->CurPageTextEdit()->ShowNotificationWidget(fw, "FindWidget");
}

/*
 * Append the selected (not checked!) Key(s) To Textedit
 */
void MainWindow::slot_append_selected_keys() {
  auto keys = m_key_list_->GetSelectedKeys();
  if (keys.empty()) return;

  auto [err, gf_buffer] = GpgKeyImportExporter::GetInstance(
                              m_key_list_->GetCurrentGpgContextChannel())
                              .ExportKey(keys.front(), false, true, false);
  if (CheckGpgError(err) != GPG_ERR_NO_ERROR) {
    CommonUtils::RaiseMessageBox(this, err);
    return;
  }

  edit_->SlotAppendText2CurTextPage(gf_buffer.ConvertToQByteArray());
}

void MainWindow::slot_append_keys_create_datetime() {
  auto key = m_key_list_->GetSelectedKey();
  if (key == nullptr) return;

  auto create_datetime_format_str_local =
      QLocale().toString(key->CreationTime()) + " (" + tr("Localize") + ") " +
      "\n";
  auto create_datetime_format_str =
      QLocale().toString(key->CreationTime().toUTC()) + " (" + tr("UTC") +
      ") " + "\n ";
  edit_->SlotAppendText2CurTextPage(create_datetime_format_str_local +
                                    create_datetime_format_str);
}

void MainWindow::slot_append_keys_expire_datetime() {
  auto key = m_key_list_->GetSelectedKey();
  if (key == nullptr) return;

  auto expire_datetime_format_str_local =
      QLocale().toString(key->ExpirationTime()) + " (" + tr("Local Time") +
      ") " + "\n";
  auto expire_datetime_format_str =
      QLocale().toString(key->ExpirationTime().toUTC()) + " (UTC) " + "\n";

  edit_->SlotAppendText2CurTextPage(expire_datetime_format_str_local +
                                    expire_datetime_format_str);
}

void MainWindow::slot_append_keys_fingerprint() {
  auto key = m_key_list_->GetSelectedKey();
  if (key == nullptr) return;

  auto fingerprint_format_str = BeautifyFingerprint(key->Fingerprint()) + "\n";

  edit_->SlotAppendText2CurTextPage(fingerprint_format_str);
}

void MainWindow::slot_copy_mail_address_to_clipboard() {
  auto key = m_key_list_->GetSelectedKey();
  if (key == nullptr) return;

  QClipboard* cb = QApplication::clipboard();
  cb->setText(key->Email());
}

void MainWindow::slot_copy_default_uid_to_clipboard() {
  auto key = m_key_list_->GetSelectedKey();
  if (key == nullptr || key->KeyType() != GpgAbstractKeyType::kGPG_KEY) return;

  QClipboard* cb = QApplication::clipboard();
  cb->setText(qSharedPointerDynamicCast<GpgKey>(key)->UIDs().front().GetUID());
}

void MainWindow::slot_copy_key_id_to_clipboard() {
  auto key = m_key_list_->GetSelectedKey();
  if (key == nullptr) return;

  QClipboard* cb = QApplication::clipboard();
  cb->setText(key->ID());
}

void MainWindow::slot_show_key_details() {
  auto keys = m_key_list_->GetSelectedKeys();
  if (keys.isEmpty()) return;

  CommonUtils::OpenDetailsDialogByKey(
      this, m_key_list_->GetCurrentGpgContextChannel(), keys.front());
}

void MainWindow::slot_add_key_2_favorite() {
  auto key = m_key_list_->GetSelectedKey();
  if (key == nullptr) return;

  auto key_db_name =
      GetGpgKeyDatabaseName(m_key_list_->GetCurrentGpgContextChannel());

  LOG_D() << "add key" << key->ID() << "to favorite at key db" << key_db_name;

  CommonUtils::GetInstance()->AddKey2Favorite(key_db_name, key);
  emit SignalUIRefresh();
}

void MainWindow::slot_remove_key_from_favorite() {
  auto keys = m_key_list_->GetSelectedKeys();
  if (keys.empty()) return;

  auto key_db_name =
      GetGpgKeyDatabaseName(m_key_list_->GetCurrentGpgContextChannel());

  CommonUtils::GetInstance()->RemoveKeyFromFavorite(key_db_name, keys.front());

  emit SignalUIRefresh();
}

void MainWindow::refresh_keys_from_key_server() {
  auto keys = m_key_list_->GetSelectedGpgKeys();
  if (keys.empty()) return;
  CommonUtils::GetInstance()->ImportGpgKeyFromKeyServer(
      m_key_list_->GetCurrentGpgContextChannel(), keys);
}

void MainWindow::slot_set_owner_trust_level_of_key() {
  auto keys = m_key_list_->GetSelectedGpgKeys();
  if (keys.empty()) return;

  auto* function = new SetOwnerTrustLevel(this);
  function->Exec(m_key_list_->GetCurrentGpgContextChannel(), keys.front());
  function->deleteLater();
}

void MainWindow::upload_key_to_server() {
  auto keys = m_key_list_->GetSelectedKeys();
  if (keys.empty()) return;

  auto* dialog = new KeyUploadDialog(m_key_list_->GetCurrentGpgContextChannel(),
                                     keys, this);
  dialog->show();
  dialog->SlotUpload();
}

void MainWindow::SlotOpenFile(const QString& path) {
  edit_->SlotOpenFile(path);
}

void MainWindow::slot_version_upgrade_notify() {
  if (!Module::IsModuleActivate(kVersionCheckingModuleID)) return;

  auto is_loading_done = Module::RetrieveRTValueTypedOrDefault<>(
      kVersionCheckingModuleID, "version.loading_done", false);
  if (!is_loading_done) {
    FLOG_W("invalid version info from rt, loading hasn't done yet");
    return;
  }

  const auto project_build_branch = GetProjectBuildGitBranchName();
  if (project_build_branch.contains("develop") ||
      project_build_branch.contains("dev/")) {
    LOG_I() << "develop or testing version, skip notifying version info.";
    return;
  }

  auto is_need_upgrade = Module::RetrieveRTValueTypedOrDefault<>(
      kVersionCheckingModuleID, "version.need_upgrade", false);

  auto is_current_a_withdrawn_version = Module::RetrieveRTValueTypedOrDefault<>(
      kVersionCheckingModuleID, "version.current_a_withdrawn_version", false);

  auto is_current_version_released = Module::RetrieveRTValueTypedOrDefault<>(
      kVersionCheckingModuleID, "version.current_version_released", false);

  auto latest_version = Module::RetrieveRTValueTypedOrDefault<>(
      kVersionCheckingModuleID, "version.latest_version", QString{});

  auto is_git_commit_hash_mismatch = Module::RetrieveRTValueTypedOrDefault<>(
      kVersionCheckingModuleID, "version.git_commit_hash_mismatch", false);

  if (is_need_upgrade) {
    statusBar()->showMessage(
        tr("GpgFrontend Upgradeable (New Version: %1).").arg(latest_version),
        30000);

    auto* b = new QToolButton();
    b->setToolButtonStyle(Qt::ToolButtonIconOnly);
    b->setIcon(QIcon(":/icons/upgrade.png"));
    connect(b, &QPushButton::clicked,
            [=]() { (new AboutDialog(tr("Update"), this))->show(); });
    statusBar()->addPermanentWidget(b);
  } else if (is_current_a_withdrawn_version) {
    auto response = QMessageBox::warning(
        this, tr("Withdrawn Version"),
        tr("This version(%1) may have been withdrawn by the developer due to "
           "serious problems. Please stop using this version immediately and "
           "download the latest stable version (%2) on the Github Releases "
           "Page.")
            .arg(latest_version)
            .arg(latest_version),
        QMessageBox::Ok | QMessageBox::Open);

    if (response == QMessageBox::Open) {
      QDesktopServices::openUrl(
          QUrl("https://github.com/saturneric/GpgFrontend/releases/latest"));
    }
  } else if (!is_current_version_released) {
    statusBar()->showMessage(
        tr("This may be a BETA Version (Latest Stable Version: %1).")
            .arg(latest_version),
        30000);

    auto* b = new QToolButton();
    b->setToolButtonStyle(Qt::ToolButtonIconOnly);
    b->setIcon(QIcon(":/icons/warning-filling.png"));
    connect(b, &QPushButton::clicked,
            [=]() { (new AboutDialog(tr("Update"), this))->show(); });
    statusBar()->addPermanentWidget(b);

  } else if (is_git_commit_hash_mismatch && !IsFlatpakENV()) {
    QMessageBox::information(
        this, tr("Commit Hash Mismatch"),
        tr("The current version's commit hash does not match the official "
           "release. This may indicate a modified or unofficial build. For "
           "security reasons, please verify your installation or download the "
           "official release from the Github Releases Page."),
        QMessageBox::Ok);
  }
}

void MainWindow::slot_refresh_current_file_view() {
  if (edit_->CurFilePage() != nullptr) {
    edit_->CurFilePage()->update();
  }
}

void MainWindow::slot_import_key_from_edit() {
  if (edit_->TabCount() == 0 || edit_->CurPageTextEdit() == nullptr) return;

  CommonUtils::GetInstance()->SlotImportKeys(
      this, m_key_list_->GetCurrentGpgContextChannel(),
      edit_->CurPlainText().toLatin1());
}

void MainWindow::slot_verify_email_by_eml_data(const QByteArray& buffer) {
  GpgOperaHelper::WaitForOpera(
      this, tr("Verifying"), [this, buffer](const OperaWaitingHd& hd) {
        Module::TriggerEvent(
            "EMAIL_VERIFY_EML_DATA",
            {
                {"eml_data", QString::fromLatin1(buffer.toBase64())},
                {"channel",
                 QString::number(m_key_list_->GetCurrentGpgContextChannel())},
            },
            [=](Module::EventIdentifier i, Module::Event::ListenerIdentifier ei,
                Module::Event::Params p) {
              LOG_D() << "EMAIL_VERIFY_EML_DATA callback: " << i << ei;

              // end waiting dialog
              hd();

              // check if error occurred
              if (handle_module_error(p)) return -1;

              if (p.contains("signature") && p.contains("mime")) {
                slot_verify_email_by_eml_data_result_helper(p);
              }

              return 0;
            });
      });
}

void MainWindow::slot_decrypt_email_by_eml_data(const QByteArray& buffer) {
  Module::TriggerEvent(
      "EMAIL_DECRYPT_EML_DATA",
      {
          {"eml_data", QString::fromLatin1(buffer.toBase64())},
          {"channel",
           QString::number(m_key_list_->GetCurrentGpgContextChannel())},
      },
      [=](Module::EventIdentifier i, Module::Event::ListenerIdentifier ei,
          Module::Event::Params p) {
        LOG_D() << "EMAIL_DECRYPT_EML_DATA callback: " << i << ei;

        // check if error occurred
        if (handle_module_error(p)) return -1;

        if (p.contains("eml_data")) {
          decrypt_email_by_eml_data_result_helper(p);
        }

        return 0;
      });
}

void MainWindow::SlotVerifyEML() {
  if (edit_->TabCount() == 0 || edit_->CurPageTextEdit() == nullptr) return;

  auto buffer = edit_->CurPlainText().toLatin1();
  buffer = buffer.replace("\n", "\r\n");

  // LOG_D() << "EML BUFFER: " << buffer;

  slot_verify_email_by_eml_data(buffer);
}

void MainWindow::slot_verifying_unknown_signature_helper(
    const QStringList& fprs) {
  if (!Module::IsModuleActivate(kKeyServerSyncModuleID) || fprs.empty()) return;

  auto fpr_set = QSet<QString>(fprs.begin(), fprs.end());

  QString fpr_list;
  for (const auto& fpr : fpr_set) {
    fpr_list += fpr + "\n";
  }

  LOG_D() << "try to sync missing key info from server: " << fpr_set;

  // Interaction with user
  auto user_response =
      QMessageBox::question(this, tr("Missing Keys"),
                            tr("Some signatures cannot be verified because "
                               "the corresponding keys are missing.\n\n"
                               "The following fingerprints are "
                               "missing:\n%1\n\n"
                               "Would you like to fetch these keys from "
                               "the key server?")
                                .arg(fpr_list),
                            QMessageBox::Yes | QMessageBox::No);

  if (user_response == QMessageBox::Yes) {
    CommonUtils::GetInstance()->ImportKeyByKeyServerSyncModule(
        this, m_key_list_->GetCurrentGpgContextChannel(), fpr_set.values());
  } else {
    QMessageBox::information(
        this, tr("Verification Incomplete"),
        tr("Verification was incomplete due to "
           "missing keys. You can manually import the keys "
           "later."));
  }
}

void MainWindow::slot_verify_email_by_eml_data_result_helper(
    const QMap<QString, QString>& p) {
  const auto mime = QByteArray::fromBase64(p["mime"].toLatin1());
  const auto signature = QByteArray::fromBase64(p["signature"].toLatin1());
  const auto part_mime_content_hash = p["mime_hash"];
  const auto prm_micalg_value = p["micalg"];

  auto timestamp = p.value("datetime", "-1").toLongLong();
  auto datetime = tr("None");
  if (timestamp > 0) {
    datetime = QLocale().toString(QDateTime::fromMSecsSinceEpoch(timestamp));
  }

  QString email_info;
  email_info.append("# E-Mail Information\n\n");
  email_info.append(QString("- %1: %2\n")
                        .arg(tr("From"))
                        .arg(p.value("from", tr("Unknown"))));
  email_info.append(
      QString("- %1: %2\n").arg(tr("To")).arg(p.value("to", tr("Unknown"))));
  email_info.append(QString("- %1: %2\n")
                        .arg(tr("Subject"))
                        .arg(p.value("subject", tr("None"))));
  email_info.append(
      QString("- %1: %2\n").arg(tr("CC")).arg(p.value("cc", tr("None"))));
  email_info.append(
      QString("- %1: %2\n").arg(tr("BCC")).arg(p.value("bcc", tr("None"))));
  email_info.append(QString("- %1: %2\n").arg(tr("Date")).arg(datetime));

  email_info.append("\n");
  email_info.append("# OpenPGP Information\n\n");
  email_info.append(QString("- %1: %2\n")
                        .arg(tr("Signed EML Data Hash (SHA1)"))
                        .arg(part_mime_content_hash));
  email_info.append(QString("- %1: %2\n")
                        .arg(tr("Message Integrity Check Algorithm"))
                        .arg(prm_micalg_value));
  email_info.append("\n");

  if (!p["capsule_id"].isEmpty()) {
    auto v =
        UIModuleManager::GetInstance().GetCapsule(p.value("capsule_id", ""));

    try {
      auto sign_result = std::any_cast<GpgVerifyResult>(v);
      auto result_analyse =
          GpgVerifyResultAnalyse(m_key_list_->GetCurrentGpgContextChannel(),
                                 GPG_ERR_NO_ERROR, sign_result);
      result_analyse.Analyse();

      slot_refresh_info_board(result_analyse.GetStatus(),
                              email_info + result_analyse.GetResultReport());

    } catch (const std::bad_any_cast& e) {
      LOG_E() << "capsule" << p["capsule_id"] << "convert to real type failed"
              << e.what();
    }
  }
}

void MainWindow::slot_eml_verify_show_helper(const QString& email_info,
                                             const GpgVerifyResultAnalyse& r) {}

void MainWindow::slot_result_analyse_show_helper(
    const GpgResultAnalyse& result_analyse) {
  slot_refresh_info_board(result_analyse.GetStatus(),
                          result_analyse.GetResultReport());
}

void MainWindow::slot_result_analyse_show_helper(
    const QContainer<GpgOperaResult>& opera_results) {
  if (opera_results.empty()) {
    slot_refresh_info_board(0, "");
    return;
  }

  int overall_status = 1;  // Initialize to OK
  QStringList report;
  QStringList summary;

  QStringList failed_tags;
  QStringList warning_tags;

  int success_count = 0;
  int fail_count = 0;
  int warn_count = 0;

  for (const auto& opera_result : opera_results) {
    // Update overall status
    overall_status = std::min(overall_status, opera_result.status);

    QString status_text;
    if (opera_result.status < 0) {
      status_text = tr("FAIL");
      failed_tags << opera_result.tag;
      fail_count++;
    } else if (opera_result.status > 0) {
      status_text = tr("OK");
      success_count++;
    } else {
      status_text = tr("WARN");
      warning_tags << opera_result.tag;
      warn_count++;
    }

    // Append detailed report for each operation
    report.append(QString("[ %1 ] %2\n\n%3\n")
                      .arg(status_text, opera_result.tag, opera_result.report));
  }

  // Prepare summary section
  summary.append("# " + tr("Summary Report") + "\n\n");
  summary.append("- " + tr("Total Operations: %1\n").arg(opera_results.size()));
  summary.append("- " + tr("Successful: %1\n").arg(success_count));
  summary.append("- " + tr("Warnings: %1\n").arg(warn_count));
  summary.append("- " + tr("Failures: %1\n").arg(fail_count));

  if (!failed_tags.isEmpty()) {
    summary.append("- " +
                   tr("Failed Objects: %1\n").arg(failed_tags.join(", ")));
  }

  if (!warning_tags.isEmpty()) {
    summary.append("- " +
                   tr("Warning Objects: %1\n").arg(warning_tags.join(", ")));
  }

  // Display the final report in the info board
  if (opera_results.size() == 1) {
    slot_refresh_info_board(overall_status, report.join(""));

  } else {
    slot_refresh_info_board(overall_status,
                            summary.join("") + "\n\n" + report.join(""));
  }
}

void MainWindow::slot_refresh_info_board(int status, const QString& text) {
  info_board_->SlotReset();

  if (status < 0) {
    info_board_->SlotRefresh(text, INFO_ERROR_CRITICAL);
  } else if (status > 0) {
    info_board_->SlotRefresh(text, INFO_ERROR_OK);
  } else {
    info_board_->SlotRefresh(text, INFO_ERROR_WARN);
  }
}

void MainWindow::slot_result_analyse_show_helper(const GpgResultAnalyse& r_a,
                                                 const GpgResultAnalyse& r_b) {
  info_board_->SlotReset();

  slot_refresh_info_board(std::min(r_a.GetStatus(), r_b.GetStatus()),
                          r_a.GetResultReport() + r_b.GetResultReport());
}

void MainWindow::SlotDecryptEML() {
  if (edit_->TabCount() == 0 || edit_->CurPageTextEdit() == nullptr) return;

  auto buffer = edit_->CurPlainText().toLatin1();
  buffer = buffer.replace("\n", "\r\n");

  // LOG_D() << "EML BUFFER: " << buffer;

  slot_decrypt_email_by_eml_data(buffer);
}

void MainWindow::decrypt_email_by_eml_data_result_helper(
    QMap<QString, QString> p) {
  auto timestamp = p.value("datetime", "-1").toLongLong();
  auto datetime = tr("None");
  if (timestamp > 0) {
    datetime = QLocale().toString(QDateTime::fromMSecsSinceEpoch(timestamp));
  }

  const auto eml_data = QByteArray::fromBase64(p["eml_data"].toLatin1());
  edit_->SlotFillTextEditWithText(eml_data);

  QString email_info;
  email_info.append("# E-Mail Information\n\n");
  email_info.append(QString("- %1: %2\n")
                        .arg(tr("From"))
                        .arg(p.value("from", tr("Unknown"))));
  email_info.append(
      QString("- %1: %2\n").arg(tr("To")).arg(p.value("to", tr("Unknown"))));
  email_info.append(QString("- %1: %2\n")
                        .arg(tr("Subject"))
                        .arg(p.value("subject", tr("None"))));
  email_info.append(
      QString("- %1: %2\n").arg(tr("CC")).arg(p.value("cc", tr("None"))));
  email_info.append(
      QString("- %1: %2\n").arg(tr("BCC")).arg(p.value("bcc", tr("None"))));
  email_info.append(QString("- %1: %2\n").arg(tr("Date")).arg(datetime));

  email_info.append("\n");

  if (!p["capsule_id"].isEmpty()) {
    auto v =
        UIModuleManager::GetInstance().GetCapsule(p.value("capsule_id", ""));

    try {
      auto sign_result = std::any_cast<GpgDecryptResult>(v);
      auto result_analyse =
          GpgDecryptResultAnalyse(m_key_list_->GetCurrentGpgContextChannel(),
                                  GPG_ERR_NO_ERROR, sign_result);
      result_analyse.Analyse();

      slot_refresh_info_board(result_analyse.GetStatus(),
                              email_info + result_analyse.GetResultReport());

    } catch (const std::bad_any_cast& e) {
      LOG_E() << "capsule" << p["capsule_id"] << "convert to real type failed"
              << e.what();
    }
  }
}

void MainWindow::SlotEncryptEML() {
  if (edit_->TabCount() == 0 || edit_->CurEMailPage() == nullptr) return;
  auto keys = m_key_list_->GetCheckedKeys();

  if (keys.isEmpty()) {
    QMessageBox::warning(this, tr("No Key Selected"),
                         tr("Please select a key for encrypt the EML."));
    return;
  }
  auto buffer = edit_->CurPlainText().toUtf8();

  auto key_ids =
      ConvertKey2GpgKeyIdList(m_key_list_->GetCurrentGpgContextChannel(), keys);

  GpgOperaHelper::WaitForOpera(
      this, tr("Encrypting"),
      [this, buffer, key_ids](const OperaWaitingHd& hd) {
        Module::TriggerEvent(
            "EMAIL_ENCRYPT_EML_DATA",
            {
                {"body_data", QString::fromLatin1(buffer.toBase64())},
                {"channel",
                 QString::number(m_key_list_->GetCurrentGpgContextChannel())},
                {"encrypt_keys", key_ids.join(';')},
            },

            [=](Module::EventIdentifier i, Module::Event::ListenerIdentifier ei,
                Module::Event::Params p) {
              LOG_D() << "EMAIL_ENCRYPT_EML_DATA callback: " << i << ei;

              // close waiting dialog
              hd();

              // check if error occurred
              if (handle_module_error(p)) return -1;

              if (!p["eml_data"].isEmpty()) {
                edit_->SlotSetText2CurEMailPage(p.value("eml_data", ""));
              }

              if (!p["capsule_id"].isEmpty()) {
                auto v = UIModuleManager::GetInstance().GetCapsule(
                    p.value("capsule_id", ""));

                try {
                  auto encr_result = std::any_cast<GpgEncryptResult>(v);
                  auto result_analyse = GpgEncryptResultAnalyse(
                      m_key_list_->GetCurrentGpgContextChannel(),
                      GPG_ERR_NO_ERROR, encr_result);
                  result_analyse.Analyse();
                  slot_result_analyse_show_helper(result_analyse);

                } catch (const std::bad_any_cast& e) {
                  LOG_E() << "capsule" << p["capsule_id"]
                          << "convert to real type failed" << e.what();
                }
              }

              return 0;
            });
      });
}

void MainWindow::SlotSignEML() {
  if (edit_->TabCount() == 0 || edit_->CurEMailPage() == nullptr) return;
  auto keys = m_key_list_->GetCheckedKeys();

  if (keys.isEmpty()) {
    QMessageBox::warning(this, tr("No Key Selected"),
                         tr("Please select a key for signing the EML."));
    return;
  }

  if (keys.size() > 1) {
    QMessageBox::warning(this, tr("Multiple Keys Selected"),
                         tr("Please select only one key to sign the EML."));
    return;
  }

  auto buffer = edit_->CurPlainText().toUtf8();
  auto key_ids =
      ConvertKey2GpgKeyIdList(m_key_list_->GetCurrentGpgContextChannel(), keys);

  GpgOperaHelper::WaitForOpera(
      this, tr("Signing"), [this, buffer, key_ids](const OperaWaitingHd& hd) {
        Module::TriggerEvent(
            "EMAIL_SIGN_EML_DATA",
            {
                {"body_data", QString::fromLatin1(buffer.toBase64())},
                {"channel",
                 QString::number(m_key_list_->GetCurrentGpgContextChannel())},
                {"sign_key", key_ids.front()},
            },
            [=](Module::EventIdentifier i, Module::Event::ListenerIdentifier ei,
                Module::Event::Params p) {
              LOG_D() << "EMAIL_SIGN_EML_DATA callback: " << i << ei;

              // close waiting dialog
              hd();

              // check if error occurred
              if (handle_module_error(p)) return -1;

              if (!p["eml_data"].isEmpty()) {
                edit_->SlotSetText2CurEMailPage(p.value("eml_data", ""));
              }

              if (!p["capsule_id"].isEmpty()) {
                auto v = UIModuleManager::GetInstance().GetCapsule(
                    p.value("capsule_id", ""));

                try {
                  auto sign_result = std::any_cast<GpgSignResult>(v);
                  auto result_analyse = GpgSignResultAnalyse(
                      m_key_list_->GetCurrentGpgContextChannel(),
                      GPG_ERR_NO_ERROR, sign_result);
                  result_analyse.Analyse();
                  slot_result_analyse_show_helper(result_analyse);

                } catch (const std::bad_any_cast& e) {
                  LOG_E() << "capsule" << p["capsule_id"]
                          << "convert to real type failed" << e.what();
                }
              }

              return 0;
            });
      });
}

void MainWindow::SlotEncryptSignEML() {
  if (edit_->TabCount() == 0 || edit_->CurEMailPage() == nullptr) return;
  auto keys = m_key_list_->GetCheckedKeys();

  if (keys.isEmpty()) {
    QMessageBox::warning(this, tr("No Key Selected"),
                         tr("Please select a key for encrypt the EML."));
    return;
  }

  auto* signers_picker =
      new SignersPicker(m_key_list_->GetCurrentGpgContextChannel(), this);
  QEventLoop loop;
  connect(signers_picker, &SignersPicker::finished, &loop, &QEventLoop::quit);
  loop.exec();

  // return when canceled
  if (!signers_picker->GetStatus()) return;

  auto signer_keys = signers_picker->GetCheckedSigners();

  if (signer_keys.isEmpty()) {
    QMessageBox::warning(this, tr("No Key Selected"),
                         tr("Please select a key for signing the EML."));
    return;
  }

  if (signer_keys.size() > 1) {
    QMessageBox::warning(this, tr("Multiple Keys Selected"),
                         tr("Please select only one key to sign the EML."));
    return;
  }

  auto buffer = edit_->CurPlainText().toUtf8();
  auto key_ids =
      ConvertKey2GpgKeyIdList(m_key_list_->GetCurrentGpgContextChannel(), keys);

  GpgOperaHelper::WaitForOpera(
      this, tr("Encrypting and Signing"),
      [this, buffer, key_ids, signer_keys](const OperaWaitingHd& hd) {
        Module::TriggerEvent(
            "EMAIL_ENCRYPT_SIGN_EML_DATA",
            {
                {"body_data", QString::fromLatin1(buffer.toBase64())},
                {"channel",
                 QString::number(m_key_list_->GetCurrentGpgContextChannel())},
                {"sign_key", signer_keys.front()->ID()},
                {"encrypt_keys", key_ids.front()},
            },
            [=](Module::EventIdentifier i, Module::Event::ListenerIdentifier ei,
                Module::Event::Params p) {
              LOG_D() << "EMAIL_ENCRYPT_SIGN_EML_DATA callback: " << i << ei;

              // close waiting dialog
              hd();

              // check if error occurred
              if (handle_module_error(p)) return -1;

              if (!p["eml_data"].isEmpty()) {
                edit_->SlotSetText2CurEMailPage(p.value("eml_data", ""));
              }

              if (!p["sign_capsule_id"].isEmpty() &&
                  !p["encr_capsule_id"].isEmpty()) {
                auto v1 = UIModuleManager::GetInstance().GetCapsule(
                    p.value("sign_capsule_id", ""));
                auto v2 = UIModuleManager::GetInstance().GetCapsule(
                    p.value("encr_capsule_id", ""));

                try {
                  auto sign_result = std::any_cast<GpgSignResult>(v1);
                  auto encr_result = std::any_cast<GpgEncryptResult>(v2);
                  auto sign_result_analyse = GpgSignResultAnalyse(
                      m_key_list_->GetCurrentGpgContextChannel(),
                      GPG_ERR_NO_ERROR, sign_result);
                  auto encr_result_analyse = GpgEncryptResultAnalyse(
                      m_key_list_->GetCurrentGpgContextChannel(),
                      GPG_ERR_NO_ERROR, encr_result);

                  sign_result_analyse.Analyse();
                  encr_result_analyse.Analyse();
                  slot_result_analyse_show_helper(sign_result_analyse,
                                                  encr_result_analyse);

                } catch (const std::bad_any_cast& e) {
                  LOG_E() << "capsule" << p["capsule_id"]
                          << "convert to real type failed" << e.what();
                }
              }

              return 0;
            });
      });
}

void MainWindow::SlotDecryptVerifyEML() {
  if (edit_->TabCount() == 0 || edit_->CurEMailPage() == nullptr) return;

  auto buffer = edit_->CurPlainText().toUtf8();

  GpgOperaHelper::WaitForOpera(
      this, tr("Decrypting and Verifying"),
      [this, buffer](const OperaWaitingHd& hd) {
        Module::TriggerEvent(
            "EMAIL_DECRYPT_VERIFY_EML_DATA",
            {
                {"eml_data", QString::fromLatin1(buffer.toBase64())},
                {"channel",
                 QString::number(m_key_list_->GetCurrentGpgContextChannel())},
            },
            [=](Module::EventIdentifier i, Module::Event::ListenerIdentifier ei,
                Module::Event::Params p) {
              LOG_D() << "EMAIL_DECRYPT_VERIFY_EML_DATA callback: " << i << ei;

              // close waiting dialog
              hd();

              // check if error occurred
              if (handle_module_error(p)) return -1;

              if (!p["eml_data"].isEmpty()) {
                edit_->SlotSetText2CurEMailPage(p.value("eml_data", ""));
              }

              const auto mime = QByteArray::fromBase64(p["mime"].toLatin1());
              const auto signature =
                  QByteArray::fromBase64(p["signature"].toLatin1());
              const auto part_mime_content_hash = p["mime_hash"];
              const auto prm_micalg_value = p["micalg"];

              auto timestamp = p.value("datetime", "-1").toLongLong();
              auto datetime = tr("None");
              if (timestamp > 0) {
                datetime = QLocale().toString(
                    QDateTime::fromMSecsSinceEpoch(timestamp));
              }

              QString email_info;
              email_info.append("# E-Mail Information\n\n");
              email_info.append(QString("- %1: %2\n")
                                    .arg(tr("From"))
                                    .arg(p.value("from", tr("Unknown"))));
              email_info.append(QString("- %1: %2\n")
                                    .arg(tr("To"))
                                    .arg(p.value("to", tr("Unknown"))));
              email_info.append(QString("- %1: %2\n")
                                    .arg(tr("Subject"))
                                    .arg(p.value("subject", tr("None"))));
              email_info.append(QString("- %1: %2\n")
                                    .arg(tr("CC"))
                                    .arg(p.value("cc", tr("None"))));
              email_info.append(QString("- %1: %2\n")
                                    .arg(tr("BCC"))
                                    .arg(p.value("bcc", tr("None"))));
              email_info.append(
                  QString("- %1: %2\n").arg(tr("Date")).arg(datetime));

              email_info.append("\n");
              email_info.append("# OpenPGP Information\n\n");
              email_info.append(QString("- %1: %2\n")
                                    .arg(tr("Signed EML Data Hash (SHA1)"))
                                    .arg(part_mime_content_hash));
              email_info.append(
                  QString("- %1: %2\n")
                      .arg(tr("Message Integrity Check Algorithm"))
                      .arg(prm_micalg_value));
              email_info.append("\n");

              if (!p["decr_capsule_id"].isEmpty() &&
                  !p["verify_capsule_id"].isEmpty()) {
                auto v1 = UIModuleManager::GetInstance().GetCapsule(
                    p.value("decr_capsule_id", ""));
                auto v2 = UIModuleManager::GetInstance().GetCapsule(
                    p.value("verify_capsule_id", ""));

                try {
                  auto decr_result = std::any_cast<GpgDecryptResult>(v1);
                  auto verify_result = std::any_cast<GpgVerifyResult>(v2);
                  auto decr_result_analyse = GpgDecryptResultAnalyse(
                      m_key_list_->GetCurrentGpgContextChannel(),
                      GPG_ERR_NO_ERROR, decr_result);
                  auto verify_result_analyse = GpgVerifyResultAnalyse(
                      m_key_list_->GetCurrentGpgContextChannel(),
                      GPG_ERR_NO_ERROR, verify_result);

                  decr_result_analyse.Analyse();
                  verify_result_analyse.Analyse();
                  slot_refresh_info_board(
                      std::min(decr_result_analyse.GetStatus(),
                               verify_result_analyse.GetStatus()),
                      email_info + decr_result_analyse.GetResultReport() +
                          verify_result_analyse.GetResultReport());

                } catch (const std::bad_any_cast& e) {
                  LOG_E() << "capsule" << p["capsule_id"]
                          << "convert to real type failed" << e.what();
                }
              }

              return 0;
            });
      });
}

auto MainWindow::handle_module_error(QMap<QString, QString> p) -> bool {
  if (p["ret"] == "-2") {
    QString detailed_error = p["err"];

    QString info =
        tr("# EML Data Error\n\n"
           "The provided EML data does not conform to RFC 3156 standards and "
           "cannot be processed.\n\n"
           "**Details:** %1\n\n"
           "### What is EML Data?\n"
           "EML is a file format for representing email messages, typically "
           "including headers, body text, attachments, and metadata. "
           "Complete and properly structured EML data is required for "
           "validation.\n\n"
           "### Suggested Solutions\n"
           "1. Verify the EML data is complete and matches the structure "
           "outlined in RFC 3156.\n"
           "2. Refer to the official documentation for the EML structure: "
           "%2\n\n"
           "After correcting the EML data, try the operation again.")
            .arg(detailed_error)
            .arg("https://www.rfc-editor.org/rfc/rfc3156.txt");
    slot_refresh_info_board(-2, info);
    return true;
  }

  if (p["ret"] != "0" || !p["err"].isEmpty()) {
    LOG_E() << "An error occurred trying to operate email, "
            << "error message: " << p["err"];

    QString error_message =
        tr("# Email Operation Error\n\n"
           "An error occurred during the email operation. The process "
           "could not be completed.\n\n"
           "**Details:**\n"
           "- **Error Code:** %1\n"
           "- **Error Message:** %2\n\n"
           "### Possible Causes\n"
           "1. The email data may be incomplete or corrupted.\n"
           "2. The selected GPG key does not have the necessary "
           "permissions.\n"
           "3. Issues in the GPG environment or configuration.\n\n"
           "### Suggested Solutions\n"
           "1. Ensure the email data is complete and follows the expected "
           "format.\n"
           "2. Verify the GPG key has the required access permissions.\n"
           "3. Check your GPG environment and configuration settings.\n"
           "4. Review the error details above or application logs for "
           "further troubleshooting.\n\n"
           "If the issue persists, consider seeking technical support or "
           "consulting the documentation.")
            .arg(p["ret"])
            .arg(p["err"]);

    slot_refresh_info_board(-1, error_message);
    return true;
  }

  return false;
}

void MainWindow::slot_gpg_opera_buffer_show_helper(
    const QContainer<GpgOperaResult>& results) {
  for (const auto& result : results) {
    if (result.o_buffer.Empty()) continue;
    edit_->SlotFillTextEditWithText(result.o_buffer.ConvertToQByteArray());
  }
}

void MainWindow::exec_operas_helper(
    const QString& task,
    const QSharedPointer<GpgOperaContextBasement>& contexts) {
  GpgOperaHelper::WaitForMultipleOperas(this, task, contexts->operas);
  slot_gpg_opera_buffer_show_helper(contexts->opera_results);
  slot_result_analyse_show_helper(contexts->opera_results);
}

}  // namespace GpgFrontend::UI