File: controller.cpp

package info (click to toggle)
classified-ads 0.13-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 6,772 kB
  • sloc: cpp: 34,291; tcl: 1,175; xml: 64; makefile: 40
file content (1632 lines) | stat: -rw-r--r-- 64,828 bytes parent folder | download
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
/*     -*-C++-*- -*-coding: utf-8-unix;-*-
  Classified Ads is Copyright (c) Antti Järvinen 2013-2017.

  This file is part of Classified Ads.

  Classified Ads is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  Classified Ads is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with Classified Ads; if not, write to the Free Software
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/

#include <QtGui>
#include <QMenuBar>
#include <QMainWindow>
#include <QMenu>
#include <QMessageBox>
#include <QProgressDialog>
#include <QErrorMessage>
#include <QSharedMemory>
#ifdef WIN32
#include <QLocalServer>
#include <QLocalSocket>
#endif
#include <QFileDialog>
#include "controller.h"
#include "FrontWidget.h"
#include "log.h"
#include "net/node.h"
#include "datamodel/model.h"
#include "datamodel/contentencryptionmodel.h"
#include "net/networklistener.h"
#include "net/networkconnectorengine.h"
#include "net/publishingengine.h"
#include "net/retrievalengine.h"
#include "net/dbretrievalengine.h"
#ifndef WIN32
#include <unistd.h> // for getpid() 
#endif
#include <signal.h>
#include "ui/passwd_dialog.h"
#include <assert.h>
#include "datamodel/profile.h"
#include "datamodel/profilemodel.h"
#include "datamodel/profilecommentmodel.h"
#include "ui/settings.h"
#include "ui/status.h"
#include "ui/aboutdialog.h"
#include "ui/searchdisplay.h"
#include "datamodel/searchmodel.h"
#include "datamodel/profile.h"
#include "datamodel/profilecomment.h"
#include "datamodel/trusttreemodel.h"
#include "datamodel/binaryfile.h"
#include "net/voicecallengine.h"
#include "datamodel/voicecall.h"
#include "ui/tclPrograms.h"
#include "tcl/tclWrapper.h"

static const char *KPrivateDataContactsSection = "contacts" ;
static const char *KPrivateDataContactsCache = "contactsCache" ;
static const char *KPrivateDataTrustTree = "trustTree" ;

Controller::Controller(QApplication &app) : iWin(NULL),
    iCurrentWidget(NULL),
    iApp ( app ) ,
    iLayout (NULL),
    iFileMenu(NULL),
    iExitAct(NULL),
    iAboutAct(NULL),
    iPwdChangeAct(NULL),
    iProfileDeleteAct(NULL),
    iProfileCreateAct(NULL),
    iProfileSelectAct(NULL),
    iDisplaySettingsAct(NULL),
    iDisplayStatusAct(NULL),
    iDisplaySearchAct(NULL),
    iTclMenu(NULL),
    iTclLibraryAct(NULL),
    iTclConsoleAct(NULL),
    iNode(NULL),
    iModel(NULL),
    iListener(NULL),
    iNetEngine(NULL),
    iPubEngine(NULL),
    iRetrievalEngine(NULL),
    iDbRetrievalEngine(NULL),
    iVoiceCallEngine (NULL),
    iInsideDestructor(false),
    iSharedMemory(NULL),
#ifdef WIN32
    iLocalServer(NULL),
#endif
    iTclWrapper(NULL),
    iGetFileNameDialog(NULL),
    iGetFileNameSemaphore(1) {
    LOG_STR("Controller::Controller constructor out") ;
}

bool Controller::init() {
    QLOG_STR("Controller::init in") ;
#ifndef WIN32
    int pid ;
    if ( ( pid =  createPidFile() ) != -1 ) {
        // there is old instance, if we have url to open, put it into shared memory
        QString sharedMemName ( QString("classified-ads-")
                                + QString::number(pid) ) ;
        if ( createSharedMemSegment(sharedMemName) == false ) {
            return false ;
        }
        // segment before signaling the previously opened instance:
        LOG_STR2("Signaling old instance %d", pid) ;
        if ( kill(pid, SIGUSR2) != -1 ) {
            // was success
            kill(getpid(), SIGINT) ; // then signal this instance to go away..
            LOG_STR("Instance signaled ") ;
            return  false   ;
        } else {
            // the process did not exist..
            LOG_STR("But process was not there?") ;
            deletePidFile() ;
            createPidFile() ;
        }
    } else {
        // createPidFile() returned -1 meaning that the
        // process was not there: create a shared memory segment:
        if ( iSharedMemory == NULL ) {
            QString sharedMemOwnName ( QString("classified-ads-")
                                       + QString::number(getpid()) ) ;
            iSharedMemory = new QSharedMemory(sharedMemOwnName) ;
        }
        if ( iSharedMemory ) {
            if( iSharedMemory->attach() == false ) {
                // 1 kb and some extra
                iSharedMemory->create(1024,QSharedMemory::ReadWrite) ;
                QLOG_STR("Created shared mem 1kb, is attached = " +
                         QString::number(iSharedMemory->isAttached())) ;
            }
        }
    }
#else
    // in WIN32 try to check existence of previous instance
    // by using a local server.
    const QString KLocalServerName("classifiedads") ;
    QString sharedMemSegmentName("classified-ads") ;
    QString segmentName("classified-ads") ;
    createSharedMemSegment(sharedMemSegmentName) ;

    QLocalSocket s ;
    s.connectToServer(KLocalServerName) ;
    if ( s.waitForConnected(2000) == true ) {
        s.close() ;
        QLOG_STR("Exiting because there is old instace has been signaled") ;

        return false ; // job done
    } else {
        switch ( s.error() ) {
        case QLocalSocket::PeerClosedError:
            // ok, looks like the server is actually  there:
            QLOG_STR("Exiting because there is old instace that closed connection") ;
            return false ;
            break ;
        default:
            QLOG_STR("Not exiting due to old instance, starting own local server") ;
            iLocalServer = new QLocalServer(this) ;
            if ( iLocalServer ) {
                if ( iLocalServer->listen(KLocalServerName) ) {
                    connect(iLocalServer,
                            SIGNAL(newConnection()),
                            this,
                            SLOT(newInstanceConnected())) ;
                    QLOG_STR("Local server listen ok") ;
                }
            }
            break ;
        }
    }
#endif
    qRegisterMetaType<MController::CAErrorSituation>("MController::CAErrorSituation");
    qRegisterMetaType<Hash>("Hash");
    qRegisterMetaType<ProtocolItemType>("ProtocolItemType");
    qRegisterMetaType<QHostAddress>("QHostAddress");
    qRegisterMetaType<VoiceCallEngine::CallState>("VoiceCallEngine::CallState");
    qRegisterMetaType<QVector<int> >("QVector<int>"); // used by dataChanged
    iWin = new QMainWindow(NULL) ;
    iWin->setWindowTitle(tr("Classified ads")) ;
    // somehow Qt should calculate size from widgets. it gets too small vertical..
    iWin->setMinimumSize(450,600) ;
    createMenus() ;
    iLayout = new QBoxLayout( QBoxLayout::TopToBottom, NULL ) ;
    QWidget *centralWidget = new QWidget() ;
    iWin->setCentralWidget(centralWidget) ;
    centralWidget->setLayout(iLayout) ;
    iModel = new Model(this);
    iDisplaySearchAct->setEnabled(true) ;
    displayFront() ;  // put UI in place only after model has been instantiated
    iWin->show() ;
    iModel->getNetReqExecutor()->start() ;
    iNode = new Node(iModel->nodeModel().nodeFingerPrint(),
                     iModel->nodeModel().listenPortOfThisNode()) ;
    iNode->setDNSAddr(iModel->nodeModel().getDnsName()) ;
    iListener = new  NetworkListener (this, iModel) ;
    // network listener enumerates network interfaces and sets
    // possible ipv6 addr into iNode() ->
    if (!Connection::Ipv6AddressesEqual(iNode->ipv6Addr(),
                                        KNullIpv6Addr)) {
        LOG_STR("We have IPv6") ;
        iListener->startListen(true) ;
    } else {
        iListener->startListen(false) ; // ipv4 only
    }
    // lets pass iListner to net engine because it is also observer
    // for new connections so lets have it observering the
    // newly-connecting outgoing connections too, it doesn't
    // need to know who originated the connection..
    iNetEngine = new NetworkConnectorEngine(this, iModel,*iListener) ;
    iNetEngine->start() ;
    PasswdDialog *pwd_dialog = new PasswdDialog(iWin, *this,tr("Enter password for protection of your messages:")) ;
    connect(pwd_dialog,
            SIGNAL(  error(MController::CAErrorSituation,
                           const QString&) ),
            this,
            SLOT(handleError(MController::CAErrorSituation,
                             const QString&)),
            Qt::QueuedConnection ) ;
    pwd_dialog->show() ;

    iPubEngine = new PublishingEngine(this, *iModel) ;
    iPubEngine->setInterval(5000); // every 5 seconds

    iRetrievalEngine = new RetrievalEngine (this, *iModel) ;
    iRetrievalEngine->setInterval(5000); // every 5 seconds

    iDbRetrievalEngine = new DbRecordRetrievalEngine (this, *iModel) ;
    iDbRetrievalEngine->setInterval(5000); // every 5 seconds

    // network listener is also connection status observer so lets
    // have it to signal the pub-engine when connections are opened/closed
    // (also the failed ones that are usually of no interest)
    assert(
        connect(iListener,
                SIGNAL(  nodeConnectionAttemptStatus(Connection::ConnectionState ,
                         const Hash  ) ),
                iPubEngine,
                SLOT( nodeConnectionAttemptStatus(Connection::ConnectionState ,
                        const Hash  )),
                Qt::QueuedConnection )  ) ;
    assert(
        connect(iListener,
                SIGNAL(  nodeConnectionAttemptStatus(Connection::ConnectionState ,
                         const Hash  ) ),
                iNetEngine,
                SLOT( nodeConnectionAttemptStatus(Connection::ConnectionState ,
                        const Hash  )),
                Qt::QueuedConnection )  ) ;
    assert(
        connect(iListener,
                SIGNAL(  nodeConnectionAttemptStatus(Connection::ConnectionState ,
                         const Hash  ) ),
                iRetrievalEngine,
                SLOT( nodeConnectionAttemptStatus(Connection::ConnectionState ,
                        const Hash  )),
                Qt::QueuedConnection )  ) ;
    assert(
        connect(iListener,
                SIGNAL(  nodeConnectionAttemptStatus(Connection::ConnectionState ,
                         const Hash  ) ),
                iDbRetrievalEngine,
                SLOT( nodeConnectionAttemptStatus(Connection::ConnectionState ,
                        const Hash  )),
                Qt::QueuedConnection )  ) ;
    assert(
        connect(iListener,
                SIGNAL(  nodeConnectionAttemptStatus(Connection::ConnectionState ,
                         const Hash  ) ),
                iModel->getNetReqExecutor(),
                SLOT( nodeConnectionAttemptStatus(Connection::ConnectionState ,
                        const Hash  )),
                Qt::QueuedConnection )  ) ;
    assert(
        connect(iListener,
                SIGNAL(  nodeConnectionAttemptStatus(Connection::ConnectionState ,
                         const Hash  ) ),
                iCurrentWidget,
                SLOT( nodeConnectionAttemptStatus(Connection::ConnectionState ,
                        const Hash  )),
                Qt::QueuedConnection )  ) ;
    assert(
        connect(iRetrievalEngine,
                SIGNAL(   notifyOfContentNotReceived(const Hash& ,
                          const ProtocolItemType  ) ),
                this,
                SLOT(    notifyOfContentNotReceived(const Hash& ,
                         const ProtocolItemType  )),
                Qt::QueuedConnection )  ) ;
    assert(
        connect(this,
                SIGNAL(userProfileSelected(const Hash&)),
                this,
                SLOT(    checkForObjectToOpen(const Hash&)),
                Qt::QueuedConnection));
    // after signals are connected, start publishing and retrieval
    iPubEngine->start() ;
    iRetrievalEngine->start() ;
    iDbRetrievalEngine->start() ;
    // instantiate voice call engine from UI thread, otherwise
    // some transient connection-related thread will do it and
    // problems start appearing after the thread finishes..
    this->voiceCallEngine() ;
    connect(this, SIGNAL(startGettingFileName(QString,bool)),
            this, SLOT(getFileNameSlot(QString,bool)),
            Qt::QueuedConnection) ; 
    /*
    // debug thing:
    iModel->classifiedAdsModel().reIndexAllAdsIntoFTS() ;
    iModel->profileModel().reIndexAllProfilesIntoFTS() ;
    iModel->profileCommentModel().reIndexAllCommentsIntoFTS() ;
    */
    QLOG_STR("Controller::init out") ;
    return true ;
}

