-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcontroller.cpp
1633 lines (1528 loc) · 63.4 KB
/
controller.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*-C++-*- -*-coding: utf-8-unix;-*-
Classified Ads is Copyright (c) Antti Järvinen 2013-2021.
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,