summaryrefslogtreecommitdiffstats
path: root/libkpgp/kpgpui.cpp
blob: 2e6d71606c06d1ecc4c2f2766960457f83506af1 (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
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
/*
    kpgpui.cpp

    Copyright (C) 2001,2002 the KPGP authors
    See file AUTHORS.kpgp for details

    This file is part of KPGP, the KDE PGP/GnuPG support library.

    KPGP 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 2 of the License, or
    (at your option) any later version.

    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 <stdio.h>

#include <tqvgroupbox.h>
#include <tqvbox.h>
#include <tqlabel.h>
#include <tqwhatsthis.h>
#include <tqtooltip.h>
#include <tqapplication.h>
#include <tqtextcodec.h>
#include <tqdatetime.h>
#include <tqpixmap.h>
#include <tqlayout.h>
#include <tqtimer.h>
#include <tqpopupmenu.h>
#include <tqregexp.h>

#include <klocale.h>
#include <kpassdlg.h>
#include <kcharsets.h>
#include <kseparator.h>
#include <kiconloader.h>
#include <klistview.h>
#include <kconfigbase.h>
#include <kconfig.h>
#include <kprogress.h>
#include <kapplication.h>
#include <twin.h>
#if KDE_IS_VERSION( 3, 1, 90 )
#include <kglobalsettings.h>
#endif

#include "kpgp.h"
#include "kpgpui.h"
#include "kpgpkey.h"

#include <assert.h>
#include <string.h> // for memcpy(3)

const int Kpgp::KeySelectionDialog::sCheckSelectionDelay = 250;

namespace Kpgp {

PassphraseDialog::PassphraseDialog( TQWidget *parent,
                                    const TQString &caption, bool modal,
                                    const TQString &keyID )
  :KDialogBase( parent, 0, modal, caption, Ok|Cancel )
{
  TQHBox *hbox = makeHBoxMainWidget();
  hbox->setSpacing( spacingHint() );
  hbox->setMargin( marginHint() );

  TQLabel *label = new TQLabel(hbox);
  label->setPixmap( BarIcon("pgp-keys") );

  TQWidget *rightArea = new TQWidget( hbox );
  TQVBoxLayout *vlay = new TQVBoxLayout( rightArea, 0, spacingHint() );

  if (keyID.isNull())
    label = new TQLabel(i18n("Please enter your OpenPGP passphrase:"),rightArea);
  else
    label = new TQLabel(i18n("Please enter the OpenPGP passphrase for\n\"%1\":").arg(keyID),
                       rightArea);
  lineedit = new KPasswordEdit( rightArea );
  lineedit->setEchoMode(TQLineEdit::Password);
  lineedit->setMinimumWidth( fontMetrics().maxWidth()*20 );
  lineedit->setFocus();
  connect( lineedit, TQT_SIGNAL(returnPressed()), this, TQT_SLOT(slotOk()) );

  vlay->addWidget( label );
  vlay->addWidget( lineedit );

  disableResize();
}


PassphraseDialog::~PassphraseDialog()
{
}

const char * PassphraseDialog::passphrase()
{
  return lineedit->password();
}


// ------------------------------------------------------------------------
// Forbidden accels for KMail: AC GH OP
//                  for KNode: ACE H O
Config::Config( TQWidget *parent, const char *name, bool encrypt )
  : TQWidget( parent, name ), pgp( Module::getKpgp() )
{
  TQGroupBox * group;
  TQLabel    * label;
  TQString     msg;


  TQVBoxLayout *topLayout = new TQVBoxLayout( this, 0, KDialog::spacingHint() );

  group = new TQVGroupBox( i18n("Warning"), this );
  group->layout()->setSpacing( KDialog::spacingHint() );
  // (mmutz) work around TQt label bug in 3.0.0 (and possibly later):
  // 1. Don't use rich text: No <qt><b>...</b></qt>
  label = new TQLabel( i18n("Please check if encryption really "
  	"works before you start using it seriously. Also note that attachments "
	"are not encrypted by the PGP/GPG module."), group );
  // 2. instead, set the font to bold:
  TQFont labelFont = label->font();
  labelFont.setBold( true );
  label->setFont( labelFont );
  // 3. and activate wordwarp:
  label->setAlignment( AlignLeft|WordBreak );
  // end; to remove the workaround, add <qt><b>..</b></qt> around the
  // text and remove lines TQFont... -> label->setAlignment(...).
  topLayout->addWidget( group );

  group = new TQVGroupBox( i18n("Encryption Tool"), this );
  group->layout()->setSpacing( KDialog::spacingHint() );

  TQHBox * hbox = new TQHBox( group );
  label = new TQLabel( i18n("Select encryption tool to &use:"), hbox );
  toolCombo = new TQComboBox( false, hbox );
  toolCombo->insertStringList( TQStringList()
			       << i18n("Autodetect")
			       << i18n("GnuPG - Gnu Privacy Guard")
			       << i18n("PGP Version 2.x")
			       << i18n("PGP Version 5.x")
			       << i18n("PGP Version 6.x")
			       << i18n("Do not use any encryption tool") );
  label->setBuddy( toolCombo );
  hbox->setStretchFactor( toolCombo, 1 );
  connect( toolCombo, TQT_SIGNAL( activated( int ) ),
           this, TQT_SIGNAL( changed( void ) ) );
  // This is the place to add a KURLRequester to be used for asking
  // the user for the path to the executable...
  topLayout->addWidget( group );

  mpOptionsGroupBox = new TQVGroupBox( i18n("Options"), this );
  mpOptionsGroupBox->layout()->setSpacing( KDialog::spacingHint() );
  storePass = new TQCheckBox( i18n("&Keep passphrase in memory"),
                             mpOptionsGroupBox );
  connect( storePass, TQT_SIGNAL( toggled( bool ) ),
           this, TQT_SIGNAL( changed( void ) ) );
  msg = i18n( "<qt><p>When this option is enabled, the passphrase of your "
	      "private key will be remembered by the application as long "
	      "as the application is running. Thus you will only have to "
	      "enter the passphrase once.</p><p>Be aware that this could be a "
	      "security risk. If you leave your computer, others "
	      "can use it to send signed messages and/or read your encrypted "
	      "messages. If a core dump occurs, the contents of your RAM will "
	      "be saved onto disk, including your passphrase.</p>"
	      "<p>Note that when using KMail, this setting only applies "
	      "if you are not using gpg-agent. It is also ignored "
	      "if you are using crypto plugins.</p></qt>" );
  TQWhatsThis::add( storePass, msg );
  if( encrypt ) {
    encToSelf = new TQCheckBox( i18n("Always encr&ypt to self"),
                               mpOptionsGroupBox );
   connect( encToSelf, TQT_SIGNAL( toggled( bool ) ),
           this, TQT_SIGNAL( changed( void ) ) );

    msg = i18n( "<qt><p>When this option is enabled, the message/file "
		"will not only be encrypted with the receiver's public key, "
		"but also with your key. This will enable you to decrypt the "
		"message/file at a later time. This is generally a good idea."
		"</p></qt>" );
    TQWhatsThis::add( encToSelf, msg );
  }
  else
    encToSelf = 0;
  showCipherText = new TQCheckBox( i18n("&Show signed/encrypted text after "
                                       "composing"),
                                  mpOptionsGroupBox );
  connect( showCipherText, TQT_SIGNAL( toggled( bool ) ),
           this, TQT_SIGNAL( changed( void ) ) );

  msg = i18n( "<qt><p>When this option is enabled, the signed/encrypted text "
	      "will be shown in a separate window, enabling you to know how "
	      "it will look before it is sent. This is a good idea when "
	      "you are verifying that your encryption system works.</p></qt>" );
  TQWhatsThis::add( showCipherText, msg );
  if( encrypt ) {
    showKeyApprovalDlg = new TQCheckBox( i18n("Always show the encryption "
                                             "keys &for approval"),
                                        mpOptionsGroupBox );
    connect( showKeyApprovalDlg, TQT_SIGNAL( toggled( bool ) ),
           this, TQT_SIGNAL( changed( void ) ) );
    msg = i18n( "<qt><p>When this option is enabled, the application will "
		"always show you a list of public keys from which you can "
		"choose the one it will use for encryption. If it is off, "
		"the application will only show the dialog if it cannot find "
		"the right key or if there are several which could be used. "
		"</p></qt>" );
    TQWhatsThis::add( showKeyApprovalDlg, msg );
}
  else
    showKeyApprovalDlg = 0;

  topLayout->addWidget( mpOptionsGroupBox );

  topLayout->addStretch(1);

  setValues();  // is this needed by KNode, b/c for KMail, it's not.
}


Config::~Config()
{
}

void
Config::setValues()
{
  // set default values
  storePass->setChecked( pgp->storePassPhrase() );
  if( 0 != encToSelf )
    encToSelf->setChecked( pgp->encryptToSelf() );
  showCipherText->setChecked( pgp->showCipherText() );
  if( 0 != showKeyApprovalDlg )
    showKeyApprovalDlg->setChecked( pgp->showKeyApprovalDlg() );

  int type = 0;
  switch (pgp->pgpType) {
    // translate Kpgp::Module enum to combobox' entries:
  default:
  case Module::tAuto: type = 0; break;
  case Module::tGPG:  type = 1; break;
  case Module::tPGP2: type = 2; break;
  case Module::tPGP5: type = 3; break;
  case Module::tPGP6: type = 4; break;
  case Module::tOff:  type = 5; break;
  }
  toolCombo->setCurrentItem( type );
}

void
Config::applySettings()
{
  pgp->setStorePassPhrase(storePass->isChecked());
  if( 0 != encToSelf )
    pgp->setEncryptToSelf(encToSelf->isChecked());
  pgp->setShowCipherText(showCipherText->isChecked());
  if( 0 != showKeyApprovalDlg )
    pgp->setShowKeyApprovalDlg( showKeyApprovalDlg->isChecked() );

  Module::PGPType type;
  switch ( toolCombo->currentItem() ) {
    // convert combobox entry indices to Kpgp::Module constants:
  default:
  case 0: type = Module::tAuto; break;
  case 1: type = Module::tGPG;  break;
  case 2: type = Module::tPGP2; break;
  case 3: type = Module::tPGP5; break;
  case 4: type = Module::tPGP6; break;
  case 5: type = Module::tOff;  break;
  }
  pgp->pgpType = type;

  pgp->writeConfig(true);
}



// ------------------------------------------------------------------------
KeySelectionDialog::KeySelectionDialog( const KeyList& keyList,
                                        const TQString& title,
                                        const TQString& text,
                                        const KeyIDList& keyIds,
                                        const bool rememberChoice,
                                        const unsigned int allowedKeys,
                                        const bool extendedSelection,
                                        TQWidget *parent, const char *name,
                                        bool modal )
  : KDialogBase( parent, name, modal, title, Default|Ok|Cancel, Ok ),
    mRememberCB( 0 ),
    mAllowedKeys( allowedKeys ),
    mCurrentContextMenuItem( 0 )
{
  if ( kapp )
    KWin::setIcons( winId(), kapp->icon(), kapp->miniIcon() );
  Kpgp::Module *pgp = Kpgp::Module::getKpgp();
  KConfig *config = pgp->getConfig();
  KConfigGroup dialogConfig( config, "Key Selection Dialog" );

  TQSize defaultSize( 580, 400 );
  TQSize dialogSize = dialogConfig.readSizeEntry( "Dialog size", &defaultSize );

  resize( dialogSize );

  mCheckSelectionTimer = new TQTimer( this, "mCheckSelectionTimer" );
  mStartSearchTimer = new TQTimer( this, "mStartSearchTimer" );

  // load the key status icons
  mKeyGoodPix    = new TQPixmap( UserIcon("key_ok") );
  mKeyBadPix     = new TQPixmap( UserIcon("key_bad") );
  mKeyUnknownPix = new TQPixmap( UserIcon("key_unknown") );
  mKeyValidPix   = new TQPixmap( UserIcon("key") );

  TQFrame *page = makeMainWidget();
  TQVBoxLayout *topLayout = new TQVBoxLayout( page, 0, spacingHint() );

  if( !text.isEmpty() ) {
    TQLabel *label = new TQLabel( page );
    label->setText( text );
    topLayout->addWidget( label );
  }

  TQHBoxLayout * hlay = new TQHBoxLayout( topLayout ); // inherits spacing
  TQLineEdit * le = new TQLineEdit( page );
  hlay->addWidget( new TQLabel( le, i18n("&Search for:"), page ) );
  hlay->addWidget( le, 1 );
  le->setFocus();

  connect( le, TQT_SIGNAL(textChanged(const TQString&)),
	   this, TQT_SLOT(slotSearch(const TQString&)) );
  connect( mStartSearchTimer, TQT_SIGNAL(timeout()), TQT_SLOT(slotFilter()) );

  mListView = new KListView( page );
  mListView->addColumn( i18n("Key ID") );
  mListView->addColumn( i18n("User ID") );
  mListView->setAllColumnsShowFocus( true );
  mListView->setResizeMode( TQListView::LastColumn );
  mListView->setRootIsDecorated( true );
  mListView->setShowSortIndicator( true );
  mListView->setSorting( 1, true ); // sort by User ID
  mListView->setShowToolTips( true );
  if( extendedSelection ) {
    mListView->setSelectionMode( TQListView::Extended );
    //mListView->setSelectionMode( TQListView::Multi );
  }
  topLayout->addWidget( mListView, 10 );

  if (rememberChoice) {
    mRememberCB = new TQCheckBox( i18n("Remember choice"), page );
    topLayout->addWidget( mRememberCB );
    TQWhatsThis::add(mRememberCB,
                    i18n("<qt><p>If you check this box your choice will "
                         "be stored and you will not be asked again."
                         "</p></qt>"));
  }

  initKeylist( keyList, keyIds );

  TQListViewItem *lvi;
  if( extendedSelection ) {
    lvi = mListView->currentItem();
    slotCheckSelection();
  }
  else {
    lvi = mListView->selectedItem();
    slotCheckSelection( lvi );
  }
  // make sure that the selected item is visible
  // (ensureItemVisible(...) doesn't work correctly in TQt 3.0.0)
  if( lvi != 0 )
    mListView->center( mListView->contentsX(), mListView->itemPos( lvi ) );

  if( extendedSelection ) {
    connect( mCheckSelectionTimer, TQT_SIGNAL( timeout() ),
             this,                 TQT_SLOT( slotCheckSelection() ) );
    connect( mListView, TQT_SIGNAL( selectionChanged() ),
             this,      TQT_SLOT( slotSelectionChanged() ) );
  }
  else {
    connect( mListView, TQT_SIGNAL( selectionChanged( TQListViewItem* ) ),
             this,      TQT_SLOT( slotSelectionChanged( TQListViewItem* ) ) );
  }
  connect( mListView, TQT_SIGNAL( doubleClicked ( TQListViewItem *, const TQPoint &, int ) ), this, TQT_SLOT( accept() ) );

  connect( mListView, TQT_SIGNAL( contextMenuRequested( TQListViewItem*,
                                                    const TQPoint&, int ) ),
           this,      TQT_SLOT( slotRMB( TQListViewItem*, const TQPoint&, int ) ) );

  setButtonText( KDialogBase::Default, i18n("&Reread Keys") );
  connect( this, TQT_SIGNAL( defaultClicked() ),
           this, TQT_SLOT( slotRereadKeys() ) );
}


KeySelectionDialog::~KeySelectionDialog()
{
  Kpgp::Module *pgp = Kpgp::Module::getKpgp();
  KConfig *config = pgp->getConfig();
  KConfigGroup dialogConfig( config, "Key Selection Dialog" );
  dialogConfig.writeEntry( "Dialog size", size() );
  config->sync();
  delete mKeyGoodPix;
  delete mKeyBadPix;
  delete mKeyUnknownPix;
  delete mKeyValidPix;
}


KeyID KeySelectionDialog::key() const
{
  if( mListView->isMultiSelection() || mKeyIds.isEmpty() )
    return KeyID();
  else
    return mKeyIds.first();
}


void KeySelectionDialog::initKeylist( const KeyList& keyList,
                                      const KeyIDList& keyIds )
{
  TQListViewItem* firstSelectedItem = 0;
  mKeyIds.clear();
  mListView->clear();

  // build a list of all public keys
  for( KeyListIterator it( keyList ); it.current(); ++it ) {
    KeyID curKeyId = (*it)->primaryKeyID();

    TQListViewItem* primaryUserID = new TQListViewItem( mListView, curKeyId,
                                                      (*it)->primaryUserID() );

    // select and open the given key
    if( keyIds.findIndex( curKeyId ) != -1 ) {
      if( 0 == firstSelectedItem ) {
        firstSelectedItem = primaryUserID;
      }
      mListView->setSelected( primaryUserID, true );
      mKeyIds.append( curKeyId );
    }
    primaryUserID->setOpen( false );

    // set icon for this key
    switch( keyValidity( *it ) ) {
      case 0: // the key's validity can't be determined
        primaryUserID->setPixmap( 0, *mKeyUnknownPix );
        break;
      case 1: // key is valid but not trusted
        primaryUserID->setPixmap( 0, *mKeyValidPix );
        break;
      case 2: // key is valid and trusted
        primaryUserID->setPixmap( 0, *mKeyGoodPix );
        break;
      case -1: // key is invalid
        primaryUserID->setPixmap( 0, *mKeyBadPix );
        break;
    }

    TQListViewItem* childItem;

    childItem = new TQListViewItem( primaryUserID, "",
                                   i18n( "Fingerprint: %1" )
                                   .arg( beautifyFingerprint( (*it)->primaryFingerprint() ) ) );
    if( primaryUserID->isSelected() && mListView->isMultiSelection() ) {
      mListView->setSelected( childItem, true );
    }

    childItem = new TQListViewItem( primaryUserID, "", keyInfo( *it ) );
    if( primaryUserID->isSelected() && mListView->isMultiSelection() ) {
      mListView->setSelected( childItem, true );
    }

    UserIDList userIDs = (*it)->userIDs();
    UserIDListIterator uidit( userIDs );
    if( *uidit ) {
      ++uidit; // skip the primary user ID
      for( ; *uidit; ++uidit ) {
        childItem = new TQListViewItem( primaryUserID, "", (*uidit)->text() );
        if( primaryUserID->isSelected() && mListView->isMultiSelection() ) {
          mListView->setSelected( childItem, true );
        }
      }
    }
  }

  if( 0 != firstSelectedItem ) {
    mListView->setCurrentItem( firstSelectedItem );
  }
}


TQString KeySelectionDialog::keyInfo( const Kpgp::Key *key ) const
{
  TQString status, remark;
  if( key->revoked() ) {
    status = i18n("Revoked");
  }
  else if( key->expired() ) {
    status = i18n("Expired");
  }
  else if( key->disabled() ) {
    status = i18n("Disabled");
  }
  else if( key->invalid() ) {
    status = i18n("Invalid");
  }
  else {
    Validity keyTrust = key->keyTrust();
    switch( keyTrust ) {
    case KPGP_VALIDITY_UNDEFINED:
      status = i18n("Undefined trust");
      break;
    case KPGP_VALIDITY_NEVER:
      status = i18n("Untrusted");
      break;
    case KPGP_VALIDITY_MARGINAL:
      status = i18n("Marginally trusted");
      break;
    case KPGP_VALIDITY_FULL:
      status = i18n("Fully trusted");
      break;
    case KPGP_VALIDITY_ULTIMATE:
      status = i18n("Ultimately trusted");
      break;
    case KPGP_VALIDITY_UNKNOWN:
    default:
      status = i18n("Unknown");
    }
    if( key->secret() ) {
      remark = i18n("Secret key available");
    }
    else if( !key->canEncrypt() ) {
      remark = i18n("Sign only key");
    }
    else if( !key->canSign() ) {
      remark = i18n("Encryption only key");
    }
  }

  TQDateTime dt;
  dt.setTime_t( key->creationDate() );
  if( remark.isEmpty() ) {
    return " " + i18n("creation date and status of an OpenPGP key",
                      "Creation date: %1, Status: %2")
                     .arg( TDEGlobal::locale()->formatDate( dt.date(), true ) )
                     .arg( status );
  }
  else {
    return " " + i18n("creation date, status and remark of an OpenPGP key",
                      "Creation date: %1, Status: %2 (%3)")
                     .arg( TDEGlobal::locale()->formatDate( dt.date(), true ) )
                     .arg( status )
                     .arg( remark );
  }
}

TQString KeySelectionDialog::beautifyFingerprint( const TQCString& fpr ) const
{
  TQCString result;

  if( 40 == fpr.length() ) {
    // convert to this format:
    // 0000 1111 2222 3333 4444  5555 6666 7777 8888 9999
    result.fill( ' ', 50 );
    memcpy( result.data()     , fpr.data()     , 4 );
    memcpy( result.data() +  5, fpr.data() +  4, 4 );
    memcpy( result.data() + 10, fpr.data() +  8, 4 );
    memcpy( result.data() + 15, fpr.data() + 12, 4 );
    memcpy( result.data() + 20, fpr.data() + 16, 4 );
    memcpy( result.data() + 26, fpr.data() + 20, 4 );
    memcpy( result.data() + 31, fpr.data() + 24, 4 );
    memcpy( result.data() + 36, fpr.data() + 28, 4 );
    memcpy( result.data() + 41, fpr.data() + 32, 4 );
    memcpy( result.data() + 46, fpr.data() + 36, 4 );
  }
  else if( 32 == fpr.length() ) {
    // convert to this format:
    // 00 11 22 33 44 55 66 77  88 99 AA BB CC DD EE FF
    result.fill( ' ', 48 );
    memcpy( result.data()     , fpr.data()     , 2 );
    memcpy( result.data() +  3, fpr.data() +  2, 2 );
    memcpy( result.data() +  6, fpr.data() +  4, 2 );
    memcpy( result.data() +  9, fpr.data() +  6, 2 );
    memcpy( result.data() + 12, fpr.data() +  8, 2 );
    memcpy( result.data() + 15, fpr.data() + 10, 2 );
    memcpy( result.data() + 18, fpr.data() + 12, 2 );
    memcpy( result.data() + 21, fpr.data() + 14, 2 );
    memcpy( result.data() + 25, fpr.data() + 16, 2 );
    memcpy( result.data() + 28, fpr.data() + 18, 2 );
    memcpy( result.data() + 31, fpr.data() + 20, 2 );
    memcpy( result.data() + 34, fpr.data() + 22, 2 );
    memcpy( result.data() + 37, fpr.data() + 24, 2 );
    memcpy( result.data() + 40, fpr.data() + 26, 2 );
    memcpy( result.data() + 43, fpr.data() + 28, 2 );
    memcpy( result.data() + 46, fpr.data() + 30, 2 );
  }
  else { // unknown length of fingerprint
    result = fpr;
  }

  return result;
}

int KeySelectionDialog::keyValidity( const Kpgp::Key *key ) const
{
  if( 0 == key ) {
    return -1;
  }

  if( ( mAllowedKeys & EncrSignKeys ) == EncryptionKeys ) {
    // only encryption keys are allowed
    if( ( mAllowedKeys & ValidKeys ) && !key->isValidEncryptionKey() ) {
      // only valid encryption keys are allowed
      return -1;
    }
    else if( !key->canEncrypt() ) {
      return -1;
    }
  }
  else if( ( mAllowedKeys & EncrSignKeys ) == SigningKeys ) {
    // only signing keys are allowed
    if( ( mAllowedKeys & ValidKeys ) && !key->isValidSigningKey() ) {
      // only valid signing keys are allowed
      return -1;
    }
    else if( !key->canSign() ) {
      return -1;
    }
  }
  else if( ( mAllowedKeys & ValidKeys ) && !key->isValid() ) {
    // only valid keys are allowed
    return -1;
  }

  // check the key's trust
  int val = 0;
  Validity keyTrust = key->keyTrust();
  switch( keyTrust ) {
  case KPGP_VALIDITY_NEVER:
    val = -1;
    break;
  case KPGP_VALIDITY_MARGINAL:
  case KPGP_VALIDITY_FULL:
  case KPGP_VALIDITY_ULTIMATE:
    val = 2;
    break;
  case KPGP_VALIDITY_UNDEFINED:
    if( mAllowedKeys & TrustedKeys ) {
      // only trusted keys are allowed
      val = -1;
    }
    else {
      val = 1;
    }
    break;
  case KPGP_VALIDITY_UNKNOWN:
  default:
    val = 0;
  }

  return val;
}


void KeySelectionDialog::updateKeyInfo( const Kpgp::Key* key,
                                        TQListViewItem* lvi ) const
{
  if( 0 == lvi ) {
    return;
  }

  if( lvi->parent() != 0 ) {
    lvi = lvi->parent();
  }

  if( 0 == key ) {
    // the key doesn't exist anymore -> delete it from the list view
    while( lvi->firstChild() ) {
      kdDebug(5100) << "Deleting '" << lvi->firstChild()->text( 1 ) << "'\n";
      delete lvi->firstChild();
    }
    kdDebug(5100) << "Deleting key 0x" << lvi->text( 0 ) << " ("
                  << lvi->text( 1 ) << ")\n";
    delete lvi;
    lvi = 0;
    return;
  }

  // update the icon for this key
  switch( keyValidity( key ) ) {
  case 0: // the key's validity can't be determined
    lvi->setPixmap( 0, *mKeyUnknownPix );
    break;
  case 1: // key is valid but not trusted
    lvi->setPixmap( 0, *mKeyValidPix );
    break;
  case 2: // key is valid and trusted
    lvi->setPixmap( 0, *mKeyGoodPix );
    break;
  case -1: // key is invalid
    lvi->setPixmap( 0, *mKeyBadPix );
    break;
  }

  // update the key info for this key
  // the key info is identified by a leading space; this shouldn't be
  // a problem because User Ids shouldn't start with a space
  for( lvi = lvi->firstChild(); lvi; lvi = lvi->nextSibling() ) {
    if( lvi->text( 1 ).at(0) == ' ' ) {
      lvi->setText( 1, keyInfo( key ) );
      break;
    }
  }
}


int
KeySelectionDialog::keyAdmissibility( TQListViewItem* lvi,
                                      TrustCheckMode trustCheckMode ) const
{
  // Return:
  //  -1 = key must not be chosen,
  //   0 = not enough information to decide whether the give key is allowed
  //       or not,
  //   1 = key can be chosen

  if( mAllowedKeys == AllKeys ) {
    return 1;
  }

  Kpgp::Module *pgp = Kpgp::Module::getKpgp();

  if( 0 == pgp ) {
    return 0;
  }

  KeyID keyId = getKeyId( lvi );
  Kpgp::Key* key = pgp->publicKey( keyId );

  if( 0 == key ) {
    return 0;
  }

  int val = 0;
  if( trustCheckMode == ForceTrustCheck ) {
    key = pgp->rereadKey( keyId, true );
    updateKeyInfo( key, lvi );
    val = keyValidity( key );
  }
  else {
    val = keyValidity( key );
    if( ( trustCheckMode == AllowExpensiveTrustCheck ) && ( 0 == val ) ) {
      key = pgp->rereadKey( keyId, true );
      updateKeyInfo( key, lvi );
      val = keyValidity( key );
    }
  }

  switch( val ) {
  case -1: // key is not usable
    return -1;
    break;
  case 0: // key status unknown
    return 0;
    break;
  case 1: // key is valid, but untrusted
    if( mAllowedKeys & TrustedKeys ) {
      // only trusted keys are allowed
      return -1;
    }
    return 1;
    break;
  case 2: // key is trusted
    return 1;
    break;
  default:
    kdDebug( 5100 ) << "Error: Invalid key status value.\n";
  }

  return 0;
}


KeyID
KeySelectionDialog::getKeyId( const TQListViewItem* lvi ) const
{
  KeyID keyId;

  if( 0 != lvi ) {
    if( 0 != lvi->parent() ) {
      keyId = lvi->parent()->text(0).local8Bit();
    }
    else {
      keyId = lvi->text(0).local8Bit();
    }
  }

  return keyId;
}


void KeySelectionDialog::slotRereadKeys()
{
  Kpgp::Module *pgp = Kpgp::Module::getKpgp();

  if( 0 == pgp ) {
    return;
  }

  KeyList keys;

  if( PublicKeys & mAllowedKeys ) {
    pgp->readPublicKeys( true );
    keys = pgp->publicKeys();
  }
  else {
    pgp->readSecretKeys( true );
    keys = pgp->secretKeys();
  }

  // save the current position of the contents
  int offsetY = mListView->contentsY();

  if( mListView->isMultiSelection() ) {
    disconnect( mListView, TQT_SIGNAL( selectionChanged() ),
                this,      TQT_SLOT( slotSelectionChanged() ) );
  }
  else {
    disconnect( mListView, TQT_SIGNAL( selectionChanged( TQListViewItem * ) ),
                this,      TQT_SLOT( slotSelectionChanged( TQListViewItem * ) ) );
  }

  initKeylist( keys, KeyIDList( mKeyIds ) );
  slotFilter();

  if( mListView->isMultiSelection() ) {
    connect( mListView, TQT_SIGNAL( selectionChanged() ),
             this,      TQT_SLOT( slotSelectionChanged() ) );
    slotSelectionChanged();
  }
  else {
    connect( mListView, TQT_SIGNAL( selectionChanged( TQListViewItem * ) ),
             this,      TQT_SLOT( slotSelectionChanged( TQListViewItem * ) ) );
  }

  // restore the saved position of the contents
  mListView->setContentsPos( 0, offsetY );
}


void KeySelectionDialog::slotSelectionChanged( TQListViewItem * lvi )
{
  slotCheckSelection( lvi );
}


void KeySelectionDialog::slotSelectionChanged()
{
  kdDebug(5100) << "KeySelectionDialog::slotSelectionChanged()\n";

  // (re)start the check selection timer. Checking the selection is delayed
  // because else drag-selection doesn't work very good (checking key trust
  // is slow).
  mCheckSelectionTimer->start( sCheckSelectionDelay );
}


void KeySelectionDialog::slotCheckSelection( TQListViewItem* plvi /* = 0 */ )
{
  kdDebug(5100) << "KeySelectionDialog::slotCheckSelection()\n";

  if( !mListView->isMultiSelection() ) {
    mKeyIds.clear();
    KeyID keyId = getKeyId( plvi );
    if( !keyId.isEmpty() ) {
      mKeyIds.append( keyId );
      enableButtonOK( 1 == keyAdmissibility( plvi, AllowExpensiveTrustCheck ) );
    }
    else {
      enableButtonOK( false );
    }
  }
  else {
    mCheckSelectionTimer->stop();

    // As we might change the selection, we have to disconnect the slot
    // to prevent recursion
    disconnect( mListView, TQT_SIGNAL( selectionChanged() ),
                this,      TQT_SLOT( slotSelectionChanged() ) );

    KeyIDList newKeyIdList;
    TQValueList<TQListViewItem*> keysToBeChecked;

    bool keysAllowed = true;
    enum { UNKNOWN, SELECTED, DESELECTED } userAction = UNKNOWN;
    // Iterate over the tree to find selected keys.
    for( TQListViewItem *lvi = mListView->firstChild();
         0 != lvi;
         lvi = lvi->nextSibling() ) {
      // We make sure that either all items belonging to a key are selected
      // or unselected. As it's possible to select/deselect multiple keys at
      // once in extended selection mode we have to figure out whether the user
      // selected or deselected keys.

      // First count the selected items of this key
      int itemCount = 1 + lvi->childCount();
      int selectedCount = lvi->isSelected() ? 1 : 0;
      for( TQListViewItem *clvi = lvi->firstChild();
           0 != clvi;
           clvi = clvi->nextSibling() ) {
        if( clvi->isSelected() ) {
          ++selectedCount;
        }
      }

      if( userAction == UNKNOWN ) {
        // Figure out whether the user selected or deselected this key
        // Remark: A selected count of 0 doesn't mean anything since in
        //         extended selection mode a normal left click deselects
        //         the not clicked items.
        if( 0 < selectedCount ) {
          if( -1 == mKeyIds.findIndex( lvi->text(0).local8Bit() ) ) {
            // some items of this key are selected and the key wasn't selected
            // before => the user selected something
            kdDebug(5100) << "selectedCount: "<<selectedCount<<"/"<<itemCount
                          <<" --- User selected key "<<lvi->text(0)<<endl;
            userAction = SELECTED;
          }
          else if( ( itemCount > selectedCount ) &&
                   ( -1 != mKeyIds.findIndex( lvi->text(0).local8Bit() ) ) ) {
            // some items of this key are unselected and the key was selected
            // before => the user deselected something
            kdDebug(5100) << "selectedCount: "<<selectedCount<<"/"<<itemCount
                          <<" --- User deselected key "<<lvi->text(0)<<endl;
            userAction = DESELECTED;
          }
        }
      }
      if( itemCount == selectedCount ) {
        // add key to the list of selected keys
        KeyID keyId = lvi->text(0).local8Bit();
        newKeyIdList.append( keyId );
        int admissibility = keyAdmissibility( lvi, NoExpensiveTrustCheck );
        if( -1 == admissibility ) {
          keysAllowed = false;
        }
        else if ( 0 == admissibility ) {
          keysToBeChecked.append( lvi );
        }
      }
      else if( 0 < selectedCount ) {
        // not all items of this key are selected or unselected. change this
        // according to the user's action
        if( userAction == SELECTED ) {
          // select all items of this key
          mListView->setSelected( lvi, true );
          for( TQListViewItem *clvi = lvi->firstChild();
               0 != clvi;
               clvi = clvi->nextSibling() ) {
            mListView->setSelected( clvi, true );
          }
          // add key to the list of selected keys
          KeyID keyId = lvi->text(0).local8Bit();
          newKeyIdList.append( keyId );
          int admissibility = keyAdmissibility( lvi, NoExpensiveTrustCheck );
          if( -1 == admissibility ) {
            keysAllowed = false;
          }
          else if ( 0 == admissibility ) {
            keysToBeChecked.append( lvi );
          }
        }
        else { // userAction == DESELECTED
          // deselect all items of this key
          mListView->setSelected( lvi, false );
          for( TQListViewItem *clvi = lvi->firstChild();
               0 != clvi;
               clvi = clvi->nextSibling() ) {
            mListView->setSelected( clvi, false );
          }
        }
      }
    }
    kdDebug(5100) << "Selected keys: " << newKeyIdList.toStringList().join(", ") << endl;
    mKeyIds = newKeyIdList;
    if( !keysToBeChecked.isEmpty() ) {
      keysAllowed = keysAllowed && checkKeys( keysToBeChecked );
    }
    enableButtonOK( keysAllowed );

    connect( mListView, TQT_SIGNAL( selectionChanged() ),
             this,      TQT_SLOT( slotSelectionChanged() ) );
  }
}