bool Controller::createSharedMemSegment(QString& aSegmentName) {
    if (  ( iSharedMemory = new QSharedMemory(aSegmentName)) != NULL ) {

        if ( iSharedMemory->attach() == false ) {
            iSharedMemory->create(1024,QSharedMemory::ReadWrite)  ;
        }
        if( iSharedMemory->isAttached() == true &&
                iSharedMemory->constData() != NULL &&
                iSharedMemory->size() >= 1024 &&
                iObjectToOpen.scheme().length() > 0 ) {
            iSharedMemory->lock();
            strcpy((char *)(iSharedMemory->data()),
                   iObjectToOpen.toString().toUtf8().constData()) ;
            iSharedMemory->unlock();
            QLOG_STR("Copied to shared mem bytes " + aSegmentName + " " +
                     QString::number(strlen((char *)(iSharedMemory->data()))) ) ;
        } else {
            if (iSharedMemory->isAttached() == true &&
                    iSharedMemory->constData() != NULL &&
                    iSharedMemory->size() >= 1024 &&
                    iObjectToOpen.scheme().length() == 0 ) {
                // there is shared memory segment but nothing in iObjectToOpen
                // so null-terminate the shared memory segment contents
                iSharedMemory->lock();
                char* d ( (char *)(iSharedMemory->data())) ;
                iSharedMemory->unlock();
                *d = '\0' ;
                QLOG_STR("Constructed shared mem segment " + aSegmentName ) ;
            }
        }
        return true ;
    } else {
        QLOG_STR("Could not construct shared mem segment " + aSegmentName ) ;
        return false ;
    }
}

