-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMainApp.cpp
2849 lines (2556 loc) · 110 KB
/
MainApp.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
#include <QTextEdit>
#include <QMessageBox>
#include "MainApp.h"
#include "ConsoleWindow.h"
#include "Util.h"
#include "Version.h"
#include <qglobal.h>
#include <QEvent>
#include <cstdlib>
#include <QSettings>
#include <QMetaType>
#include <QStatusBar>
#include <QTimer>
#include <QKeyEvent>
#include <QFileDialog>
#include <QTextStream>
#include <QFile>
#include <QFileInfo>
#include <QPixmap>
#include <QIcon>
#include <QDir>
#include <QDesktopWidget>
#include <QMutexLocker>
#include <QSystemTrayIcon>
#include <QMenu>
#include <QAction>
#include <QProgressDialog>
#include <QDialog>
#include <QGLFormat>
#include <QGLContext>
#include <QLocale>
#include "Icon.xpm"
#include "ParWindowIcon.xpm"
#include "ConfigureDialogController.h"
#include "ChanMappingController.h"
#include "GraphsWindow.h"
#include "Sha1VerifyTask.h"
#include "Par2Window.h"
#include "ui_StimGLIntegration.h"
#include "StimGL_SpikeGL_Integration.h"
#include "ui_TextBrowser.h"
#include "ui_CommandServerOptions.h"
#include "CommandServer.h"
#include "ui_TempFileDialog.h"
#include "FileViewerWindow.h"
#include <algorithm>
#include "SpatialVisWindow.h"
#include "Bug_ConfigDialog.h"
#include "Bug_Popout.h"
#include "FG_ConfigDialog.h"
#include "ui_SampleBuf_Dialog.h"
Q_DECLARE_METATYPE(unsigned);
namespace {
struct Init {
Init() {
qRegisterMetaType<unsigned>("unsigned");
qRegisterMetaType<QVector<int> >("QVector<int>");
}
};
Init * volatile init = 0;
class LogLineEvent : public QEvent
{
public:
LogLineEvent(const QString &str, const QColor & color)
: QEvent((QEvent::Type)MainApp::LogLineEventType), str(str), color(color)
{}
QString str;
QColor color;
};
class StatusMsgEvent : public QEvent
{
public:
StatusMsgEvent(const QString &msg, int timeout)
: QEvent((QEvent::Type)MainApp::StatusMsgEventType), msg(msg), timeout(timeout)
{}
QString msg;
int timeout;
};
};
MainApp * MainApp::singleton = 0;
MainApp::MainApp(int & argc, char ** argv)
: QApplication(argc, argv, true), mut(QMutex::Recursive), consoleWindow(0), debug(false), initializing(true), sysTray(0), nLinesInLog(0), nLinesInLogMax(1000), task(0), graphsWindow(0), spatialWindow(0), bugWindow(0), fgWindow(0), notifyServer(0), commandServer(0), fastSettleRunning(false), helpWindow(0), noHotKeys(false), pdWaitingForStimGL(false), precreateDialog(0), pregraphDummyParent(0), maxPreGraphs(/*MAX_NUM_GRAPHS_PER_GRAPH_TAB*/4), tPerGraph(0.), acqStartingDialog(0), doBugAcqInstead(false)
{
got_sgl_ended = got_sgl_save = got_sgl_started = false;
reader = 0;
gthread1 = gthread2 = 0;
dthread = 0;
samplesBuffer = 0;
need2FreeSamplesBuffer = false;
scanCt = 0;
scanSkipCt = 0;
QLocale::setDefault(QLocale::c());
setApplicationName("SpikeGL");
setApplicationVersion(VERSION_STR);
sb_Timeout = 0;
if (singleton) {
QMessageBox::critical(0, "Invariant Violation", "Only 1 instance of MainApp allowed per application!");
std::exit(1);
}
singleton = this;
if (!::init) ::init = new Init;
setQuitOnLastWindowClosed(false);
loadSettings();
initActions();
createIcons();
configCtl = new ConfigureDialogController(this);
bugConfig = new Bug_ConfigDialog(configCtl->acceptedParams, this);
fgConfig = new FG_ConfigDialog(configCtl->acceptedParams, this);
installEventFilter(this); // filter our own events
consoleWindow = new ConsoleWindow;
#ifdef Q_OS_MACX
/* add the console window to the Window menu, which, on OSX is an app-global menu
-- on other platform the console window is *in* the window menu so only needs to be done on OSX */
windowMenuAdd(consoleWindow);
#endif
Connect(this, SIGNAL(do_updateWindowTitles()), this, SLOT(updateWindowTitles()));
Connect(this, SIGNAL(do_stopTask()), this, SLOT(stopTask()));
defaultLogColor = consoleWindow->textEdit()->textColor();
consoleWindow->setAttribute(Qt::WA_DeleteOnClose, false);
Connect(consoleWindow->windowMenu(), SIGNAL(aboutToShow()), this, SLOT(windowMenuAboutToShow()));
sysTray = new QSystemTrayIcon(this);
sysTray->setContextMenu(new QMenu(consoleWindow));
sysTray->contextMenu()->addAction(hideUnhideConsoleAct);
sysTray->contextMenu()->addAction(hideUnhideGraphsAct);
sysTray->contextMenu()->addSeparator();
sysTray->contextMenu()->addAction(aboutAct);
sysTray->contextMenu()->addSeparator();
sysTray->contextMenu()->addAction(quitAct);
sysTray->setIcon(appIcon);
sysTray->show();
par2Win = new Par2Window(0);
par2Win->setAttribute(Qt::WA_DeleteOnClose, false);
par2Win->setWindowTitle(QString(APPNAME) + " - Par2 Redundancy Tool");
par2Win->setWindowIcon(QPixmap(ParWindowIcon_xpm));
Connect(par2Win, SIGNAL(closed()), this, SLOT(par2WinClosed()));
Log() << VERSION_STR;
Log() << "Application started";
if (getNProcessors() > 1)
setProcessAffinityMask(0x1); // set it to core 1
consoleWindow->installEventFilter(this);
consoleWindow->textEdit()->installEventFilter(this);
consoleWindow->resize(800, 300);
consoleWindow->show();
setupStimGLIntegration();
setupCommandServer();
QTimer *timer = new QTimer(this);
Connect(timer, SIGNAL(timeout()), this, SLOT(updateStatusBar()));
timer->setSingleShot(false);
timer->start(247); // update status bar every 247ms.. i like this non-round-numbre.. ;)
acqWaitingForPrecreate = false;
pregraphTimer = new QTimer(this);
Connect(pregraphTimer, SIGNAL(timeout()), this, SLOT(precreateGraphs()));
pregraphTimer->setSingleShot(false);
pregraphTimer->start(0);
appInitialized();
}
MainApp::~MainApp()
{
stopTask();
Log() << "Application shutting down..";
Status() << "Application shutting down.";
if (commandServer) delete commandServer, commandServer = 0;
CommandServer::deleteAllActiveConnections();
saveSettings();
delete par2Win, par2Win = 0;
delete configCtl, configCtl = 0;
delete bugConfig, bugConfig = 0;
delete fgConfig, fgConfig = 0;
delete sysTray, sysTray = 0;
delete helpWindow, helpWindow = 0;
delete pregraphDummyParent, pregraphDummyParent = 0;
pregraphs.clear();
singleton = 0;
}
bool MainApp::isDebugMode() const
{
// always true for now..
return debug;
}
bool MainApp::isSaveCBEnabled() const { return saveCBEnabled; }
bool MainApp::isDSFacilityEnabled() const { return dsFacilityEnabled; }
bool MainApp::isConsoleHidden() const
{
return !consoleWindow || consoleWindow->isHidden();
}
void MainApp::toggleDebugMode()
{
debug = !debug;
Log() << "Debug mode: " << (debug ? "on" : "off");
saveSettings();
}
void MainApp::toggleExcessiveDebugMode()
{
excessiveDebug = !excessiveDebug;
Debug() << "Excessive Debug mode: " << (excessiveDebug ? "on" : "off");
saveSettings();
}
void MainApp::toggleShowChannelSaveCB()
{
saveCBEnabled = !saveCBEnabled;
if (graphsWindow) graphsWindow->hideUnhideSaveChannelCBs();
saveSettings();
}
void MainApp::toggleEnableDSFacility()
{
dsFacilityEnabled = !dsFacilityEnabled;
if(dsFacilityEnabled)
tempFileSizeAct->setEnabled(true);
else {
tempFileSizeAct->setEnabled(false);
tmpDataFile.close(); // immediately deletes file, resetting settings
}
saveSettings();
}
bool MainApp::isShiftPressed()
{
return (keyboardModifiers() & Qt::ShiftModifier);
}
bool MainApp::processKey(QKeyEvent *event)
{
switch (event->key()) {
case 'd':
case 'D':
if (event->modifiers() == Qt::ControlModifier)
toggleExcessiveDebugAct->trigger();
else
toggleDebugAct->trigger();
return true;
case 'c':
case 'C':
if (event->modifiers()) // trap for hotkey if no ctrl of shift pressed unmodified.
return false;
hideUnhideConsoleAct->trigger();
return true;
case 'g':
case 'G':
if (event->modifiers()) // trap for hotkey if no ctrl of shift pressed unmodified.
return false;
hideUnhideGraphsAct->trigger();
return true;
case 'n':
case 'N':
if (event->modifiers()) // trap for hotkey if no ctrl of shift pressed unmodified.
return false;
newAcqAct->trigger();
return true;
case 'b':
case 'B':
if (event->modifiers()) // trap for hotkey if no ctrl of shift pressed unmodified.
return false;
bugAcqAct->trigger();
return true;
case 'f':
case 'F':
if (event->modifiers()) // trap for hotkey if no ctrl of shift pressed unmodified.
return false;
fgAcqAct->trigger();
return true;
case 'o':
case 'O':
if (event->modifiers()) // trap for hotkey if no ctrl of shift pressed unmodified.
return false;
fileOpenAct->trigger();
return true;
case Qt::Key_Escape:
if (event->modifiers()) // trap for hotkey if no ctrl of shift pressed unmodified.
return false;
stopAcq->trigger();
return true;
}
return false;
}
bool MainApp::eventFilter(QObject *watched, QEvent *event)
{
int type = static_cast<int>(event->type());
if (type == QEvent::KeyPress) {
// globally forward all keypresses
// if they aren't handled, then return false for normal event prop.
QKeyEvent *k = dynamic_cast<QKeyEvent *>(event);
if (k && !noHotKeys
&& watched != helpWindow && (!helpWindow || !Util::objectHasAncestor(watched, helpWindow))
&& watched != par2Win && (!par2Win || !Util::objectHasAncestor(watched, par2Win))
&& (watched == graphsWindow || watched == consoleWindow || (spatialWindow && watched == spatialWindow) || (bugWindow && watched == bugWindow) || (fgWindow && watched == fgWindow) || watched == consoleWindow->textEdit() || ((!graphsWindow || watched != graphsWindow->saveFileLineEdit()) && Util::objectHasAncestor(watched, graphsWindow)))) {
if (processKey(k)) {
event->accept();
return true;
}
}
}
if (type == QEvent::Close) {
FileViewerWindow *fvw = 0;
if (watched == graphsWindow) {
// request to close the graphsWindow.. this stops the acq -- ask the user to confirm.. do this after this event handler runs, so enqueue it with a timer
QTimer::singleShot(1, this, SLOT(maybeCloseCurrentIfRunning()));
event->ignore();
return true;
} else if ((precreateDialog && watched == precreateDialog) || (acqStartingDialog && watched == acqStartingDialog)) {
event->ignore();
return true;
} else if ( (fvw = dynamic_cast<FileViewerWindow *>(watched)) ) {
if (fvw->queryCloseOK()) {
windowMenuRemove(fvw);
fvw->deleteLater(); // schedule window for deletion...
} else
event->ignore();
return true; // tell Qt we handled the event
}
}
if (watched == consoleWindow) {
ConsoleWindow *cw = dynamic_cast<ConsoleWindow *>(watched);
if (type == LogLineEventType) {
LogLineEvent *evt = dynamic_cast<LogLineEvent *>(event);
if (evt && cw->textEdit()) {
QTextEdit *te = cw->textEdit();
QColor origcolor = te->textColor();
te->setTextColor(evt->color);
te->append(evt->str);
// make sure the log textedit doesn't grow forever
// so prune old lines when a threshold is hit
nLinesInLog += evt->str.split("\n").size();
if (nLinesInLog > nLinesInLogMax) {
const int n2del = MAX(nLinesInLogMax/10, nLinesInLog-nLinesInLogMax);
QTextCursor cursor = te->textCursor();
cursor.movePosition(QTextCursor::Start);
for (int i = 0; i < n2del; ++i) {
cursor.movePosition(QTextCursor::Down, QTextCursor::KeepAnchor);
}
cursor.removeSelectedText(); // deletes the lines, leaves a blank line
nLinesInLog -= n2del;
}
te->setTextColor(origcolor);
te->moveCursor(QTextCursor::End);
te->ensureCursorVisible();
return true;
} else {
return false;
}
} else if (type == StatusMsgEventType) {/*
StatusMsgEvent *evt = dynamic_cast<StatusMsgEvent *>(event);
if (evt && cw->statusBar()) {
cw->statusBar()->showMessage(evt->msg, evt->timeout);
return true;
} else {
return false;
}
*/
return true;
}
}
if (watched == this) {
if (type == QuitEventType) {
quit();
return true;
}
}
// otherwise do default action for event which probably means
// propagate it down
return QApplication::eventFilter(watched, event);
}
void MainApp::logLine(const QString & line, const QColor & c)
{
qApp->postEvent(consoleWindow, new LogLineEvent(line, c.isValid() ? c : defaultLogColor));
}
void MainApp::loadSettings()
{
QSettings settings(SETTINGS_DOMAIN, SETTINGS_APP);
settings.beginGroup("MainApp");
debug = settings.value("debug", true).toBool();
excessiveDebug = settings.value("excessiveDebug", excessiveDebug).toBool();
saveCBEnabled = settings.value("saveChannelCB", true).toBool();
dsFacilityEnabled = settings.value("dsFacilityEnabled", false).toBool();
tmpDataFile.setTempFileSize(settings.value("dsTemporaryFileSize", 1048576000).toLongLong());
mut.lock();
#ifdef Q_OS_WIN
outDir = settings.value("outDir", "c:/users/code").toString();
#else
outDir = settings.value("outDir", QDir::homePath() ).toString();
#endif
lastOpenFile = settings.value("lastFileOpenFile", "").toString();
m_sortGraphsByElectrodeId = settings.value("sortGraphsByElectrodeId", false).toBool();
mut.unlock();
{
StimGLIntegrationParams & p(stimGLIntParams);
p.iface = settings.value("StimGLInt_Listen_Interface", "0.0.0.0").toString();
p.port = settings.value("StimGLInt_Listen_Port", SPIKE_GL_NOTIFY_DEFAULT_PORT).toUInt();
p.timeout_ms = settings.value("StimGLInt_TimeoutMS", SPIKE_GL_NOTIFY_DEFAULT_TIMEOUT_MSECS ).toInt();
}
{
CommandServerParams & p (commandServerParams);
p.iface = settings.value("CmdSrvr_Iface", "0.0.0.0").toString();
p.port = settings.value("CmdSrvr_Port", DEFAULT_COMMAND_PORT).toUInt();
p.timeout_ms = settings.value("CmdSrvr_TimeoutMS", DEFAULT_COMMAND_TIMEOUT_MS).toInt();
p.enabled = settings.value("CmdSrvr_Enabled", true).toBool();
}
{
BufSizesParams & p (bufSizesParams);
#ifdef WIN64
p.regularMB = settings.value("BufSize_RegularAcq_MBx64", unsigned(DEF_SAMPLES_SHM_SIZE_REG)/(1024U*1024U)).toUInt();
p.fgShmMB = settings.value("BufSize_FGAcq_MBx64", unsigned(DEF_SAMPLES_SHM_SIZE_FG)/(1024U*1024U)).toUInt();
#else
p.regularMB = settings.value("BufSize_RegularAcq_MB", unsigned(DEF_SAMPLES_SHM_SIZE_REG)/(1024U*1024U)).toUInt();
p.fgShmMB = settings.value("BufSize_FGAcq_MB", unsigned(DEF_SAMPLES_SHM_SIZE_FG)/(1024U*1024U)).toUInt();
#endif
}
}
void MainApp::saveSettings()
{
QSettings settings(SETTINGS_DOMAIN, SETTINGS_APP);
settings.beginGroup("MainApp");
settings.setValue("debug", debug);
settings.setValue("excessiveDebug", excessiveDebug);
settings.setValue("saveChannelCB", saveCBEnabled);
settings.setValue("dsFacilityEnabled", dsFacilityEnabled);
settings.setValue("dsTemporaryFileSize", tmpDataFile.getTempFileSize());
settings.setValue("sortGraphsByElectrodeId", m_sortGraphsByElectrodeId);
mut.lock();
settings.setValue("outDir", outDir);
mut.unlock();
settings.setValue("lastFileOpenFile", lastOpenFile);
{
StimGLIntegrationParams & p(stimGLIntParams);
settings.setValue("StimGLInt_Listen_Interface", p.iface);
settings.setValue("StimGLInt_Listen_Port", p.port);
settings.setValue("StimGLInt_TimeoutMS", p.timeout_ms);
}
{
CommandServerParams & p(commandServerParams);
settings.setValue("CmdSrvr_Iface", p.iface);
settings.setValue("CmdSrvr_Port", p.port);
settings.setValue("CmdSrvr_TimeoutMS", p.timeout_ms);
settings.setValue("CmdSrvr_Enabled", p.enabled);
}
{
BufSizesParams & p (bufSizesParams);
#ifdef WIN64
settings.setValue("BufSize_RegularAcq_MBx64", p.regularMB);
settings.setValue("BufSize_FGAcq_MBx64", p.fgShmMB);
#else
settings.setValue("BufSize_RegularAcq_MB", p.regularMB);
settings.setValue("BufSize_FGAcq_MB", p.fgShmMB);
#endif
}
}
void MainApp::statusMsg(const QString &msg, int timeout)
{
if (consoleWindow && consoleWindow->statusBar()) {
QStatusBar *sbar = consoleWindow->statusBar();
QFont f(sbar->font());
static unsigned default_pointsize = 0;
if (!default_pointsize) default_pointsize = f.pointSize();
else f.setPointSize(default_pointsize);
if (task && task->isRunning())
#ifdef Q_OS_WIN
f.setPointSize(default_pointsize-1);
#else
f.setPointSize(default_pointsize-2);
#endif
// while (QFontMetrics(f).width(msg) > sbar->width()) {
// f.setPointSize(f.pointSize()-1);
// if (f.pointSize() == 5) break;
// }
sbar->setFont(f);
consoleWindow->statusBar()->showMessage(msg, timeout);
}
}
void MainApp::sysTrayMsg(const QString & msg, int timeout_msecs, bool iserror)
{
if (sysTray) {
sysTray->showMessage(APPNAME, msg, iserror ? QSystemTrayIcon::Critical : QSystemTrayIcon::Information, timeout_msecs);
}
}
QString MainApp::sbString() const
{
QMutexLocker ml(&mut);
return sb_String;
}
void MainApp::setSBString(const QString &msg, int timeout)
{
QMutexLocker ml(&mut);
sb_String = msg;
sb_Timeout = timeout;
}
void MainApp::updateStatusBar()
{
QMutexLocker ml(&mut);
sysTray->setToolTip(sb_String);
statusMsg(sb_String, sb_Timeout);
}
/** \brief A helper class that helps prevent reentrancy into certain functions.
Mainly MainApp::pickOutputDir() makes use of this class to prevent recursive calls into itself.
Functions that want to be mutually exclusive with respect to each other
and non-reentrant with respect to themselves need merely construct an
instance of this class as a local variable, and
then reentrancy into the function can be guarded by checking against
this class's operator bool() function.
*/
struct ReentrancyPreventer
{
static volatile int ct;
/// Increments a global counter.
/// The global counter is 1 if only 1 instance of this class exists throughout the application, and >1 otherwise.
ReentrancyPreventer() { ++ct; }
/// Decrements the global counter.
/// If it reaches 0 this was the last instance of this class and there are no other ones active globally.
~ReentrancyPreventer() {--ct; }
/// Returns true if the global counter is 1 (that is, only one globally active instance of this class exists throughout the application), and false otherwise. If false is returned, you can then abort your function early as a reentrancy condition has been detected.
operator bool() const { return ct == 1; }
};
volatile int ReentrancyPreventer::ct = 0;
void MainApp::about()
{
QMessageBox::about(consoleWindow, "About " APPNAME,
VERSION_STR
"\n\n(C) 2010-2016 Calin A. Culianu <[email protected]>\n\n"
"Developed for the Anthony Leonardo lab at\n"
"Janelia Farm Research Campus, HHMI\n\n"
"Software License: GPL v2 or later\n\n"
"Bitcoin Address: 1Ca1inQuedcKdyELCTmN8AtKTTehebY4mC\n"
"Git Repository: https://github.com/cculianu/SpikeGL"
);
// find the QLabel for the above text to make it selectable...
foreach (QWidget *w, QApplication::topLevelWidgets()) {
//Debug() << "Window title: " << w->windowTitle();
QList<QLabel *> chlds = w->findChildren<QLabel *>();
foreach (QLabel *l, chlds) {
//Debug() << " Label text: " << l->text();
if (l->text().startsWith(VERSION_STR)) {
// found it! make text selectable so they can email or bitcoin me! :)
l->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);
}
}
}
}
bool MainApp::setOutputDirectory(const QString & dpath)
{
QDir d(dpath);
if (!d.exists()) return false;
mut.lock();
outDir = dpath;
mut.unlock();
return true;
}
void MainApp::pickOutputDir()
{
ReentrancyPreventer rp; if (!rp) return;
mut.lock();
QString od = outDir;
mut.unlock();
noHotKeys = true;
if ( !(od = QFileDialog::getExistingDirectory(0, "Choose a directory to which to save output files", od, QFileDialog::DontResolveSymlinks|QFileDialog::ShowDirsOnly)).isNull() ) {
mut.lock();
outDir = od;
mut.unlock();
saveSettings(); // just to remember the file *now*
}
noHotKeys = false;
}
void MainApp::createIcons()
{
appIcon.addPixmap(QPixmap(Icon_xpm));
bugIcon.addPixmap(QPixmap(QString(":/Bug3/dragonfly.png")));
}
void MainApp::hideUnhideConsole()
{
if (consoleWindow) {
if (consoleWindow->isHidden()) {
consoleWindow->show();
#ifdef Q_OS_MACX
windowMenuAdd(consoleWindow);
#endif
} else {
bool hadfocus = ( focusWidget() == consoleWindow );
consoleWindow->hide();
#ifdef Q_OS_MACX
windowMenuRemove(consoleWindow);
#endif
if (graphsWindow && hadfocus) graphsWindow->setFocus(Qt::OtherFocusReason);
}
}
}
void MainApp::hideUnhideGraphs()
{
if (graphsWindow) {
if (graphsWindow->isHidden()) {
graphsWindow->clearGraph(-1);
graphsWindow->show();
} else {
bool hadfocus = ( focusWidget() == graphsWindow );
graphsWindow->hide();
if (consoleWindow && hadfocus) consoleWindow->setFocus(Qt::OtherFocusReason);
}
}
}
void MainApp::initActions()
{
Connect( quitAct = new QAction("&Quit", this) ,
SIGNAL(triggered()), this, SLOT(maybeQuit()));
Connect( toggleDebugAct = new QAction("&Debug Mode D", this) ,
SIGNAL(triggered()), this, SLOT(toggleDebugMode()));
Connect( toggleExcessiveDebugAct = new QAction("Excessive Debug Mode Ctrl+D", this) ,
SIGNAL(triggered()), this, SLOT(toggleExcessiveDebugMode()));
toggleDebugAct->setCheckable(true);
toggleDebugAct->setChecked(isDebugMode());
toggleExcessiveDebugAct->setCheckable(true);
toggleExcessiveDebugAct->setChecked(excessiveDebug);
Connect( chooseOutputDirAct = new QAction("Choose &Output Directory...", this),
SIGNAL(triggered()), this, SLOT(pickOutputDir()));
Connect( hideUnhideConsoleAct = new QAction("Hide/Unhide &Console C", this),
SIGNAL(triggered()), this, SLOT(hideUnhideConsole()));
Connect( hideUnhideGraphsAct = new QAction("Hide/Unhide &Graphs G", this),
SIGNAL(triggered()), this, SLOT(hideUnhideGraphs()));
hideUnhideGraphsAct->setEnabled(false);
Connect( aoPassthruAct = new QAction("AO Passthru...", this),
SIGNAL(triggered()), this, SLOT(respecAOPassthru()));
aoPassthruAct->setEnabled(false);
Connect( helpAct = new QAction("SpikeGL &Help", this),
SIGNAL(triggered()), this, SLOT(help()));
Connect( aboutAct = new QAction("&About", this),
SIGNAL(triggered()), this, SLOT(about()));
Connect(aboutQtAct = new QAction("About &Qt", this),
SIGNAL(triggered()), this, SLOT(aboutQt()));
Connect( newAcqAct = new QAction("New NI-DAQ Acquisition... &N", this),
SIGNAL(triggered()), this, SLOT(newAcq()));
Connect( bugAcqAct = new QAction("New Bug Acquisition... &B", this),
SIGNAL(triggered()), this, SLOT(bugAcq()));
Connect( fgAcqAct = new QAction("New Framegrabber Acquisition... &F", this),
SIGNAL(triggered()), this, SLOT(fgAcq()));
Connect( stopAcq = new QAction("Stop Running Acquisition ESC", this),
SIGNAL(triggered()), this, SLOT(maybeCloseCurrentIfRunning()) );
stopAcq->setEnabled(false);
Connect( verifySha1Act = new QAction("Verify SHA1...", this),
SIGNAL(triggered()), this, SLOT(verifySha1()) );
Connect( par2Act = new QAction("PAR2 Redundancy Tool", this),
SIGNAL(triggered()), this, SLOT(showPar2Win()) );
Connect( stimGLIntOptionsAct = new QAction("StimGL Integration Options", this),
SIGNAL(triggered()), this, SLOT(execStimGLIntegrationDialog()) );
Connect( commandServerOptionsAct = new QAction("Command Server Options", this),
SIGNAL(triggered()), this, SLOT(execCommandServerOptionsDialog()) );
Connect( showChannelSaveCBAct = new QAction("Show Save Checkboxes", this),
SIGNAL(triggered()), this, SLOT(toggleShowChannelSaveCB()) );
showChannelSaveCBAct->setCheckable(true);
showChannelSaveCBAct->setChecked(isSaveCBEnabled());
Connect( enableDSFacilityAct = new QAction("Enable Matlab Data API", this) ,
SIGNAL(triggered()), this, SLOT(toggleEnableDSFacility()));
enableDSFacilityAct->setCheckable(true);
enableDSFacilityAct->setChecked(isDSFacilityEnabled());
Connect( tempFileSizeAct = new QAction("Matlab Data API Tempfile...", this),
SIGNAL(triggered()), this, SLOT(execDSTempFileDialog()) );
tempFileSizeAct->setEnabled(isDSFacilityEnabled());
Connect( bufferSizesDialogAct = new QAction("Specify Realtime Buffer Sizes...", this),
SIGNAL(triggered()), this, SLOT(execBufferSizesDialog()) );
Connect( fileOpenAct = new QAction("Open... &O", this), SIGNAL(triggered()), this, SLOT(fileOpen()));
Connect( bringAllToFrontAct = new QAction("Bring All to Front", this), SIGNAL(triggered()), this, SLOT(bringAllToFront()) );
Connect( sortGraphsByElectrodeAct = new QAction("Sort graphs by Electrode", this), SIGNAL(triggered()), this, SLOT(optionsSortGraphsByElectrode()) );
sortGraphsByElectrodeAct->setCheckable(true);
sortGraphsByElectrodeAct->setChecked(m_sortGraphsByElectrodeId);
}
static inline unsigned long computeSamplesShmPageSize(double samplingRateHz, unsigned scanSizeSamps, bool lowLatency, unsigned metaBytesPerScan = 0, unsigned *metaBytesPerPage = 0) {
unsigned long oneScanBytes = scanSizeSamps * sizeof(int16);
unsigned long nScansPerPage = (unsigned long)qRound(samplingRateHz * double((double)SAMPLES_SHM_DESIRED_PAGETIME_MS/1000.0));
if (lowLatency) nScansPerPage /= 2;
if (!nScansPerPage) nScansPerPage = 1;
if (metaBytesPerPage) *metaBytesPerPage = nScansPerPage * metaBytesPerScan;
return nScansPerPage*oneScanBytes + metaBytesPerScan*nScansPerPage;
}
bool MainApp::startAcq(QString & errTitle, QString & errMsg)
{
QMutexLocker ml (&mut);
// NOTE: acq cannot be running here!
if (isAcquiring()) {
errTitle = "Already running!";
errMsg = "The acquisition is already running. Please stop it first.";
return false;
}
fgWindow = 0;
scanCt = 0;
scanSkipCt = 0;
lastScanSz = 0;
stopRecordAtSamp = -1;
tNow = getTime();
taskShouldStop = false;
pdWaitingForStimGL = false;
queuedParams.clear();
sgl_ended = sgl_save = sgl_started = SGL_Parms();
got_sgl_ended = got_sgl_save = got_sgl_started = false;
if (!configCtl || !bugConfig || !fgConfig) {
errTitle = "Internal Error";
errMsg = "configCtl and/or bugConfig and/or fgConfig pointer is NULL! Shouldn't happen!";
return false;
}
DAQ::Params & params(doBugAcqInstead ? bugConfig->acceptedParams : (doFGAcqInstead ? fgConfig->acceptedParams : configCtl->acceptedParams));
lastNPDSamples.clear();
lastNPDSamples.reserve(params.pdThreshW);
if (!params.stimGlTrigResave) {
if (!dataFile.openForWrite(params)) {
errTitle = "Error Opening File!";
errMsg = QString("Could not open data file `%1'!").arg(params.outputFile);
return false;
}
if (!queuedParams.isEmpty()) stimGL_SaveParams("", queuedParams);
}
if (samplesBuffer && need2FreeSamplesBuffer) free(samplesBuffer);
samplesBuffer = 0; need2FreeSamplesBuffer = false;
int shmSizeMB = doFGAcqInstead ? bufSizesParams.fgShmMB : bufSizesParams.regularMB;
if (sizeof(void *) <= 4 && shmSizeMB > 2047) shmSizeMB = 2047;
const long shmSizeBytes = long(shmSizeMB)*1024L*1024L;
if (doFGAcqInstead) {
if (!shm.isAttached()) {
shm.setKey(SAMPLES_SHM_NAME);
if (shm.attach()) {
shm.detach(); // for some reason doing this under windows often 'fixes' the problem
if (shm.attach()) {
shm.detach();
errTitle = "Shared Memory Error";
errMsg = QString("The shared memory segment already exists.\n\nPlease kill all instances of SpikeGL and its subprocesses to continue.");
Error() << errTitle << ": " << errMsg;
return false;
}
}
if (!shm.create(shmSizeBytes)) {
errTitle = "Shared Memory Error";
errMsg = QString("Error creating the shared memory segment.\n\nError was #") + QString::number(int(shm.error())) + ": \n`" + shm.errorString() + "'\n\nSpikeGL requires enough memory to create a buffer of size " + QString::number(shmSizeMB) + " MB.";
return false;
} else {
if ( shm.size() < shmSizeBytes ) {
shm.detach();
errTitle = "Shm Segment Wrong Size";
errMsg = QString("Shm segment attached ok, but it is too small. Required size: ") + QString::number(shmSizeBytes) + " Current size: " + QString::number(shm.size());
return false;
} else {
Log() << "Successfully created '" << SAMPLES_SHM_NAME <<"' shm segment of size " << QString::number(shmSizeMB) << "MB";
}
}
} else if ( shm.size() < shmSizeBytes ) {
shm.detach();
errTitle = "Shm Segment Wrong Size";
errMsg = QString("Shm segment attached ok, but it is too small. Required size: ") + QString::number(shmSizeBytes) + " Current size: " + QString::number(shm.size());
return false;
}
samplesBuffer = shm.data();
need2FreeSamplesBuffer = false;
} else { // not framegrabber acq, so don't use a SHM, instead just malloc the required memory
need2FreeSamplesBuffer = false;
samplesBuffer = malloc(shmSizeBytes);
if (!samplesBuffer) {
errTitle = "Not Enough Memory";
errMsg = QString("Failed to allocate a sample buffer of size ") + QString::number(shmSizeMB) + " MB.\n\nSpikeGL requires a large sample buffer to avoid potential overruns. Free up some memory or upgrade your system! ";
return false;
}
need2FreeSamplesBuffer = true;
Log() << "Successfully created '" << SAMPLES_SHM_NAME <<"' sample buffer size " << QString::number(shmSizeMB) << "MB";
}
// re-set the data temp file, delete it, etc
tmpDataFile.close();
tmpDataFile.setNChans(params.nVAIChans);
// acq starting dialog block -- show this dialog because the startup is kinda slow..
if (acqStartingDialog) delete acqStartingDialog, acqStartingDialog = 0;
acqStartingDialog = new QMessageBox ( QMessageBox::Information, "DAQ Task Starting Up", "DAQ task starting up, please wait...", QMessageBox::Ok, consoleWindow, Qt::WindowFlags(Qt::Dialog| Qt::MSWindowsFixedSizeDialogHint));
acqStartingDialog->setWindowModality(Qt::ApplicationModal);
QAbstractButton *but = acqStartingDialog->button(QMessageBox::Ok);
if (but) but->hide();
acqStartingDialog->open();
// end acq starting dialog block
preBuf.clear();
preBuf.reserve(0);
if (params.usePD && (params.acqStartEndMode == DAQ::PDStart || params.acqStartEndMode == DAQ::PDStartEnd
|| params.acqStartEndMode == DAQ::AITriggered || params.acqStartEndMode == DAQ::Bug3TTLTriggered)) {
const double sil = params.silenceBeforePD > 0. ? params.silenceBeforePD : DEFAULT_PD_SILENCE;
if (params.stimGlTrigResave) pdWaitingForStimGL = true;
int szSamps = params.nVAIChans*params.srate*sil;
if (szSamps <= 0) szSamps = params.nVAIChans;
if (szSamps % params.nVAIChans)
szSamps += params.nVAIChans - szSamps%params.nVAIChans;
preBuf.reserve(szSamps*sizeof(int16));
char *mem = new char[preBuf.capacity()];
memset(mem, 0, preBuf.capacity());
preBuf.putData(mem, preBuf.capacity());
delete [] mem;
}
if (doFGAcqInstead) {
if (params.fg.disableChanMap) {
// for testing 4/26/16 -- we just sort by intan for testing.
m_sortGraphsByElectrodeId = false;
sortGraphsByElectrodeAct->setChecked(false);
} else {
// hardcoded .. make user experience be that by default, in framegrabber more, we sort graphs by electrode, so that the channel remapping thing looks right onscreen
m_sortGraphsByElectrodeId = true;
sortGraphsByElectrodeAct->setChecked(true);
}
}
graphsWindow = new GraphsWindow(params, 0, dataFile.isOpen(), !doFGAcqInstead, doFGAcqInstead ? params.graphUpdateRate : -1);
graphsWindow->setAttribute(Qt::WA_DeleteOnClose, false);
Connect(this, SIGNAL(do_setPDTrigLED(bool)), graphsWindow, SLOT(setPDTrig(bool)));
Connect(this, SIGNAL(do_setManualTrigEnabled(bool)), graphsWindow, SLOT(setTrigOverrideEnabled(bool)));
Connect(this, SIGNAL(do_setSGLTrig(bool)), graphsWindow, SLOT(setSGLTrig(bool)));
graphsWindow->setWindowIcon(appIcon);
hideUnhideGraphsAct->setEnabled(true);
graphsWindow->installEventFilter(this);
windowMenuAdd(graphsWindow);
// TESTING OF SPATIAL VISUALIZATION WINDOW -- REMOVE ME TO NOT USE SPATIAL VIS
unsigned spatialBoxW = MAX(graphsWindow->numColsPerGraphTab(),graphsWindow->numRowsPerGraphTab());
Vec2i spatialDims;
if (doFGAcqInstead) {
spatialDims = Vec2i(params.fg.spatialCols, params.fg.spatialRows);
} else {
int nvai = params.nVAIChans, x = 1, y = 1;
bool ff = true;
while (x*y < nvai) {
if (ff) ++x; else ++y;
ff = !ff;
}
spatialDims = Vec2i(x,y);
}
spatialWindow = new SpatialVisWindow(params, spatialDims, spatialBoxW, 0, doFGAcqInstead ? params.spatialVisUpdateRate : -1, doFGAcqInstead && params.fg.spatialVisSuppressExtraChans);
spatialWindow->setSorting(graphsWindow->currentSorting(), graphsWindow->currentNaming());
spatialWindow->setGraphTimesSecs(graphsWindow->getGraphTimesSecs());
spatialWindow->setDownsampleRatio(graphsWindow->getDownsampleRatio());
spatialWindow->setAttribute(Qt::WA_DeleteOnClose, false);
spatialWindow->setWindowIcon(appIcon);
spatialWindow->installEventFilter(this);
windowMenuAdd(spatialWindow);
Connect(graphsWindow, SIGNAL(manualTrig(bool)), this, SLOT(gotManualTrigOverride(bool)));
Connect(graphsWindow, SIGNAL(sortingChanged(const QVector<int> &, const QVector<int> &)), spatialWindow, SLOT(setSorting(const QVector<int> &, const QVector<int> &)));
Connect(graphsWindow, SIGNAL(graphTimeSecsChanged(int,double)), spatialWindow, SLOT(setGraphTimeSecs(int,double)));
Connect(graphsWindow, SIGNAL(downsampleRatioChanged(double)), spatialWindow, SLOT(setDownsampleRatio(double)));
if (!params.suppressGraphs) {
//spatialWindow->show();
graphsWindow->show();
#if QT_VERSION >= 0x050000
// Iff app built with Qt Creator, then graphs window
// will not get any mouse events until a modal dialog
// shows on top and is then destroyed!! That's what we
// do here...make an invisible message box.
{
QMessageBox XX( consoleWindow );
XX.setWindowModality( Qt::ApplicationModal );
XX.setAttribute( Qt::WA_DontShowOnScreen, true );
XX.move( QApplication::desktop()->screen()->rect().topLeft() );
XX.show();
// auto-destroyed
}
#endif
} else {
spatialWindow->hide();
graphsWindow->hide();
}
taskWaitingForStop = false;
taskHasManualTrigOverride = false;
switch (params.acqStartEndMode) {
case DAQ::Immediate: taskWaitingForTrigger = false; break;
case DAQ::Timed:
if (params.isImmediate) {
taskWaitingForTrigger = false;
startScanCt = 0;
} else {
startScanCt = i64(params.startIn * params.srate);
}
stopScanCt = params.isIndefinite ? 0x7fffffffffffffffLL : i64(startScanCt + params.duration*params.srate);
case DAQ::PDStartEnd:
case DAQ::PDStart:
case DAQ::StimGLStartEnd:
case DAQ::StimGLStart:
case DAQ::AITriggered:
case DAQ::Bug3TTLTriggered:
taskWaitingForTrigger = true; break;
default:
errTitle = "Internal Error";
errMsg = "params.acqStartEndMode is an illegal value! FIXME!";
Error() << errTitle << " " << errMsg;
return false;
}
if (params.acqStartEndMode == DAQ::Bug3TTLTriggered) {
graphsWindow->setTrigOverrideEnabled(true);
} else
graphsWindow->setTrigOverrideEnabled(false);
if (reader) delete reader, reader = 0;
reader = new PagedScanReader(params.nVAIChans, 0, samplesBuffer, shmSizeBytes, computeSamplesShmPageSize(params.srate,params.nVAIChans,params.lowLatency));
reader->bzero();
DAQ::NITask *nitask = 0;