bool KeySelectionDialog::checkKeys( const TQValueList<TQListViewItem*>& keys ) const
{
  KProgressDialog* pProgressDlg = 0;
  bool keysAllowed = true;
  kdDebug(5100) << "Checking keys...\n";

  pProgressDlg = new KProgressDialog( 0, 0, i18n("Checking Keys"),
                                      i18n("Checking key 0xMMMMMMMM..."),
                                      true );
  pProgressDlg->setAllowCancel( false );
  pProgressDlg->progressBar()->setTotalSteps( keys.count() );
  pProgressDlg->setMinimumDuration( 1000 );
  pProgressDlg->show();

  for( TQValueList<TQListViewItem*>::ConstIterator it = keys.begin();
       it != keys.end();
       ++it ) {
    kdDebug(5100) << "Checking key 0x" << getKeyId( *it ) << "...\n";
    pProgressDlg->setLabel( i18n("Checking key 0x%1...")
                            .arg( TQString( getKeyId( *it ) ) ) );
    kapp->processEvents();
    keysAllowed = keysAllowed && ( -1 != keyAdmissibility( *it, AllowExpensiveTrustCheck ) );
    pProgressDlg->progressBar()->advance( 1 );
    kapp->processEvents();
  }

  delete pProgressDlg;
  pProgressDlg = 0;

  return keysAllowed;
}