Controller::~Controller() {
    LOG_STR("Controller::~Controller") ;
    iInsideDestructor = true ;
    if ( iGetFileNameDialog ) {
        iGetFileNameDialog->reject() ; 
        QWaitCondition waitCondition;
        QMutex mutex;
        mutex.lock() ; // waitCondition needs a mutex initially locked
        waitCondition.wait(&mutex, 100);// let file selection call stack
                // collapse or it will return to deleted tcl interpreter
        mutex.unlock() ;
    }
    if (  iGetFileNameDialog ) {
        delete iGetFileNameDialog ; 
        iGetFileNameDialog = NULL ; 
    }
    if ( iTclWrapper ) {
        iTclWrapper->stopScript(true) ; // deletes self
        iTclWrapper = NULL ;
    }
#ifdef WIN32
    if ( iLocalServer ) {
        iLocalServer->close() ;
        delete iLocalServer ;
    }
#endif
    if ( iVoiceCallEngine ) {
        delete iVoiceCallEngine ;
        iVoiceCallEngine = NULL ; // call status dialog, if open, will ask..
    }
    if ( iListener ) {
        iListener->stopAccepting() ;
    }
    if ( iNetEngine ) {
        iNetEngine->iNeedsToRun = false ;
    }
    if ( iPubEngine ) {
        iPubEngine->iNeedsToRun = false ;
        iPubEngine->stop() ;
        delete iPubEngine ;
        iPubEngine = NULL ;
    }
    LOG_STR("Controller::~Controller 1 pubengine gone") ;
    if ( iRetrievalEngine ) {
        iRetrievalEngine->stop() ;
        delete iRetrievalEngine ;
        iRetrievalEngine = NULL ;
    }
    if ( iDbRetrievalEngine ) {
        iDbRetrievalEngine->stop() ;
        delete iDbRetrievalEngine ;
        iDbRetrievalEngine = NULL ;
    }
    if ( iNetEngine ) {
#ifndef WIN32
        deletePidFile() ; // if we did not instantiate net engine, we
        // did not create pidfile either
        QLOG_STR("NetEngine->terminate") ;
        iNetEngine->terminate() ;
        iNetEngine->wait(1000) ; // 1 sec max, then just delete..
        QLOG_STR("NetEngine->terminate out") ;
#endif
    }
    LOG_STR("Controller::~Controller 2 netengine gone") ;
    // .. connections reference iListener.
    // so in order to prevent random crash at closing, lets first get rid
    // of connections, only after that delete iListener ;
    if ( iModel ) {
        iModel->closeAllConnections(false) ;
        // after all connections have been instructed to close themselves,
        // wait for some time to give them time to do so..
        unsigned char waitCounter ( 0 ) ;
        while (  ( waitCounter < 60 && iModel->getConnections().count() > 0 ) ||
                 ( waitCounter < 2 ) ) {
            ++waitCounter ;
            QLOG_STR("Waitcounter " + QString::number(waitCounter) +
                     " conn count " + QString::number( iModel->getConnections().count() ) ) ;
            QWaitCondition waitCondition;
            QMutex mutex;
            mutex.lock() ; // waitCondition needs a mutex initially locked
            waitCondition.wait(&mutex, 500);// give other threads a chance..
            mutex.unlock() ;
            QThread::yieldCurrentThread ();
            QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents) ;
        }
        iModel->closeAllConnections(true) ; // forcefully delete the remaining
        // now safe to delete listener (and net engine)
        LOG_STR("Controller::~Controller connections closed") ;
        delete iNetEngine ; // will delete also connections opened by net engine
        iNetEngine = NULL ;
        LOG_STR("Controller::~Controller netengine deleted") ;
        delete iListener ; // will delete also connections received by listener
        iListener = NULL ;
        LOG_STR("Controller::~Controller listener deleted") ;
        delete iModel ;
    }
    iModel = NULL ;
    LOG_STR("Controller::~Controller datamodel") ;
    delete iNode ;
    if ( iFileMenu ) {
        delete iFileMenu;
    }
    if ( iExitAct ) {
        delete iExitAct ;
    }
    if ( iAboutAct ) {
        delete iAboutAct ;
    }
    if ( iPwdChangeAct ) {
        delete iPwdChangeAct;
    }
    if ( iProfileDeleteAct) {
        delete iProfileDeleteAct  ;
    }
    if (  iProfileCreateAct ) {
        delete iProfileCreateAct  ;
    }
    if (  iProfileSelectAct ) {
        delete iProfileSelectAct  ;
    }
    if ( iDisplaySettingsAct ) {
        delete iDisplaySettingsAct ;
    }
    if ( iDisplayStatusAct ) {
        delete iDisplayStatusAct ;
    }
    if ( iDisplaySearchAct ) {
        delete iDisplaySearchAct ;
    }
    if ( iTclMenu ) {
        delete iTclMenu;
    }
    if ( iTclLibraryAct ) {
        delete iTclLibraryAct ;
    }
    if ( iTclConsoleAct ) {
        delete iTclConsoleAct ;
    }
    if ( iWin ) {
        delete iWin ;
        iWin = NULL ;
    }
    if ( iSharedMemory ) {
        iSharedMemory->detach() ;
        delete iSharedMemory ;
    }
}

void Controller::userInterfaceAction ( CAUserInterfaceRequest aRequest,
                                       const Hash& aHashConcerned ,
                                       const Hash& aFetchFromNode ,
                                       const QString* aAdditionalInformation ) {
    LOG_STR2("Controller::userInterfaceAction %d", aRequest) ;

    if ( aRequest == ViewProfileDetails ) {

        iModel->lock() ;
        Profile *p = iModel->profileModel().profileByFingerPrint((aHashConcerned) ) ;
        iModel->unlock() ;
        if (p) {
            delete (p) ;
            iCurrentWidget->showDetailsOfProfile(aHashConcerned) ;
        } else {
            // seems like we do not have the profile. lets put a wait-dialog
            // in place and profile fetch request to network..
            NetworkRequestExecutor::NetworkRequestQueueItem req ;
            req.iRequestType =RequestForUserProfile ;
            req.iRequestedItem = aHashConcerned ;
            req.iState = NetworkRequestExecutor::NewRequest ;
            req.iDestinationNode = aFetchFromNode ; // may be KNullHash
            startRetrievingContent(req,false,UserProfile) ;
            userInterfaceAction ( DisplayProgressDialog,
                                  KNullHash ,
                                  KNullHash ) ;
        }
    } else if ( aRequest == ViewCa ) {
        iModel->lock() ;
        CA ca = iModel->classifiedAdsModel().caByHash(aHashConcerned)  ;
        iModel->unlock() ;
        if ( ca.iFingerPrint != KNullHash ) {
            // classified ad was found from local storage
            iCurrentWidget->showClassifiedAd(ca) ;
        } else {
            // classified ad was not found from local storage, begin fetch
            NetworkRequestExecutor::NetworkRequestQueueItem req ;
            req.iRequestType =RequestForClassifiedAd ;
            req.iRequestedItem = aHashConcerned ;
            req.iState = NetworkRequestExecutor::NewRequest ;
            req.iDestinationNode = aFetchFromNode ; // may be KNullHash
            startRetrievingContent(req,false,ClassifiedAd) ;
            userInterfaceAction ( DisplayProgressDialog,
                                  KNullHash ,
                                  KNullHash ) ;
        }
    } else if ( aRequest == ViewProfileComment ) {
        // ok, profile comment is tricky to display because it
        // is two-stage process. first state is finding the
        // profile, that may or may not be locally stored.
        // after profile is found and displayed, we may
        // continue with the comment itself, that again
        // may or may not be found.
        //
        // in order to know the profile, the comment is required
        // first.
        iModel->lock() ;
        ProfileComment* c ( iModel->profileCommentModel().profileCommentByFingerPrint(aHashConcerned) ) ;
        iModel->unlock() ;
        if ( c ) {
            // see if we have the profile too:
            iModel->lock() ;
            Profile *p ( iModel->profileModel().profileByFingerPrint(c->iProfileFingerPrint,
                         true, /* emit */
                         true  /* no image */  ) ) ;
            iModel->unlock() ;
            if ( p ) {
                delete p ;
                p = NULL ;
                iCurrentWidget->showDetailsOfProfile(c->iProfileFingerPrint) ;
                iCurrentWidget->showSingleCommentOfProfile(aHashConcerned) ;
            } else {
                // seems like we do not have the profile. lets put a wait-dialog
                // in place and profile fetch request to network..
                NetworkRequestExecutor::NetworkRequestQueueItem req ;
                req.iRequestType = RequestForUserProfile ;
                req.iRequestedItem = c->iProfileFingerPrint ;
                req.iState = NetworkRequestExecutor::NewRequest ;
                req.iDestinationNode = aFetchFromNode ; // may be KNullHash
                startRetrievingContent(req,false,UserProfile) ;
                iHashOfProfileCommentBeingWaitedFor = aHashConcerned ;
                iNodeForCommentBeingWaitedFor =  aFetchFromNode ;
                userInterfaceAction ( DisplayProgressDialog,
                                      KNullHash ,
                                      KNullHash ) ;
            }
            delete c ;
        } else {
            // comment was not found, begin fetch for that:
            NetworkRequestExecutor::NetworkRequestQueueItem req ;
            req.iRequestType = RequestForProfileComment ;
            req.iRequestedItem = aHashConcerned ;
            req.iState = NetworkRequestExecutor::NewRequest ;
            req.iDestinationNode = aFetchFromNode ; // may be KNullHash
            startRetrievingContent(req,false,UserProfileComment) ;
            userInterfaceAction ( DisplayProgressDialog,
                                  KNullHash ,
                                  KNullHash ) ;
        }

    } else if ( aRequest == DisplayProgressDialog ) {
        QProgressDialog* waitDialog = new QProgressDialog(iCurrentWidget) ;
        waitDialog->setLabelText ( tr("Fetching item from network..") );
        waitDialog->setMaximum(0) ;
        waitDialog->setMinimum(0) ;
        connect(this,SIGNAL(waitDialogToBeDismissed()),
                waitDialog,SLOT(reject())) ;
        waitDialog->exec() ;
    } else if ( aRequest == VoiceCallToNode && iNode != NULL ) {
        QLOG_STR("Voice call request to node " +
                 aHashConcerned.toString() ) ;
        // here let voice call engine handle all the logic:
        if ( !iVoiceCallEngine ) {
            this->voiceCallEngine() ; // has side effect of instantiating one
        }
        VoiceCall callData;
        callData.iCallId = rand() ;
        callData.iTimeOfCallAttempt = QDateTime::currentDateTimeUtc().toTime_t() ;
        callData.iOkToProceed = true ;
        quint32 dummyTimeStamp ;
        iModel->lock() ;
        QLOG_STR("unlock " + QString(__FILE__) + " "+ QString::number(__LINE__));
        iModel->contentEncryptionModel().PublicKey(iProfileHash,
                callData.iOriginatingOperatorKey,
                &dummyTimeStamp) ;

        callData.iOriginatingNode = iNode->nodeFingerPrint() ;
        callData.iDestinationNode = iModel->nodeModel().nodeByHash(aHashConcerned)->nodeFingerPrint();
        if ( aAdditionalInformation ) {
            callData.iPeerOperatorNick = *aAdditionalInformation ;
            QLOG_STR("Peer nick was set to " + callData.iPeerOperatorNick ) ;
        }
        iVoiceCallEngine->insertCallStatusData(callData,
                                               iNode->nodeFingerPrint() ) ;
        iModel->unlock() ;
        QLOG_STR("unlock " + QString(__FILE__) + " "+ QString::number(__LINE__));
        callData.iOriginatingNode = KNullHash ; // or it gets deleted
        // calldata destructor will delete callData.iDestinationNode
    } else {
        LOG_STR2("Unhandled user interface request %d", aRequest) ;
    }
    LOG_STR2("Controller::userInterfaceAction out %d", aRequest) ;
}

void Controller::hideUI() {
    if ( iWin ) {
        iWin->hide() ;
    }
}

void Controller::showUI() {
    if ( iWin ) {
        iWin->show() ;
    }
}

void Controller::createMenus() {
    // first "file" menu:
    iExitAct = new QAction(tr("E&xit"), this);
    iExitAct->setShortcuts(QKeySequence::Quit);
    iExitAct->setStatusTip(tr("Exit the application"));

    iAboutAct = new QAction(tr("&About"), this);
    iAboutAct->setStatusTip(tr("Show the application's About box"));

    iPwdChangeAct = new QAction(tr("&Change password"), this);
    iPwdChangeAct->setStatusTip(tr("Change password of current profile"));

    iProfileCreateAct = new QAction(tr("Create &new profile"), this);
    iProfileCreateAct->setStatusTip(tr("Makes a brand new user profile"));

    iProfileDeleteAct = new QAction(tr("&Delete current profile"), this);
    iProfileDeleteAct->setStatusTip(tr("Deletes currently open profile"));

    iProfileSelectAct = new QAction(tr("&Select another profile"), this);
    iProfileSelectAct->setStatusTip(tr("If you have multitude of profiles"));

    iDisplaySettingsAct = new QAction(tr("Settings.."), this);
    iDisplaySettingsAct->setStatusTip(tr("Node-wide settings.."));

    iDisplayStatusAct = new QAction(tr("Network status.."), this);

    iDisplaySearchAct = new QAction(tr("Search.."), this);
    connect(iAboutAct, SIGNAL(triggered()), this, SLOT(displayAboutBox()));
    connect(iExitAct, SIGNAL(triggered()), this, SLOT(exitApp()));
    connect(iPwdChangeAct, SIGNAL(triggered()), this, SLOT(changeProfilePasswd()));
    connect(iProfileCreateAct, SIGNAL(triggered()),
            this, SLOT(createProfile()));
    connect(iProfileDeleteAct, SIGNAL(triggered()),
            this, SLOT(deleteProfile()));
    connect(iProfileSelectAct, SIGNAL(triggered()),
            this, SLOT(selectProfile()));
    connect(iDisplaySettingsAct, SIGNAL(triggered()),
            this, SLOT(displaySettings()));
    connect(iDisplayStatusAct, SIGNAL(triggered()),
            this, SLOT(displayStatus()));
    connect(iDisplaySearchAct, SIGNAL(triggered()),
            this, SLOT(displaySearch()));

    iFileMenu = iWin->menuBar()->addMenu(tr("&File"));
    iFileMenu->addAction(iAboutAct);
    iFileMenu->addAction(iPwdChangeAct);
    iFileMenu->addAction(iProfileCreateAct);
    iFileMenu->addAction(iProfileDeleteAct);
    iFileMenu->addAction(iProfileSelectAct);
    iFileMenu->addAction(iDisplaySettingsAct) ;
    iFileMenu->addAction(iDisplayStatusAct) ;
    iFileMenu->addAction(iDisplaySearchAct) ;
    iPwdChangeAct->setDisabled(true) ; // enable when profile is open
    iProfileDeleteAct->setDisabled(true) ; // enable when profile is open
    iFileMenu->addAction(iExitAct);

    // menu-items related to TCL interpreter
    iTclMenu = iWin->menuBar()->addMenu(tr("&TCL Programs"));
    iTclLibraryAct = new QAction(tr("&Local library"), this);
    iTclLibraryAct->setStatusTip(tr("Locally stored TCL programs"));
    connect(iTclLibraryAct, SIGNAL(triggered()), this, SLOT(displayTclProgs()));
    iTclMenu->addAction(iTclLibraryAct) ;
    iTclConsoleAct = new QAction(tr("TCL &Console"), this);
    iTclConsoleAct->setStatusTip(tr("Display interpreter console"));
    connect(iTclConsoleAct, SIGNAL(triggered()), this, SLOT(displayTclConsole()));
    iTclMenu->addAction(iTclConsoleAct) ;
}

void Controller::exitApp() {
    LOG_STR("Controller::exitApp") ;
    if ( iCurrentWidget && iLayout ) {
        iLayout->removeWidget(iCurrentWidget) ;
        delete iCurrentWidget ;
    }
    // iLayout is owned by iCurrentWidget so it should be
    // deleted there.
    if ( iWin ) {
        iWin->close() ;
    }
}

void Controller::displayAboutBox() {
    if ( iWin ) {
        const QString dlgName ("classified_ads_about_dialog") ;
        AboutDialog *dialog = iWin->findChild<AboutDialog *>(dlgName) ;
        if ( dialog == NULL ) {
            dialog = new AboutDialog(iWin, *this) ;
            dialog->setObjectName(dlgName) ;
            dialog->show() ;
        } else {
            dialog->setFocus(Qt::MenuBarFocusReason) ;
        }
    }
}

void Controller::changeProfilePasswd() {
    if ( iWin) {
        // the last false tells dialog to behave in change-mode instead
        // of query-mode
        PasswdDialog *pwd_dialog = new PasswdDialog(iWin, *this,tr("Enter new password:"),false) ;
        connect(pwd_dialog,
                SIGNAL(  error(MController::CAErrorSituation,
                               const QString&) ),
                this,
                SLOT(handleError(MController::CAErrorSituation,
                                 const QString&)),
                Qt::QueuedConnection ) ;
        pwd_dialog->show() ;
    }
    LOG_STR("Controller::changeProfilePasswd out") ;
}

//  Initiates UI sequence for new profile
void Controller::createProfile() {
    LOG_STR("createProfile in") ;
    iModel->lock() ;
    setProfileInUse(iModel->contentEncryptionModel().generateKeyPair()) ;
    iModel->unlock() ;
    if ( iProfileHash != KNullHash ) {
        changeProfilePasswd() ;
    }
    LOG_STR("createProfile in") ;
}

//  Initiates UI sequence for selecting a profile
void Controller::selectProfile() {
    LOG_STR("selectProfile in") ;
    PasswdDialog *pwd_dialog = new PasswdDialog(iWin, *this,tr("Activate another profile with password")) ;
    connect(pwd_dialog,
            SIGNAL(  error(MController::CAErrorSituation,
                           const QString&) ),
            this,
            SLOT(handleError(MController::CAErrorSituation,
                             const QString&)),
            Qt::QueuedConnection ) ;
    pwd_dialog->show() ;
    LOG_STR("selectProfile in") ;
}

void Controller::displaySettings() {
    LOG_STR("Controller::displaySettings") ;
    const QString dlgName ("classified_ads_settings_dialog") ;
    SettingsDialog *dialog = iWin->findChild<SettingsDialog *>(dlgName) ;
    if ( dialog == NULL ) {
        dialog = new SettingsDialog(iWin, *this) ;
        dialog->setObjectName(dlgName) ;
        connect(dialog,
                SIGNAL(  error(MController::CAErrorSituation,
                               const QString&) ),
                this,
                SLOT(handleError(MController::CAErrorSituation,
                                 const QString&)),
                Qt::QueuedConnection ) ;
        dialog->show() ;
    } else {
        dialog->setFocus(Qt::MenuBarFocusReason) ;
    }
}