void KeySelectionDialog::slotRMB( TQListViewItem* lvi, const TQPoint& pos, int )
{
  if( !lvi ) {
    return;
  }

  mCurrentContextMenuItem = lvi;

  TQPopupMenu menu(this);
  menu.insertItem( i18n( "Recheck Key" ), this, TQT_SLOT( slotRecheckKey() ) );
  menu.exec( pos );
}


void KeySelectionDialog::slotRecheckKey()
{
  if( 0 != mCurrentContextMenuItem ) {
    // force rereading the key
    keyAdmissibility( mCurrentContextMenuItem, ForceTrustCheck );
    // recheck the selection
    slotCheckSelection( mCurrentContextMenuItem );
  }
}

void KeySelectionDialog::slotOk()
{
  if( mCheckSelectionTimer->isActive() ) {
    slotCheckSelection();
  }
  mStartSearchTimer->stop();
  accept();
}


void KeySelectionDialog::slotCancel()
{
  mCheckSelectionTimer->stop();
  mStartSearchTimer->stop();
  mKeyIds.clear();
  reject();
}

void KeySelectionDialog::slotSearch( const TQString & text )
{
  mSearchText = text.stripWhiteSpace().upper();
  mStartSearchTimer->start( sCheckSelectionDelay, true /*single-shot*/ );
}