void Controller::displayStatus() {
    LOG_STR("Controller::displayStatus") ;
    const QString dlgName ("classified_ads_status_dialog") ;
    StatusDialog *dialog = iWin->findChild<StatusDialog *>(dlgName) ;
    if ( dialog == NULL ) {
        dialog = new StatusDialog(iWin, *this) ;
        dialog->setObjectName(dlgName) ;
        connect(dialog,
                SIGNAL(  error(MController::CAErrorSituation,
                               const QString&) ),
                this,
                SLOT(handleError(MController::CAErrorSituation,
                                 const QString&)),
                Qt::QueuedConnection ) ;
        dialog->show() ;
    } else {
        dialog->setFocus(Qt::MenuBarFocusReason) ;
    }
}

void Controller::displaySearch() {
    LOG_STR("Controller::displaySearch") ;
    const QString dlgName ("classified_ads_search_dialog") ;
    SearchDisplay *dialog = iWin->findChild<SearchDisplay *>(dlgName) ;
    if ( dialog == NULL && iCurrentWidget->selectedProfile()) {
        dialog = new SearchDisplay(iCurrentWidget,
                                   this,
                                   iModel->searchModel(),
                                   *(iCurrentWidget->selectedProfile())) ;
        dialog->setObjectName(dlgName) ;
        connect(dialog,
                SIGNAL(  error(MController::CAErrorSituation,
                               const QString&) ),
                this,
                SLOT(handleError(MController::CAErrorSituation,
                                 const QString&)),
                Qt::QueuedConnection ) ;

        // pointer of current profile is inside dialog -> if that
        // changes, close the dialog ; user needs to re-open search
        // dialog if she switches profile in use
        assert(connect(this,
                       SIGNAL(userProfileSelected(const Hash&)),
                       dialog,
                       SLOT(deleteLater()),
                       Qt::QueuedConnection)  ) ;

        dialog->show() ;
    } else {
        dialog->setFocus(Qt::MenuBarFocusReason) ;
    }
}

/** Slot for displaying TCL library */
void Controller::displayTclProgs() {
    QLOG_STR("Controller::displayTclProgs") ;

    const QString dlgName ("classified_ads_tclprogs_dialog") ;
    TclProgramsDialog *dialog = iWin->findChild<TclProgramsDialog *>(dlgName) ;
    if ( dialog == NULL ) {
        dialog = new TclProgramsDialog(iWin, *this) ;
        dialog->setObjectName(dlgName) ;
        connect(dialog,
                SIGNAL(  error(MController::CAErrorSituation,
                               const QString&) ),
                this,
                SLOT(handleError(MController::CAErrorSituation,
                                 const QString&)),
                Qt::QueuedConnection ) ;
        dialog->show() ;
        // also connect tcl eval signal from dialog to wrapper
        tclWrapper() ;// ensure there is interpreter inside wrapper
        if ( iTclWrapper ) {
            connect(dialog, SIGNAL(evalScript(QString,QString*)),
                    iTclWrapper, SLOT(evalScript(QString,QString*)),
                    Qt::QueuedConnection) ;
            connect(iTclWrapper, SIGNAL(started()),
                    dialog, SLOT(tclProgramStarted()),
                    Qt::QueuedConnection) ;
            connect(iTclWrapper, SIGNAL(finished()),
                    dialog, SLOT(tclProgramStopped()),
                    Qt::QueuedConnection) ;
#if QT_VERSION < 0x050000
            // qt5 has no terminated signal in QThread
            // but if on older qt connect that anyway
            connect(iTclWrapper, SIGNAL(terminated()),
                    dialog, SLOT(tclProgramStopped()),
                    Qt::QueuedConnection) ;
#endif
            if ( iTclWrapper->isRunning() ) {
                dialog->tclProgramStarted() ;
            }
        }
    } else {
        dialog->setFocus(Qt::MenuBarFocusReason) ;
    }
}

/** Slot for displaying TCL console */
void Controller::displayTclConsole() {
    QLOG_STR("Controller::displayTclConsole") ;
    tclWrapper().showConsole() ;
}


// Initiates UI sequence for deleting profile
void Controller::deleteProfile() {
    LOG_STR("deleteProfile in") ;
    QMessageBox msgBox;
    iModel->lock() ;
    int numberOfPrivateKeys = iModel->contentEncryptionModel().listKeys(true,NULL).size() ;
    iModel->unlock() ;
    if ( numberOfPrivateKeys < 2 ) {
        msgBox.setText(tr("Can't delete only profile."));
        msgBox.setStandardButtons( QMessageBox::Ok );
        msgBox.exec();
    } else {
        msgBox.setText(tr("Permanently discard profile?"));
        msgBox.setInformativeText(tr("There will be NO way to access content of this profile later"));
        msgBox.setStandardButtons( QMessageBox::Ok | QMessageBox::Cancel);
        msgBox.setDefaultButton(QMessageBox::Cancel);
        int ret = msgBox.exec();
        if ( ret == QMessageBox::Ok  ) {
            LOG_STR("delete profile..") ;
            iModel->lock() ;
            bool deletiaResult = iModel->contentEncryptionModel().deleteKeyPair(iProfileHash)  ;
            iModel->unlock() ;
            if ( deletiaResult ) {
                PasswdDialog *pwd_dialog = new PasswdDialog(iWin, *this,tr("Activate another profile with password")) ;
                connect(pwd_dialog,
                        SIGNAL(  error(MController::CAErrorSituation,
                                       const QString&) ),
                        this,
                        SLOT(handleError(MController::CAErrorSituation,
                                         const QString&)),
                        Qt::QueuedConnection ) ;
                pwd_dialog->show() ;
            }
        } else {
            LOG_STR("user is unsure") ;
        }
    }
}

void Controller::displayFront() {
    LOG_STR("displayFront") ;
    if ( iCurrentWidget ) {
        iLayout->removeWidget(iCurrentWidget) ;
        delete iCurrentWidget ;
    }
    iLayout->addWidget(iCurrentWidget = new FrontWidget(this,*iWin)) ;
    connect(iCurrentWidget,
            SIGNAL(  error(MController::CAErrorSituation,
                           const QString&) ),
            this,
            SLOT(handleError(MController::CAErrorSituation,
                             const QString&)),
            Qt::QueuedConnection ) ;
    //
    // important:
    // connection is queued. in practice this signal is emitted at
    // situation where datamodel is locked.
    // UI in question will immediately try to obtain lock to datamodel
    // so we would end up in deadlock situation. Use queued signal
    // here so call stack of the caller is left to collapse
    // until this signal is delivered
    //
    assert(connect(this,
                   SIGNAL(userProfileSelected(const Hash&)),
                   iCurrentWidget,
                   SLOT(userProfileSelected(const Hash&)),
                   Qt::QueuedConnection)  ) ;
    LOG_STR("displayFront out") ;
}

void Controller::handleError(MController::CAErrorSituation aError,
                             const QString& aExplanation) {
    LOG_STR2("Error enum value %d", aError) ;
    QLOG_STR(aExplanation) ;
    switch ( aError ) {
    case OwnCertNotFound:
        QMessageBox::about(iWin,tr("Cant load node cert or key cert"),
                           aExplanation);
        LOG_STR("Cant load node cert or key cert") ;
        break ;
    case FileOperationError:  // type of non-fatal error
        QMessageBox::about(iWin,tr("File error"),
                           aExplanation);
        LOG_STR("File error " + aExplanation ) ;
        break ;
    case DataBaseNotMountable:
        QMessageBox::about(iWin,tr("Database error"),
                           aExplanation);
        LOG_STR("Can't open DB") ;
        QApplication::quit() ;
        break ;
    case ContentEncryptionError :
        QMessageBox::about(iWin,tr("Cryptographic module"),
                           aExplanation);
        QLOG_STR("ContentEncryptionError " + aExplanation ) ;
        break ;
    case DbTransactionError :
        QMessageBox::about(iWin,tr("Database module"),
                           aExplanation);
        QLOG_STR("DbTransactionError " + aExplanation ) ;
        break ;
    case BadPassword :
        QMessageBox::about(iWin,tr("Cryptographic module"),
                           tr("Bad password"));
        QLOG_STR("DbTransactionError " + aExplanation ) ;
        break ;
    case TCLEvalError :
        QMessageBox::about(iWin,tr("TCL Interpreter"),
                           aExplanation);
        QLOG_STR("DbTransactionError " + aExplanation ) ;
        break ;
    }
}

Node& Controller::getNode() const {
    return *iNode ;
}

NetworkListener *Controller::networkListener() const {
    return iListener ;
}

Model& Controller::model() const {
    return *iModel ;
}

int Controller::createPidFile() {
    int retval = -1 ;
#ifndef WIN32
    QString path(QDir::home().path());
    path.append(QDir::separator()).append(".classified_ads");
    path.append(QDir::separator()).append("instance.pid") ;
    bool ok = false ;
    if (QFile(path).exists()) {
        QFile f(path) ;
        f.open(QIODevice::ReadOnly) ;
        QByteArray arr = f.readAll() ;
        QLatin1String content8bit(arr);
        QString content (content8bit) ;
        retval = content.toInt(&ok, 10) ;
    }
    if (!ok ) {
        QFile f(path) ;
        f.open(QIODevice::WriteOnly) ;
        QString content = QString::number(getpid());
        QByteArray contentBytes(content.toLatin1()) ;
        f.write(contentBytes) ;
        f.close() ;
        retval = -1 ;
    }
#endif
    return retval ;
}

void Controller::deletePidFile() {
#ifndef WIN32
    QString path(QDir::home().path());
    path.append(QDir::separator()).append(".classified_ads");
    path.append(QDir::separator()).append("instance.pid") ;
    QFile(path).remove() ;
#endif
}

void Controller::setContentKeyPasswd(QString aPasswd) {
    iContentKeyPasswd = aPasswd ;
}

QString Controller::contentKeyPasswd()  const {
    return iContentKeyPasswd ;
}

void Controller::setProfileInUse(const Hash& aProfileHash) {
    if ( iProfileHash != KNullHash ) {
        storePrivateDataOfSelectedProfile() ;
    }
    iProfileHash = aProfileHash ;
    iPwdChangeAct->setDisabled(false) ;
    int numberOfPrivateKeys = iModel->contentEncryptionModel().listKeys(true,NULL).size() ;
    if ( numberOfPrivateKeys > 1 ) {
        iProfileDeleteAct->setDisabled(false) ;
        iProfileSelectAct->setDisabled(false) ;
    } else {
        iProfileDeleteAct->setDisabled(true) ;
        iProfileSelectAct->setDisabled(true) ;
    }
    reStorePrivateDataOfSelectedProfile() ;
    emit userProfileSelected(iProfileHash) ; // must be Qt::QueuedConnection
}


const Hash& Controller::profileInUse() {
    return iProfileHash ;
}



// signal of received content
void Controller::notifyOfContentReceived(const Hash& aHashOfContent,
        const ProtocolItemType aTypeOfReceivedContent) {
    LOG_STR2("Controller::notifyOfContentReceived type : %d", aTypeOfReceivedContent);
    if ( iCurrentWidget ) {
        iCurrentWidget->receiveNotifyOfContentReceived( aHashOfContent,
                aTypeOfReceivedContent) ;
        if ( aHashOfContent == iHashOfObjectBeingWaitedFor &&
                aTypeOfReceivedContent == iTypeOfObjectBeingWaitedFor ) {
            emit waitDialogToBeDismissed() ;
            iHashOfObjectBeingWaitedFor= KNullHash ; // do not wait any more
            if ( aTypeOfReceivedContent == UserProfile ) {
                iCurrentWidget->showDetailsOfProfile(aHashOfContent) ;
                if ( iHashOfProfileCommentBeingWaitedFor != KNullHash ) {
                    // stage 2: we were waiting for profile but actually
                    // user wanted to see an ad: as we now have the profile,
                    // lets ask for comment too
                    //
                    // lets check if we have the comment:
                    ProfileComment* c ( iModel->profileCommentModel().profileCommentByFingerPrint(iHashOfProfileCommentBeingWaitedFor) ) ;
                    if ( c == NULL ) {
                        NetworkRequestExecutor::NetworkRequestQueueItem req ;
                        req.iRequestType = RequestForProfileComment ;
                        req.iRequestedItem = iHashOfProfileCommentBeingWaitedFor ;
                        iHashOfProfileCommentBeingWaitedFor = KNullHash ;
                        req.iState = NetworkRequestExecutor::NewRequest ;
                        req.iDestinationNode = iNodeForCommentBeingWaitedFor ;
                        iNodeForCommentBeingWaitedFor = KNullHash ;
                        startRetrievingContent(req,false,UserProfileComment) ;
                        userInterfaceAction ( DisplayProgressDialog,
                                              KNullHash ,
                                              KNullHash ) ;
                    } else {
                        iCurrentWidget->showSingleCommentOfProfile(iHashOfProfileCommentBeingWaitedFor) ;
                        delete c ;
                        iHashOfProfileCommentBeingWaitedFor = KNullHash ;
                    }
                }
            } else if ( aTypeOfReceivedContent == ClassifiedAd ) {
                iModel->lock() ;
                CA ca = iModel->classifiedAdsModel().caByHash(aHashOfContent)  ;
                iModel->unlock() ;
                if ( ca.iFingerPrint != KNullHash ) {
                    iCurrentWidget->showClassifiedAd(ca) ;
                }
            } else if ( aTypeOfReceivedContent == BinaryBlob ) {
                iCurrentWidget->openBinaryFile(aHashOfContent,false) ;
            }
        }
    }
    iRetrievalEngine->notifyOfContentReceived(aHashOfContent,
            aTypeOfReceivedContent) ;
    // offer db records to db retrieval engine
    if ( aTypeOfReceivedContent == DbRecord ) {
        iDbRetrievalEngine->notifyOfContentReceived(aHashOfContent,
                                                    aTypeOfReceivedContent) ;
    }
    // offer profiles to trust list
    if ( aTypeOfReceivedContent == UserProfile ) {
        iModel->trustTreeModel()->contentReceived(aHashOfContent,
                aTypeOfReceivedContent) ;
    }

    if ( iTclWrapper ) {
        iTclWrapper->notifyOfContentReceived(aHashOfContent,
                                             aTypeOfReceivedContent) ;
    }
}