void KeySelectionDialog::slotFilter()
{
  if ( mSearchText.isEmpty() ) {
    showAllItems();
    return;
  }

  // OK, so we need to filter:
  TQRegExp keyIdRegExp( "(?:0x)?[A-F0-9]{1,8}", false /*case-insens.*/ );
  if ( keyIdRegExp.exactMatch( mSearchText ) ) {
    if ( mSearchText.startsWith( "0X" ) )
      // search for keyID only:
      filterByKeyID( mSearchText.mid( 2 ) );
    else
      // search for UID and keyID:
      filterByKeyIDOrUID( mSearchText );
  } else {
    // search in UID:
    filterByUID( mSearchText );
  }
}

void KeySelectionDialog::filterByKeyID( const TQString & keyID )
{
  assert( keyID.length() <= 8 );
  assert( !keyID.isEmpty() ); // regexp in slotFilter should prevent these
  if ( keyID.isEmpty() )
    showAllItems();
  else
    for ( TQListViewItem * item = mListView->firstChild() ; item ; item = item->nextSibling() )
      item->setVisible( item->text( 0 ).upper().startsWith( keyID ) );
}

void KeySelectionDialog::filterByKeyIDOrUID( const TQString & str )
{
  assert( !str.isEmpty() );

  // match beginnings of words:
  TQRegExp rx( "\\b" + TQRegExp::escape( str ), false );

  for ( TQListViewItem * item = mListView->firstChild() ; item ; item = item->nextSibling() )
    item->setVisible( item->text( 0 ).upper().startsWith( str )
		      || rx.search( item->text( 1 ) ) >= 0
		      || anyChildMatches( item, rx ) );

}