void Controller::notifyOfContentReceived(const Hash& aHashOfContent,
        const Hash& aHashOfClassification,
        const ProtocolItemType aTypeOfReceivedContent) {
    LOG_STR2("Controller::notifyOfContentReceived v2 type : %d", aTypeOfReceivedContent);
    if ( iCurrentWidget ) {
        iCurrentWidget->receiveNotifyOfContentReceived( aHashOfContent,
                aHashOfClassification,
                aTypeOfReceivedContent) ;
        if ( aHashOfContent == iHashOfObjectBeingWaitedFor &&
                aTypeOfReceivedContent == iTypeOfObjectBeingWaitedFor ) {
            emit waitDialogToBeDismissed() ;
            iHashOfObjectBeingWaitedFor= KNullHash ; // do not wait any more
            if ( aTypeOfReceivedContent == UserProfile ) {
                iCurrentWidget->showDetailsOfProfile(aHashOfContent) ;
                if ( iHashOfProfileCommentBeingWaitedFor != KNullHash ) {
                    ProfileComment* c ( iModel->profileCommentModel().profileCommentByFingerPrint(iHashOfProfileCommentBeingWaitedFor) ) ;
                    if ( c ) {
                        // we were waiting for profile but actually want to
                        // to display one comment from that profile. we now
                        // have the profile+comment
                        iCurrentWidget->showSingleCommentOfProfile(iHashOfProfileCommentBeingWaitedFor) ;
                        iHashOfProfileCommentBeingWaitedFor = KNullHash ;
                        delete c ;
                    } else {

                        // stage 2: we were waiting for profile but actually
                        // user wanted to see an ad: as we now have the profile,
                        // lets ask for comment too
                        NetworkRequestExecutor::NetworkRequestQueueItem req ;
                        req.iRequestType = RequestForProfileComment ;
                        req.iRequestedItem = iHashOfProfileCommentBeingWaitedFor ;
                        iHashOfProfileCommentBeingWaitedFor = KNullHash ;
                        req.iState = NetworkRequestExecutor::NewRequest ;
                        req.iDestinationNode = iNodeForCommentBeingWaitedFor ;
                        iNodeForCommentBeingWaitedFor = KNullHash ;
                        startRetrievingContent(req,false,UserProfileComment) ;
                        userInterfaceAction ( DisplayProgressDialog,
                                              KNullHash ,
                                              KNullHash ) ;
                    }
                }
            } else if ( aTypeOfReceivedContent == ClassifiedAd ) {
                iModel->lock() ;
                CA ca = iModel->classifiedAdsModel().caByHash(aHashOfContent)  ;
                iModel->unlock() ;
                if ( ca.iFingerPrint != KNullHash ) {
                    iCurrentWidget->showClassifiedAd(ca) ;
                }
            }
        }
    }
    iRetrievalEngine->notifyOfContentReceived(aHashOfContent,
            aTypeOfReceivedContent) ;
    iDbRetrievalEngine->notifyOfContentReceived(aHashOfContent,
            aTypeOfReceivedContent) ;

    if ( iTclWrapper ) {
        iTclWrapper->notifyOfContentReceived(aHashOfContent,
                                             aTypeOfReceivedContent) ;
    }
}
void Controller::notifyOfContentNotReceived(const Hash& aHashOfContent,
        const ProtocolItemType
#ifdef DEBUG
        aTypeOfNotReceivdContent  // needed only in debug build
#else
        /* aTypeOfNotReceivdContent  */
#endif
                                           ) {
    LOG_STR2("Controller::notifyOfContentNotReceived type : %d", aTypeOfNotReceivdContent);
    if ( iHashOfObjectBeingWaitedFor == aHashOfContent ) {
        iHashOfObjectBeingWaitedFor= KNullHash ;
        iHashOfProfileCommentBeingWaitedFor = KNullHash ;
        emit waitDialogToBeDismissed() ;
        QErrorMessage* errorDialog = new QErrorMessage(iCurrentWidget) ;
        errorDialog->showMessage ( tr("Could not find item from network..") );
    }
}

void Controller::startRetrievingContent(NetworkRequestExecutor::NetworkRequestQueueItem aReq,
                                        bool aIsBackgroundDl,
                                        ProtocolItemType aTypeOfExpectedObject) {
    // here queue the item into retrieval-engine
    iRetrievalEngine->startRetrieving(aReq,
                                      aIsBackgroundDl) ;
    iHashOfObjectBeingWaitedFor = aReq.iRequestedItem ;
    iTypeOfObjectBeingWaitedFor = aTypeOfExpectedObject ;
}


void Controller::startRetrievingContent( CaDbRecord::SearchTerms aSearchTerms ) {
    if ( iDbRetrievalEngine ) {
        iDbRetrievalEngine->startRetrieving(aSearchTerms) ; 
    }
}

void Controller::storePrivateDataOfSelectedProfile(bool aPublishTrustListToo) {

    if ( iProfileHash!= KNullHash ) {
        QMap<QString,QVariant> m ;
        m.insert(KPrivateDataContactsSection,
                 iCurrentWidget->contactDataOfSelectedProfile()) ;
        if ( iHashDisplaynameMapping.size() > 0 ) {
            QMap<QString,QVariant> cache ;
            QMapIterator<Hash, QString> i(iHashDisplaynameMapping);
            while (i.hasNext()) {
                i.next();
                cache.insert(i.value(), i.key().toQVariant()) ;
            }
            m.insert(KPrivateDataContactsCache,
                     cache) ;
        }
        m.insert(KPrivateDataTrustTree,
                 iModel->trustTreeModel()->trustTreeSettings()) ;

        iModel->profileModel().setPrivateDataForProfile(iProfileHash,
                QVariant(m)) ;

        if ( iCurrentWidget->selectedProfile() ) {
            iCurrentWidget->selectedProfile()->iTrustList.clear() ;
            iCurrentWidget->selectedProfile()->iTrustList.append(iCurrentWidget->trustListOfSelectedProfile()) ;
            if ( aPublishTrustListToo ) {
                iCurrentWidget->selectedProfile()->iTimeOfPublish = QDateTime::currentDateTimeUtc().toTime_t() ;
                iModel->profileModel().publishProfile(*(iCurrentWidget->selectedProfile()));
            }
        }
    } else {
        LOG_STR("No selected profile while storePrivateDataOfSelectedProfile") ;
    }
}

void Controller::reStorePrivateDataOfSelectedProfile() {
    if ( iProfileHash!= KNullHash ) {
        QMap<QString,QVariant> privateData = iModel->profileModel().privateDataOfProfile(iProfileHash).toMap() ;
        if (privateData.contains(KPrivateDataContactsSection)) {
            QVariantList listOfContacts (privateData[KPrivateDataContactsSection].toList()) ;
            iCurrentWidget->setContactDataOfSelectedProfile(listOfContacts) ;
        }
        if (privateData.contains(KPrivateDataTrustTree)) {
            iModel->trustTreeModel()->initModel(privateData[KPrivateDataTrustTree]) ;
        } else {
            iModel->trustTreeModel()->initModel(QVariant()) ;
        }

        iHashDisplaynameMapping.clear() ;
        if (privateData.contains(KPrivateDataContactsCache)) {
            QVariantMap contactsCache (privateData[KPrivateDataContactsCache].toMap()) ;

            QMapIterator<QString,QVariant> i(contactsCache);
            while (i.hasNext()) {
                i.next();
                Hash profileKey ;
                profileKey.fromQVariant(i.value()) ;
                QLOG_STR("Inserting into iHashDisplaynameMapping key = " + profileKey.toString() + " name " + i.key()) ;
                if ( profileKey.toString() != i.key() ) {
                    iHashDisplaynameMapping.insert(profileKey,i.key() ) ; // not how i.key() is profile name. this is
                    // because in QVariantMap the key is hard-coded to be a QString
                } else {
                    QLOG_STR("..Or not, because name was profile hash") ;
                }
            }
        }
    }
}

bool Controller::isContactInContactList(const Hash& aFingerPrint) const {
    return iCurrentWidget->isContactInContactList(aFingerPrint) ;
}

QString Controller::displayableNameForProfile(const Hash& aProfileFingerPrint) const {
    return iHashDisplaynameMapping.value(aProfileFingerPrint, aProfileFingerPrint.toString()) ;
}

void Controller::offerDisplayNameForProfile(const Hash& aProfileFingerPrint,
        const QString& aDisplayName,
        const bool aStoreInPersistenStorage) {
    if ( aProfileFingerPrint.toString() != aDisplayName ) {
        if (aDisplayName.length() > 0 && ( ! iHashDisplaynameMapping.contains(aProfileFingerPrint )) ) {
            iHashDisplaynameMapping.insert(aProfileFingerPrint, aDisplayName) ;
            if ( aStoreInPersistenStorage ) {
                storePrivateDataOfSelectedProfile() ;
            }
        } else if ( iHashDisplaynameMapping.contains(aProfileFingerPrint ) &&
                    aDisplayName.length() > 0 ) {
            QString& contentAsDescriptor ( iHashDisplaynameMapping[aProfileFingerPrint] ) ;
            contentAsDescriptor = aDisplayName ;
        }
    } else {
        QLOG_STR("Offered display name was profile hash -> discarding") ;
    }
}

void Controller::displayFileInfoOnUi(const BinaryFile& aFileMetadata) {
    QMessageBox infoMessage ;
    QStringList info ;
    info.append(tr("SHA1: ")) ;
    info.append(aFileMetadata.iFingerPrint.toString()) ;
    info.append("\n") ;

    if ( aFileMetadata.iMimeType.length() > 0 ) {
        info.append(tr("Mime-Type: ")) ;
        info.append(aFileMetadata.iMimeType) ;
        info.append("\n") ;
    }

    if ( aFileMetadata.iDescription.length() > 0 ) {
        info.append(tr("Description: ")) ;
        info.append(aFileMetadata.iDescription) ;
        info.append("\n") ;
    }

    if ( aFileMetadata.iOwner.length() > 0 ) {
        info.append(tr("Publisher: ")) ;
        info.append(aFileMetadata.iOwner) ;
        info.append("\n") ;
    }

    if ( aFileMetadata.iContentOwner.length() > 0 ) {
        info.append(tr("Content owner: ")) ;
        info.append(aFileMetadata.iContentOwner) ;
        info.append("\n") ;
    }

    if ( aFileMetadata.iLicense.length() > 0 ) {
        info.append(tr("License: ")) ;
        info.append(aFileMetadata.iLicense) ;
        info.append("\n") ;
    }

    if ( aFileMetadata.iFileName.length() > 0 ) {
        info.append(tr("Name: ")) ;
        info.append(aFileMetadata.iFileName) ;
        info.append("\n") ;
    }

    QDateTime d ;
    d.setTime_t(aFileMetadata.iTimeOfPublish) ;
    info.append(tr("Date: ")) ;
    info.append(d.toString(Qt::SystemLocaleShortDate)) ;
    info.append("\n") ;

    infoMessage.setText(info.join("")) ;
    infoMessage.setStandardButtons( QMessageBox::Ok );
    infoMessage.exec() ;
}