void KeySelectionDialog::filterByUID( const TQString & str )
{
  assert( !str.isEmpty() );

  // match beginnings of words:
  TQRegExp rx( "\\b" + TQRegExp::escape( str ), false );

  for ( TQListViewItem * item = mListView->firstChild() ; item ; item = item->nextSibling() )
    item->setVisible( rx.search( item->text( 1 ) ) >= 0
		      || anyChildMatches( item, rx ) );
}


bool KeySelectionDialog::anyChildMatches( const TQListViewItem * item, TQRegExp & rx ) const
{
  if ( !item )
    return false;

  TQListViewItem * stop = item->nextSibling(); // It's OK if stop is NULL...

  for ( TQListViewItemIterator it( item->firstChild() ) ; it.current() && it.current() != stop ; ++it )
    if ( rx.search( it.current()->text( 1 ) ) >= 0 ) {
      //item->setOpen( true ); // do we want that?
      return true;
    }
  return false;
}

void KeySelectionDialog::showAllItems()
{
  for ( TQListViewItem * item = mListView->firstChild() ; item ; item = item->nextSibling() )
    item->setVisible( true );
}

// ------------------------------------------------------------------------
KeyRequester::KeyRequester( TQWidget * parent, bool multipleKeys,
			    unsigned int allowedKeys, const char * name )
  : TQWidget( parent, name ),
    mDialogCaption( i18n("OpenPGP Key Selection") ),
    mDialogMessage( i18n("Please select an OpenPGP key to use.") ),
    mMulti( multipleKeys ),
    mAllowedKeys( allowedKeys ),
    d( 0 )
{
  TQHBoxLayout * hlay = new TQHBoxLayout( this, 0, KDialog::spacingHint() );

  // the label where the key id is to be displayed:
  mLabel = new TQLabel( this );
  mLabel->setFrameStyle( TQFrame::Panel | TQFrame::Sunken );

  // the button to unset any key:
  mEraseButton = new TQPushButton( this );
  mEraseButton->setAutoDefault( false );
  mEraseButton->setSizePolicy( TQSizePolicy( TQSizePolicy::Minimum,
					    TQSizePolicy::Minimum ) );
  mEraseButton->setPixmap( SmallIcon( "clear_left" ) );
  TQToolTip::add( mEraseButton, i18n("Clear") );

  // the button to call the KeySelectionDialog:
  mDialogButton = new TQPushButton( i18n("Change..."), this );
  mDialogButton->setAutoDefault( false );

  hlay->addWidget( mLabel, 1 );
  hlay->addWidget( mEraseButton );
  hlay->addWidget( mDialogButton );

  connect( mEraseButton, TQT_SIGNAL(clicked()), TQT_SLOT(slotEraseButtonClicked()) );
  connect( mDialogButton, TQT_SIGNAL(clicked()), TQT_SLOT(slotDialogButtonClicked()) );

  setSizePolicy( TQSizePolicy( TQSizePolicy::MinimumExpanding,
			      TQSizePolicy::Fixed ) );
}

KeyRequester::~KeyRequester() {

}

KeyIDList KeyRequester::keyIDs() const {
  return mKeys;
}

void KeyRequester::setKeyIDs( const KeyIDList & keyIDs ) {
  mKeys = keyIDs;
  if ( mKeys.empty() ) {
    mLabel->clear();
    return;
  }
  if ( mKeys.size() > 1 )
    setMultipleKeysEnabled( true );

  TQString s = mKeys.toStringList().join(", ");

  mLabel->setText( s );
  TQToolTip::remove( mLabel );
  TQToolTip::add( mLabel, s );
}

void KeyRequester::slotDialogButtonClicked() {
  Module * pgp = Module::getKpgp();

  if ( !pgp ) {
    kdWarning() << "Kpgp::KeyRequester::slotDialogButtonClicked(): No pgp module found!" << endl;
    return;
  }

  setKeyIDs( keyRequestHook( pgp ) );
  emit changed();
}

void KeyRequester::slotEraseButtonClicked() {
  mKeys.clear();
  mLabel->clear();
  emit changed();
}

void KeyRequester::setDialogCaption( const TQString & caption ) {
  mDialogCaption = caption;
}

void KeyRequester::setDialogMessage( const TQString & msg ) {
  mDialogMessage = msg;
}

bool KeyRequester::isMultipleKeysEnabled() const {
  return mMulti;
}

void KeyRequester::setMultipleKeysEnabled( bool multi ) {
  if ( multi == mMulti ) return;

  if ( !multi && mKeys.size() > 1 )
    mKeys.erase( ++mKeys.begin(), mKeys.end() );

  mMulti = multi;
}

int KeyRequester::allowedKeys() const {
  return mAllowedKeys;
}

void KeyRequester::setAllowedKeys( int allowedKeys ) {
  mAllowedKeys = allowedKeys;
}


PublicKeyRequester::PublicKeyRequester( TQWidget * parent, bool multi,
					unsigned int allowed, const char * name )
  : KeyRequester( parent, multi, allowed & ~SecretKeys, name )
{

}

PublicKeyRequester::~PublicKeyRequester() {

}

KeyIDList PublicKeyRequester::keyRequestHook( Module * pgp ) const {
  assert( pgp );
  return pgp->selectPublicKeys( mDialogCaption, mDialogMessage, mKeys, TQString(), mAllowedKeys );
}