void Controller::sendProfileUpdateQuery(const Hash& aProfileFingerPrint,
                                        const Hash& aProfileNodeFingerPrint ) {
    NetworkRequestExecutor::NetworkRequestQueueItem req ;
    req.iRequestType = RequestForProfilePoll ;
    req.iRequestedItem = aProfileFingerPrint ;
    req.iState = NetworkRequestExecutor::NewRequest ;
    req.iDestinationNode = aProfileNodeFingerPrint ;
    // try to get time of last poll..
    iModel->lock() ;
    req.iTimeStampOfItem = iModel->profileModel().getLastProfileUpdateTime (aProfileFingerPrint) ;
    iModel->addNetworkRequest(req) ;
    iModel->unlock() ;
}

VoiceCallEngine* Controller::voiceCallEngine() {
    if ( !iVoiceCallEngine && iInsideDestructor == false ) {
        iVoiceCallEngine = new VoiceCallEngine(*this,
                                               *iModel) ;
        assert(
            connect(iVoiceCallEngine,
                    SIGNAL(   callStateChanged(quint32,
                                               VoiceCallEngine::CallState) ),
                    iCurrentWidget,
                    SLOT(    callStateChanged(quint32,
                                              VoiceCallEngine::CallState) ),
                    Qt::QueuedConnection )  ) ;
        assert(
            connect(iListener,
                    SIGNAL(  nodeConnectionAttemptStatus(Connection::ConnectionState ,
                             const Hash  ) ),
                    iVoiceCallEngine,
                    SLOT( nodeConnectionAttemptStatus(Connection::ConnectionState ,
                            const Hash  )),
                    Qt::QueuedConnection )  ) ;
    }
    return iVoiceCallEngine ;
}

MVoiceCallEngine* Controller::voiceCallEngineInterface() {
    return this->voiceCallEngine() ;
}

void Controller::addObjectToOpen(QUrl aClassifiedAdsObject) {
    iObjectToOpen = aClassifiedAdsObject ;
}

void Controller::checkForObjectToOpen(const Hash& /* aIgnored */) {
    if ( iObjectToOpen.scheme().length() > 0 && iCurrentWidget ) {
        iCurrentWidget->linkActivated(iObjectToOpen.toString()) ;
    }
    iObjectToOpen.setScheme("") ;
}

void Controller::checkForSharedMemoryContents() {
    if ( iSharedMemory ) {
        iSharedMemory->lock();
    }
    if (iSharedMemory &&
            iSharedMemory->constData() != NULL &&
            iSharedMemory->size() >= 1024 ) {
        QString urlStr ( QString::fromUtf8 ( reinterpret_cast<const char *>(iSharedMemory->constData()) ) ) ;
        QLOG_STR("checkForSharedMemoryContents content = " +
                 urlStr) ;
        QUrl url (urlStr) ;
        if ( url.scheme() == "caprofile" ||
                url.scheme() == "caad" ||
                url.scheme() == "cacomment" ||
                url.scheme() == "cablob"  ) {
            if ( iProfileHash == KNullHash ) {
                // there is no profile in use
                addObjectToOpen(url) ; // <- goes into wait list
            } else {
                iObjectToOpen = url ;
                emit userProfileSelected(iProfileHash) ;
            }
        }
    } else {
        QLOG_STR("checkForSharedMemoryContents foud no content") ;
    }
    if ( iSharedMemory ) {
        iSharedMemory->unlock();
    }
}

#ifdef WIN32
// WIN32 IPC callback
void Controller::newInstanceConnected() {
    QLOG_STR("Controller::newInstanceConnected ") ;
    QLocalSocket *clientConnection = iLocalServer->nextPendingConnection();
    if ( clientConnection ) {
        connect(clientConnection, SIGNAL(disconnected()),
                clientConnection, SLOT(deleteLater()));

        clientConnection->flush();
        clientConnection->disconnectFromServer();
    }
    checkForSharedMemoryContents() ;
    if ( iCurrentWidget ) {
        iCurrentWidget->activateWindow() ;
    }
}
#endif

TclWrapper & Controller::tclWrapper() {
    if ( iTclWrapper == NULL ) {
        QLOG_STR("Controller::tclWrapper instantiates new") ;
        iTclWrapper = new TclWrapper(*iModel,*this) ;
        connect(iTclWrapper,
                SIGNAL(error(MController::CAErrorSituation,
                             const QString&) ),
                this,
                SLOT(handleError(MController::CAErrorSituation,
                                 const QString&)),
                Qt::QueuedConnection ) ;
        if ( iDbRetrievalEngine ) {
            assert(
                connect(iTclWrapper,
                        SIGNAL(finished()),
                        iDbRetrievalEngine,
                        SLOT(stopRetrieving()),
                        Qt::QueuedConnection )) ;
        } else {
            QLOG_STR("TCL Wrapper instantiated by retrieval engine missing?");
        }
    }
    return *iTclWrapper ;
}

QWidget* Controller::frontWidget() {
    return iCurrentWidget ;
}


QString Controller::getFileName(bool& aSuccess,
                                bool aIsSaveFile , 
                                QString aSuggestedFileName ) {
    if ( iGetFileNameDialog || iGetFileNameSemaphore.available() == 0 ) {
        aSuccess = false ; 
        return QString::null ; 
    }
    iGetFileNameResult = QString::null ; 
    iGetFileNameSuccess = false ; 
    // lock mutex once
    QLOG_STR("iGetFileNameMutex.acquire") ; 
    iGetFileNameSemaphore.acquire(1) ; 
    // go to UI thread:
    QLOG_STR("emit getFileNameSignal") ; 
    emit startGettingFileName(aSuggestedFileName, aIsSaveFile) ; 
    // stop here until UI thread calls iGetFileNameMutex.release
    QLOG_STR("iGetFileNameMutex.acquire 2") ; 
    iGetFileNameSemaphore.acquire(1) ; 
    QLOG_STR("iGetFileNameMutex.release") ; 
    iGetFileNameSemaphore.release(1) ; 
    aSuccess = iGetFileNameSuccess ; 
    return iGetFileNameResult ; 
}

// this will be executed in UI thread, called from getFileName
// method via queued connection
void Controller::getFileNameSlot(QString aSuggestedFileName,bool aIsSaveFile) {
    QLOG_STR("getFileNameSlot in") ; 
    if ( ( iGetFileNameDialog = new QFileDialog() ) != NULL ) {

        if ( aIsSaveFile ) {
            iGetFileNameDialog->setFileMode(QFileDialog::AnyFile);
            iGetFileNameDialog->setAcceptMode(QFileDialog::AcceptSave) ; 
        } else {
            iGetFileNameDialog->setFileMode(QFileDialog::ExistingFile);
            iGetFileNameDialog->setAcceptMode(QFileDialog::AcceptOpen) ;
        }
        if ( aSuggestedFileName.length() > 0 ) {
            iGetFileNameDialog->setNameFilter(aSuggestedFileName);
        }
        QStringList fileNames;
        if (iGetFileNameDialog->exec() && iGetFileNameDialog )
            fileNames = iGetFileNameDialog->selectedFiles();
        if ( fileNames.count() > 0 ) {
            iGetFileNameResult = fileNames.at(0) ; 
            iGetFileNameSuccess = true ;
        }
        delete iGetFileNameDialog ; 
    }
    iGetFileNameDialog = NULL ; 
    iGetFileNameSemaphore.release(1) ; 
    QLOG_STR("getFileNameSlot out") ; 
}