SecretKeyRequester::SecretKeyRequester( TQWidget * parent, bool multi,
					unsigned int allowed, const char * name )
  : KeyRequester( parent, multi, allowed & ~PublicKeys, name )
{

}

SecretKeyRequester::~SecretKeyRequester() {

}

KeyIDList SecretKeyRequester::keyRequestHook( Module * pgp ) const {
  assert( pgp );

  KeyID keyID = mKeys.first();
  keyID = pgp->selectSecretKey( mDialogCaption, mDialogMessage, keyID );

  return KeyIDList() << keyID;
}



// ------------------------------------------------------------------------
KeyApprovalDialog::KeyApprovalDialog( const TQStringList& addresses,
                                      const TQValueVector<KeyIDList>& keyIDs,
                                      const int allowedKeys,
                                      TQWidget *parent, const char *name,
                                      bool modal )
  : KDialogBase( parent, name, modal, i18n("Encryption Key Approval"),
                 Ok|Cancel, Ok ),
    mKeys( keyIDs ),
    mAllowedKeys( allowedKeys ),
    mPrefsChanged( false )
{
  Kpgp::Module *pgp = Kpgp::Module::getKpgp();

  if( pgp == 0 )
    return;

  // ##### error handling
  // if( addresses.isEmpty() || keyList.isEmpty() ||
  //     addresses.count()+1 != keyList.count() )
  //   do something;

  TQFrame *page = makeMainWidget();
  TQVBoxLayout *topLayout = new TQVBoxLayout( page, 0, KDialog::spacingHint() );

  TQLabel *label = new TQLabel( i18n("The following keys will be used for "
                                   "encryption:"),
                              page );
  topLayout->addWidget( label );

  TQScrollView* sv = new TQScrollView( page );
  sv->setResizePolicy( TQScrollView::AutoOneFit );
  topLayout->addWidget( sv );
  TQVBox* bigvbox = new TQVBox( sv->viewport() );
  bigvbox->setMargin( KDialog::marginHint() );
  bigvbox->setSpacing( KDialog::spacingHint() );
  sv->addChild( bigvbox );

  TQButtonGroup *mChangeButtonGroup = new TQButtonGroup( bigvbox );
  mChangeButtonGroup->hide();
  mAddressLabels.resize( addresses.count() );
  mKeyIdsLabels.resize( keyIDs.size() );
  //mKeyIdListBoxes.resize( keyIDs.size() );
  mEncrPrefCombos.resize( addresses.count() );

  // the sender's key
  if( pgp->encryptToSelf() ) {
    mEncryptToSelf = 1;
    TQHBox* hbox = new TQHBox( bigvbox );
    new TQLabel( i18n("Your keys:"), hbox );
    TQLabel* keyidsL = new TQLabel( hbox );
    if( keyIDs[0].isEmpty() ) {
      keyidsL->setText( i18n("<none> means 'no key'", "<none>") );
    }
    else {
      keyidsL->setText( "0x" + keyIDs[0].toStringList().join( "\n0x" ) );
    }
    keyidsL->setFrameStyle( TQFrame::Panel | TQFrame::Sunken );
    /*
    TQListBox* keyidLB = new TQListBox( hbox );
    if( keyIDs[0].isEmpty() ) {
      keyidLB->insertItem( i18n("<none>") );
    }
    else {
      keyidLB->insertStringList( keyIDs[0].toStringList() );
    }
    keyidLB->setSelectionMode( TQListBox::NoSelection );
    keyidLB->setFrameStyle( TQFrame::Panel | TQFrame::Sunken );
    */
    TQPushButton *button = new TQPushButton( i18n("Change..."), hbox );
    mChangeButtonGroup->insert( button );
    button->setAutoDefault( false );
    hbox->setStretchFactor( keyidsL, 10 );
    mKeyIdsLabels.insert( 0, keyidsL );
    //hbox->setStretchFactor( keyidLB, 10 );
    //mKeyIdListBoxes.insert( 0, keyidLB );

    new KSeparator( Qt::Horizontal, bigvbox );
  }
  else {
    mEncryptToSelf = 0;
    // insert dummy KeyIdListBox
    mKeyIdsLabels.insert( 0, 0 );
    //mKeyIdListBoxes.insert( 0, 0 );
  }

  TQStringList::ConstIterator ait;
  TQValueVector<KeyIDList>::const_iterator kit;
  int i;
  for( ait = addresses.begin(), kit = keyIDs.begin(), i = 0;
       ( ait != addresses.end() ) && ( kit != keyIDs.end() );
       ++ait, ++kit, ++i ) {
    if( i == 0 ) {
      ++kit; // skip the sender's key id
    }
    else {
      new KSeparator( Qt::Horizontal, bigvbox );
    }

    TQHBox *hbox = new TQHBox( bigvbox );
    new TQLabel( i18n("Recipient:"), hbox );
    TQLabel *addressL = new TQLabel( *ait, hbox );
    hbox->setStretchFactor( addressL, 10 );
    mAddressLabels.insert( i, addressL  );

    hbox = new TQHBox( bigvbox );
    new TQLabel( i18n("Encryption keys:"), hbox );
    TQLabel* keyidsL = new TQLabel( hbox );
    if( (*kit).isEmpty() ) {
      keyidsL->setText( i18n("<none> means 'no key'", "<none>") );
    }
    else {
      keyidsL->setText( "0x" + (*kit).toStringList().join( "\n0x" ) );
    }
    keyidsL->setFrameStyle( TQFrame::Panel | TQFrame::Sunken );
    /*
    TQListBox* keyidLB = new TQListBox( hbox );
    if( (*kit).isEmpty() ) {
      keyidLB->insertItem( i18n("<none>") );
    }
    else {
      keyidLB->insertStringList( (*kit).toStringList() );
    }
    keyidLB->setSelectionMode( TQListBox::NoSelection );
    keyidLB->setFrameStyle( TQFrame::Panel | TQFrame::Sunken );
    */
    TQPushButton *button = new TQPushButton( i18n("Change..."), hbox );
    mChangeButtonGroup->insert( button );
    button->setAutoDefault( false );
    hbox->setStretchFactor( keyidsL, 10 );
    mKeyIdsLabels.insert( i + 1, keyidsL );
    //hbox->setStretchFactor( keyidLB, 10 );
    //mKeyIdListBoxes.insert( i + 1, keyidLB );

    hbox = new TQHBox( bigvbox );
    new TQLabel( i18n("Encryption preference:"), hbox );
    TQComboBox *encrPrefCombo = new TQComboBox( hbox );
    encrPrefCombo->insertItem( i18n("<none>") );
    encrPrefCombo->insertItem( i18n("Never Encrypt with This Key") );
    encrPrefCombo->insertItem( i18n("Always Encrypt with This Key") );
    encrPrefCombo->insertItem( i18n("Encrypt Whenever Encryption is Possible") );
    encrPrefCombo->insertItem( i18n("Always Ask") );
    encrPrefCombo->insertItem( i18n("Ask Whenever Encryption is Possible") );

    EncryptPref encrPref = pgp->encryptionPreference( *ait );
    switch( encrPref ) {
      case NeverEncrypt:
        encrPrefCombo->setCurrentItem( 1 );
        break;
      case AlwaysEncrypt:
        encrPrefCombo->setCurrentItem( 2 );
        break;
      case AlwaysEncryptIfPossible:
        encrPrefCombo->setCurrentItem( 3 );
        break;
      case AlwaysAskForEncryption:
        encrPrefCombo->setCurrentItem( 4 );
        break;
      case AskWheneverPossible:
        encrPrefCombo->setCurrentItem( 5 );
        break;
      default:
        encrPrefCombo->setCurrentItem( 0 );
    }
    connect( encrPrefCombo, TQT_SIGNAL(activated(int)),
             this, TQT_SLOT(slotPrefsChanged(int)) );
    mEncrPrefCombos.insert( i, encrPrefCombo );
  }
  connect( mChangeButtonGroup, TQT_SIGNAL(clicked(int)),
           this, TQT_SLOT(slotChangeEncryptionKey(int)) );

  // calculate the optimal width for the dialog
  int dialogWidth = marginHint()
                  + sv->frameWidth()
                  + bigvbox->sizeHint().width()
                  + sv->verticalScrollBar()->sizeHint().width()
                  + sv->frameWidth()
                  + marginHint()
                  + 2;
  // calculate the optimal height for the dialog
  int dialogHeight = marginHint()
                   + label->sizeHint().height()
                   + topLayout->spacing()
                   + sv->frameWidth()
                   + bigvbox->sizeHint().height()
                   + sv->horizontalScrollBar()->sizeHint().height()
                   + sv->frameWidth()
                   + topLayout->spacing()
                   + actionButton( KDialogBase::Cancel )->sizeHint().height()
                   + marginHint()
                   + 2;
  // don't make the dialog too large
  TQRect desk = TDEGlobalSettings::desktopGeometry(this);
  int screenWidth = desk.width();
  if( dialogWidth > 3*screenWidth/4 )
    dialogWidth = 3*screenWidth/4;
  int screenHeight = desk.height();
  if( dialogHeight > 7*screenHeight/8 )
    dialogHeight = 7*screenHeight/8;

  setInitialSize( TQSize( dialogWidth, dialogHeight ) );
}

void
KeyApprovalDialog::slotChangeEncryptionKey( int nr )
{
  Kpgp::Module *pgp = Kpgp::Module::getKpgp();

  kdDebug(5100)<<"Key approval dialog size is "
               <<width()<<"x"<<height()<<endl;

  if( pgp == 0 )
    return;

  if( !mEncryptToSelf )
    nr++;
  KeyIDList keyIds = mKeys[nr];
  if( nr == 0 ) {
    keyIds = pgp->selectPublicKeys( i18n("Encryption Key Selection"),
                                    i18n("if in your language something like "
                                         "'key(s)' isn't possible please "
                                         "use the plural in the translation",
                                         "Select the key(s) which should "
                                         "be used to encrypt the message "
                                         "to yourself."),
                                    keyIds,
                                    "",
                                    mAllowedKeys );
  }
  else {
    keyIds = pgp->selectPublicKeys( i18n("Encryption Key Selection"),
                                    i18n("if in your language something like "
                                         "'key(s)' isn't possible please "
                                         "use the plural in the translation",
                                         "Select the key(s) which should "
                                         "be used to encrypt the message "
                                         "for\n%1")
                                    .arg( mAddressLabels[nr-1]->text() ),
                                    keyIds,
                                    mAddressLabels[nr-1]->text(),
                                    mAllowedKeys );
  }
  if( !keyIds.isEmpty() ) {
    mKeys[nr] = keyIds;
    TQLabel* keyidsL = mKeyIdsLabels[nr];
    keyidsL->setText( "0x" + keyIds.toStringList().join( "\n0x" ) );
    /*
    TQListBox* qlb = mKeyIdListBoxes[nr];
    qlb->clear();
    qlb->insertStringList( keyIds.toStringList() );
    */
  }
}


void
KeyApprovalDialog::slotOk()
{
  Kpgp::Module *pgp = Kpgp::Module::getKpgp();

  if( pgp == 0 ) {
    accept();
    return;
  }

  if( mPrefsChanged ) {
    // store the changed preferences
    for( unsigned int i = 0; i < mAddressLabels.size(); i++ ) {
      // traverse all Address and Encryption Preference widgets
      EncryptPref encrPref;
      switch( mEncrPrefCombos[i]->currentItem() ) {
        case 1:
          encrPref = NeverEncrypt;
          break;
        case 2:
          encrPref = AlwaysEncrypt;
          break;
        case 3:
          encrPref = AlwaysEncryptIfPossible;
          break;
        case 4:
          encrPref = AlwaysAskForEncryption;
          break;
        case 5:
          encrPref = AskWheneverPossible;
          break;
        default:
        case 0:
          encrPref = UnknownEncryptPref;
      }
      pgp->setEncryptionPreference( mAddressLabels[i]->text(), encrPref );
    }
  }

  accept();
}


void
KeyApprovalDialog::slotCancel()
{
  reject();
}



// ------------------------------------------------------------------------
CipherTextDialog::CipherTextDialog( const TQCString & text,
                                    const TQCString & charset, TQWidget *parent,
                                    const char *name, bool modal )
  :KDialogBase( parent, name, modal, i18n("OpenPGP Information"), Ok|Cancel, Ok)
{
  // FIXME (post KDE2.2): show some more info, e.g. the output of GnuPG/PGP
  TQFrame *page = makeMainWidget();
  TQVBoxLayout *topLayout = new TQVBoxLayout( page, 0, spacingHint() );

  TQLabel *label = new TQLabel( page );
  label->setText(i18n("Result of the last encryption/sign operation:"));
  topLayout->addWidget( label );

  mEditBox = new TQMultiLineEdit( page );
  mEditBox->setReadOnly(true);
  topLayout->addWidget( mEditBox, 10 );

  TQString unicodeText;
  if (charset.isEmpty())
    unicodeText = TQString::fromLocal8Bit(text.data());
  else {
    bool ok=true;
    TQTextCodec *codec = TDEGlobal::charsets()->codecForName(charset, ok);
    if(!ok)
      unicodeText = TQString::fromLocal8Bit(text.data());
    else
      unicodeText = codec->toUnicode(text.data(), text.length());
  }

  mEditBox->setText(unicodeText);

  setMinimumSize();
}

void CipherTextDialog::setMinimumSize()
{
  // this seems to force a layout of the entire document, so we get a
  // a proper contentsWidth(). Is there a better way?
  for ( int i = 0; i < mEditBox->paragraphs(); i++ )
      (void) mEditBox->paragraphRect( i );

  mEditBox->setMinimumHeight( mEditBox->fontMetrics().lineSpacing() * 25 );

  int textWidth = mEditBox->contentsWidth() + 30;


#if KDE_IS_VERSION( 3, 1, 90 )
  int maxWidth = TDEGlobalSettings::desktopGeometry(parentWidget()).width()-100;
#else
  KConfig gc("kdeglobals", false, false);
  gc.setGroup("Windows");
  int maxWidth;
  if (TQApplication::desktop()->isVirtualDesktop() &&
      gc.readBoolEntry("XineramaEnabled", true) &&
      gc.readBoolEntry("XineramaPlacementEnabled", true)) {
    maxWidth = TQApplication::desktop()->screenGeometry(TQApplication::desktop()->screenNumber(parentWidget())).width()-100;
  } else {
    maxWidth = TQApplication::desktop()->geometry().width()-100;
  }
#endif

  mEditBox->setMinimumWidth( TQMIN( textWidth, maxWidth ) );
}

void KeyRequester::virtual_hook( int, void* ) {}

void PublicKeyRequester::virtual_hook( int id, void* data ) {
  base::virtual_hook( id, data );
}

void SecretKeyRequester::virtual_hook( int id, void* data ) {
  base::virtual_hook( id, data );
}

} // namespace Kpgp



#include "kpgpui.moc"