-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
743 lines (660 loc) · 27.7 KB
/
mainwindow.cpp
File metadata and controls
743 lines (660 loc) · 27.7 KB
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
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDateTime>
#include <QDebug>
#include <QFileDialog>
#include <QMessageBox>
#include <QSettings>
#include <QStandardPaths>
#if QT_VERSION_MAJOR < 6
#include <QRegExp>
#else
#include <QRegularExpression>
using QRegExp = QRegularExpression;
#endif
#include <string>
#include <vector>
// recording class
#include "recording.h"
#include "tcpinterface.h"
const QStringList bids_modalities_default = QStringList({"eeg", "ieeg", "meg", "beh"});
MainWindow::MainWindow(QWidget *parent, const char *config_file)
: QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
connect(ui->actionLoad_Configuration, &QAction::triggered, this, [this]() {
load_config(QFileDialog::getOpenFileName(
this, "Load Configuration File", "", "Configuration Files (*.cfg)"));
});
connect(ui->actionSave_Configuration, &QAction::triggered, this, [this]() {
save_config(QFileDialog::getSaveFileName(
this, "Save Configuration File", "", "Configuration Files (*.cfg)"));
});
connect(ui->actionQuit, &QAction::triggered, this, &MainWindow::close);
// Signals for stream finding/selecting/starting/stopping
connect(ui->refreshButton, &QPushButton::clicked, this, &MainWindow::refreshStreams);
connect(ui->selectAllButton, &QPushButton::clicked, this, &MainWindow::selectAllStreams);
connect(ui->selectNoneButton, &QPushButton::clicked, this, &MainWindow::selectNoStreams);
connect(ui->startButton, &QPushButton::clicked, this, &MainWindow::startRecording);
connect(ui->stopButton, &QPushButton::clicked, this, &MainWindow::stopRecording);
connect(ui->actionAbout, &QAction::triggered, this, [this]() {
QString infostr = QStringLiteral("LSL library version: ") +
QString::number(lsl::library_version()) +
"\nLSL library info:" + lsl::library_info();
QMessageBox::about(this, "About this app", infostr);
});
// Signals for Remote Control Socket
connect(ui->rcsCheckBox, &QCheckBox::toggled, this, &MainWindow::rcsCheckBoxChanged);
connect(ui->rcsport, QOverload<int>::of(&QSpinBox::valueChanged), this, &MainWindow::rcsportValueChangedInt);
// Wheenver lineEdit_template is changed, print the final result.
connect(
ui->lineEdit_template, &QLineEdit::textChanged, this, &MainWindow::printReplacedFilename);
auto spinchanged = static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged);
connect(ui->spin_counter, spinchanged, this, &MainWindow::printReplacedFilename);
// Signals for builder-related edits -> buildFilename
connect(ui->rootBrowseButton, &QPushButton::clicked, this, [this]() {
this->ui->rootEdit->setText(QDir::toNativeSeparators(
QFileDialog::getExistingDirectory(this, "Study root folder...")));
this->buildFilename();
});
connect(ui->rootEdit, &QLineEdit::editingFinished, this, &MainWindow::buildFilename);
connect(
ui->lineEdit_participant, &QLineEdit::editingFinished, this, &MainWindow::buildFilename);
connect(ui->lineEdit_session, &QLineEdit::editingFinished, this, &MainWindow::buildFilename);
connect(ui->lineEdit_acq, &QLineEdit::editingFinished, this, &MainWindow::buildFilename);
connect(ui->input_blocktask, &QComboBox::currentTextChanged, this, &MainWindow::buildFilename);
connect(ui->input_modality, &QComboBox::currentTextChanged, this, &MainWindow::buildFilename);
connect(ui->check_bids, &QCheckBox::toggled, this, [this](bool checked) {
auto &box = *ui->lineEdit_template;
box.setReadOnly(checked);
if (checked) {
legacyTemplate = box.text();
box.setText(QDir::toNativeSeparators(
QStringLiteral("sub-%p/ses-%s/%m/sub-%p_ses-%s_task-%b[_acq-%a]_run-%r_%m.xdf")));
ui->label_counter->setText("Run (%r)");
} else {
box.setText(QDir::toNativeSeparators(legacyTemplate));
ui->label_counter->setText("Exp num (%n)");
}
});
timer = std::make_unique<QTimer>(this);
connect(&*timer, &QTimer::timeout, this, &MainWindow::statusUpdate);
timer->start(1000);
QString cfgfilepath = find_config_file(config_file);
load_config(cfgfilepath);
}
void MainWindow::statusUpdate() const {
if (currentRecording) {
auto elapsed = static_cast<int>(lsl::local_clock() - startTime);
QString recFilename = replaceFilename(QDir::cleanPath(ui->lineEdit_template->text()));
auto fileinfo = QFileInfo(QDir::cleanPath(ui->rootEdit->text()) + '/' + recFilename);
fileinfo.refresh();
auto size = fileinfo.size();
QString timeString = QStringLiteral("Recording to %1 (%2; %3kb)")
.arg(QDir::toNativeSeparators(recFilename),
QTime(0,0).addSecs(elapsed).toString("hh:mm:ss"),
QString::number(size / 1000));
statusBar()->showMessage(timeString);
}
}
void MainWindow::closeEvent(QCloseEvent *ev) {
if (currentRecording) ev->ignore();
}
void MainWindow::blockSelected(const QString &block) {
if (currentRecording)
QMessageBox::information(this, "Still recording",
"Please stop recording before switching blocks.", QMessageBox::Ok);
else {
printReplacedFilename();
// scripted action code here...
}
}
void MainWindow::load_config(QString filename) {
qInfo() << "loading config file " << QDir::toNativeSeparators(filename);
bool auto_start = false;
try {
QSettings pt(QDir::cleanPath(filename), QSettings::Format::IniFormat);
// ----------------------------
// required streams
// ----------------------------
auto required = pt.value("RequiredStreams").toStringList();
#if QT_VERSION >= QT_VERSION_CHECK(5,14,0)
missingStreams = QSet<QString>(required.begin(), required.end());
#else
missingStreams = required.toSet();
#endif
// ----------------------------
// online sync streams
// ----------------------------
QStringList onlineSyncStreams = pt.value("OnlineSync", QStringList()).toStringList();
for (QString &oss : onlineSyncStreams) {
#if QT_VERSION >= QT_VERSION_CHECK(5,14,0)
auto skipEmpty = Qt::SkipEmptyParts;
#else
auto skipEmpty = QString::SkipEmptyParts;
#endif
QStringList words = oss.split(' ', skipEmpty);
// The first two words ("StreamName (PC)") are the stream identifier
if (words.length() < 2) {
qInfo() << "Invalid sync stream config: " << oss;
continue;
}
QString key = words.takeFirst() + ' ' + words.takeFirst();
int val = 0;
for (const auto &word : qAsConst(words)) {
if (word == "post_clocksync") { val |= lsl::post_clocksync; }
if (word == "post_dejitter") { val |= lsl::post_dejitter; }
if (word == "post_monotonize") { val |= lsl::post_monotonize; }
if (word == "post_threadsafe") { val |= lsl::post_threadsafe; }
if (word == "post_ALL") { val = lsl::post_ALL; }
}
syncOptionsByStreamName[key.toStdString()] = val;
qInfo() << "stream sync options: " << key << ": " << val;
}
// ----------------------------
// Block/Task Names
// ----------------------------
QStringList taskNames;
if (pt.contains("SessionBlocks")) { taskNames = pt.value("SessionBlocks").toStringList(); }
ui->input_blocktask->clear();
ui->input_blocktask->insertItems(0, taskNames);
// StorageLocation
QString studyRoot;
legacyTemplate.clear();
if (pt.contains("StorageLocation")) {
if (pt.contains("StudyRoot"))
throw std::runtime_error("StorageLocation cannot be used if StudyRoot is also specified.");
if (pt.contains("PathTemplate"))
throw std::runtime_error("StorageLocation cannot be used if PathTemplate is also specified.");
QString str_path = pt.value("StorageLocation").toString();
QString path_root;
auto index = str_path.indexOf('%');
if (index != -1) {
// When a % is encountered, the studyroot gets set to the
// longest path before the placeholder, e.g.
// foo/bar/baz%a/untitled.xdf gets split into
// foo/bar and baz%a/untitled.xdf
path_root = str_path.left(index);
} else {
// Otherwise, it's split into folder and constant filename
path_root = str_path;
}
studyRoot = QFileInfo(path_root).absolutePath();
legacyTemplate = str_path.remove(0, studyRoot.length() + 1);
// absolute path, nothing to be done
// studyRoot = QFileInfo(path_root).absolutePath();
}
// StudyRoot
if (pt.contains("StudyRoot")) { studyRoot = pt.value("StudyRoot").toString(); }
if (pt.contains("PathTemplate")) { legacyTemplate = pt.value("PathTemplate").toString(); }
if (studyRoot.isEmpty())
studyRoot = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) +
QDir::separator() + "CurrentStudy";
ui->rootEdit->setText(QDir::toNativeSeparators(studyRoot));
if (legacyTemplate.isEmpty()) {
ui->check_bids->setChecked(true);
// Use default, exp%n/%b.xdf , only to be used if BIDS gets unchecked.
legacyTemplate = "exp%n/block_%b.xdf";
} else {
ui->check_bids->setChecked(false);
ui->lineEdit_template->setText(QDir::toNativeSeparators(legacyTemplate));
}
// Append BIDS modalities to the default list.
ui->input_modality->insertItems(
ui->input_modality->count(), pt.value("BidsModalities", bids_modalities_default).toStringList());
ui->input_modality->setCurrentIndex(0);
buildFilename();
// Remote Control Socket options
if (pt.contains("RCSPort")) {
int rcs_port = pt.value("RCSPort").toInt();
ui->rcsport->setValue(rcs_port);
// In case it's already running (how?), stop the RCS listener.
ui->rcsCheckBox->setChecked(false);
}
if (pt.contains("RCSEnabled")) {
bool b_enable_rcs = pt.value("RCSEnabled").toBool();
ui->rcsCheckBox->setChecked(b_enable_rcs);
}
// Check the wild-card-replaced filename to see if it exists already.
// If it does then increment the exp number.
// We only do this on settings-load because manual spin changes might indicate purposeful
// overwriting.
QString recFilename = QDir::cleanPath(ui->lineEdit_template->text());
// Spin Number
if (recFilename.contains(counterPlaceholder())) {
for (int i = 1; i < 1001; i++) {
ui->spin_counter->setValue(i);
if (!QFileInfo::exists(replaceFilename(recFilename))) break;
}
}
if (pt.contains("AutoStart")) {
auto_start = pt.value("AutoStart").toBool();
}
} catch (std::exception &e) { qWarning() << "Problem parsing config file: " << e.what(); }
// std::cout << "refreshing streams ..." <<std::endl;
refreshStreams();
if (auto_start) { startRecording(); }
}
void MainWindow::save_config(QString filename) {
QSettings settings(filename, QSettings::Format::IniFormat);
settings.setValue("StudyRoot", QDir::cleanPath(ui->rootEdit->text()));
if (!ui->check_bids->isChecked())
settings.setValue("PathTemplate", QDir::cleanPath(ui->lineEdit_template->text()));
// Build QStringList from missingStreams and knownStreams that are missing.
QStringList requiredStreams = missingStreams.values();
for (auto &k : knownStreams) {
if (k.checked) { requiredStreams.append(k.listName()); }
}
qInfo() << missingStreams;
settings.setValue("RequiredStreams", requiredStreams);
// Stub.
}
QString info_to_listName(const lsl::stream_info& info) {
return QString::fromStdString(info.name() + " (" + info.hostname() + ")");
}
/**
* @brief MainWindow::refreshStreams Find streams, generate a list of missing streams
* and fill the UI streamlist.
* @return A vector of found stream_infos
*/
std::vector<lsl::stream_info> MainWindow::refreshStreams() {
const std::vector<lsl::stream_info> resolvedStreams = lsl::resolve_streams(1.0);
// For each item in resolvedStreams, ignore if already in knownStreams, otherwise add to knownStreams.
// if in missingStreams then also mark it as required (--> checked by default) and remove from missingStreams.
for (const auto& s : resolvedStreams) {
bool known = false;
for (auto &k : knownStreams) {
known |= s.name() == k.name && s.type() == k.type && s.source_id() == k.id;
}
if (!known) {
bool found = missingStreams.contains(info_to_listName(s));
knownStreams << StreamItem(s.name(), s.type(), s.source_id(), s.hostname(), found);
if (found) { missingStreams.remove(info_to_listName(s)); }
}
}
// For each item in knownStreams, update its checked status from GUI. (only works for streams found on a previous refresh)
// Because we search by name + host, entries aren't guaranteed to be unique, so checking one entry with matching name and host checks them all.
for (auto &k : knownStreams) {
QList<QListWidgetItem *> foundItems = ui->streamList->findItems(k.listName(), Qt::MatchCaseSensitive);
if (foundItems.count() > 0) {
bool checked = false;
for (auto &fi : foundItems) { checked |= fi->checkState() == Qt::Checked; }
k.checked = checked;
}
}
// For each item in knownStreams; if it is not resolved then drop it. If it was checked then add back to missingStreams.
int k_ind = 0;
while (k_ind < knownStreams.count()) {
StreamItem k = knownStreams.at(k_ind);
bool resolved = false;
size_t r_ind = 0;
while (!resolved && r_ind < resolvedStreams.size()) {
const lsl::stream_info r = resolvedStreams[r_ind];
resolved |= (r.name() == k.name) && (r.type() == k.type) && (r.source_id() == k.id);
r_ind++;
}
if (!resolved) {
if (k.checked) { missingStreams += k.listName(); }
knownStreams.removeAt(k_ind);
} else {
k_ind++;
}
}
// Clear the streamList
// Add missing items first.
// Then add knownStreams (only in list if resolved).
const QBrush good_brush(QColor(0, 128, 0)), bad_brush(QColor(255, 0, 0));
ui->streamList->clear();
for (auto& m : qAsConst(missingStreams)) {
auto *item = new QListWidgetItem(m, ui->streamList);
item->setCheckState(Qt::Checked);
item->setForeground(bad_brush);
ui->streamList->addItem(item);
}
for (auto& k : knownStreams) {
auto *item = new QListWidgetItem(k.listName(), ui->streamList);
item->setCheckState(k.checked ? Qt::Checked : Qt::Unchecked);
item->setForeground(good_brush);
ui->streamList->addItem(item);
}
// return a std::vector of streams of checked and not missing streams.
std::vector<lsl::stream_info> requestedAndAvailableStreams;
for (const auto &r : resolvedStreams) {
for (auto &k : knownStreams) {
if ((r.name() == k.name) && (r.type() == k.type) && (r.source_id() == k.id)) {
if (k.checked) { requestedAndAvailableStreams.push_back(r); }
break;
}
}
}
return requestedAndAvailableStreams;
}
void MainWindow::startRecording() {
if (!currentRecording) {
// automatically refresh streams
const std::vector<lsl::stream_info> requestedAndAvailableStreams = refreshStreams();
if (!hideWarnings) {
// if a checked stream is now missing
if (!missingStreams.isEmpty()) {
// are you sure?
QMessageBox msgBox(QMessageBox::Warning, "Stream not found",
"At least one of the streams that you checked seems to be offline",
QMessageBox::Yes | QMessageBox::No, this);
msgBox.setInformativeText("Do you want to start recording anyway?");
msgBox.setDefaultButton(QMessageBox::No);
if (msgBox.exec() != QMessageBox::Yes) return;
}
if (requestedAndAvailableStreams.size() == 0) {
QMessageBox msgBox(QMessageBox::Warning, "No available streams selected",
"You have selected no streams", QMessageBox::Yes | QMessageBox::No, this);
msgBox.setInformativeText("Do you want to start recording anyway?");
msgBox.setDefaultButton(QMessageBox::No);
if (msgBox.exec() != QMessageBox::Yes) return;
}
}
// don't hide critical errors.
QString recFilename = replaceFilename(QDir::cleanPath(ui->lineEdit_template->text()));
if (recFilename.isEmpty()) {
QMessageBox::critical(this, "Filename empty", "Can not record without a file name");
return;
}
recFilename.prepend(QDir::cleanPath(ui->rootEdit->text()) + '/');
QFileInfo recFileInfo(recFilename);
if (recFileInfo.exists()) {
if (recFileInfo.isDir()) {
QMessageBox::warning(
this, "Error", "Recording path already exists and is a directory");
return;
}
QString rename_to = recFileInfo.absolutePath() + '/' + recFileInfo.baseName() +
"_old%1." + recFileInfo.suffix();
// search for highest _oldN
int i = 1;
while (QFileInfo::exists(rename_to.arg(i))) i++;
QString newname = rename_to.arg(i);
if (!QFile::rename(recFileInfo.absoluteFilePath(), newname)) {
QMessageBox::warning(this, "Permissions issue",
"Cannot rename the file " + recFilename + " to " + newname);
return;
}
qInfo() << "Moved existing file to " << newname;
recFileInfo.refresh();
}
// regardless, we need to create the directory if it doesn't exist
if (!recFileInfo.dir().mkpath(".")) {
QMessageBox::warning(this, "Permissions issue",
"Can not create the directory " + recFileInfo.dir().path() +
". Please check your permissions.");
return;
}
std::vector<std::string> watchfor;
for (const QString &missing : qAsConst(missingStreams)) {
std::string query;
// Convert missing to query expected by lsl::resolve_stream
// name='BioSemi' and hostname=AASDFSDF
QRegularExpression re("(.+)\\s+\\((\\S+)\\)");
QRegularExpressionMatch match = re.match(missing);
if (match.hasMatch())
{
QString name = match.captured(1);
QString host = match.captured(2);
query = "name='" + match.captured(1).toStdString() + "'";
if (host.size() > 1) {
query += " and hostname='" + host.toStdString() + "'";
}
} else {
// Regexp failed but we can try using the entire string as the stream name.
query = "name='" + missing.toStdString() + "'";
}
watchfor.push_back(query);
}
qInfo() << "Missing: " << missingStreams;
currentRecording = std::make_unique<recording>(recFilename.toStdString(),
requestedAndAvailableStreams, watchfor, syncOptionsByStreamName, true);
ui->stopButton->setEnabled(true);
ui->startButton->setEnabled(false);
startTime = (int)lsl::local_clock();
} else if (!hideWarnings) {
QMessageBox::information(
this, "Already recording", "The recording is already running", QMessageBox::Ok);
}
}
void MainWindow::stopRecording() {
if (currentRecording) {
try {
currentRecording = nullptr;
} catch (std::exception &e) { qWarning() << "exception on stop: " << e.what(); }
ui->startButton->setEnabled(true);
ui->stopButton->setEnabled(false);
statusBar()->showMessage("Stopped");
} else if (!hideWarnings) {
QMessageBox::information(
this, "Not recording", "There is not ongoing recording", QMessageBox::Ok);
}
}
void MainWindow::selectAllStreams() {
for (int i = 0; i < ui->streamList->count(); i++) {
QListWidgetItem *item = ui->streamList->item(i);
item->setCheckState(Qt::Checked);
}
}
void MainWindow::selectRegexStreams(const QString& regex_pattern) {
// make filter from regex pattern
QRegExp regex_filter(regex_pattern);
// iterate over the UI checkboxes
for (int i = 0; i < ui->streamList->count(); i++) {
QListWidgetItem* item = ui->streamList->item(i);
QString streamName = item->text();
// Select entries that match
if (regex_filter.exactMatch(streamName))
item->setCheckState(Qt::Checked);
}
}
void MainWindow::selectStreams(const QString& search_str) {
// Convert the search string to lowercase for case-insensitive matching
QString lowerSearchStr = search_str.toLower();
// Iterate over the UI checkboxes
for (int i = 0; i < ui->streamList->count(); i++) {
QListWidgetItem* item = ui->streamList->item(i);
QString streamName = item->text().toLower(); // Convert the stream name to lowercase
// Select entries that match (case-insensitive)
if (streamName.contains(lowerSearchStr)) {
item->setCheckState(Qt::Checked);
}
}
}
void MainWindow::selectNoStreams() {
for (int i = 0; i < ui->streamList->count(); i++) {
QListWidgetItem *item = ui->streamList->item(i);
item->setCheckState(Qt::Unchecked);
}
}
void MainWindow::buildBidsTemplate() {
// path/to/CurrentStudy/sub-%p/ses-%s/eeg/sub-%p_ses-%s_task-%b[_acq-%a]_run-%r_eeg.xdf
// Make sure the BIDS required fields are full.
if (ui->lineEdit_participant->text().isEmpty()) { ui->lineEdit_participant->setText("P001"); }
if (ui->lineEdit_session->text().isEmpty()) { ui->lineEdit_session->setText("S001"); }
if (ui->input_blocktask->currentText().isEmpty()) {
ui->input_blocktask->setCurrentText("Default");
}
// BIDS modality selection
if (ui->input_modality->currentText().isEmpty()) {
ui->input_modality->insertItems(0, bids_modalities_default);
ui->input_modality->setCurrentIndex(0);
}
// Folder hierarchy
QStringList fileparts{"sub-%p", "ses-%s", "%m"};
// filename
QString fname = "sub-%p_ses-%s_task-%b";
if (!ui->lineEdit_acq->text().isEmpty()) { fname.append("_acq-%a"); }
fname.append("_run-%r_%m.xdf");
fileparts << fname;
ui->lineEdit_template->setText(QDir::toNativeSeparators(fileparts.join('/')));
}
void MainWindow::buildFilename() {
// This function is only called when a widget within Location Builder is activated.
// Build the file location in parts, starting with the root folder.
if (ui->check_bids->isChecked()) { buildBidsTemplate(); }
QString tpl = QDir::cleanPath(ui->lineEdit_template->text());
// Auto-increment Spin/Run Number if necessary.
if (tpl.contains(counterPlaceholder())) {
for (int i = 1; i < 1001; i++) {
ui->spin_counter->setValue(i);
if (!QFileInfo::exists(replaceFilename(tpl))) break;
}
}
// Sometimes lineEdit_template doesn't change so printReplacedFilename isn't triggered.
// So trigger manually.
printReplacedFilename();
}
QString MainWindow::replaceFilename(QString fullfile) const {
// Replace wildcards.
// There are two different wildcard formats: legacy, BIDS
// Legacy takes the form path/to/study/exp%n/%b.xdf
// Where %n will be replaced by the contents of the spin_counter widget
// and %b will be replaced by the contents of the blockList widget.
fullfile.replace("%b", ui->input_blocktask->currentText());
// BIDS
// See https://docs.google.com/document/d/1ArMZ9Y_quTKXC-jNXZksnedK2VHHoKP3HCeO5HPcgLE/
// path/to/study/sub-<participant_label>/ses-<session_label>/eeg/sub-<participant_label>_ses-<session_label>_task-<task_label>[_acq-<acq_label>]_run-<run_index>_eeg.xdf
// path/to/study/sub-%p/ses-%s/eeg/sub-%p_ses-%s_task-%b[_acq-%a]_run-%r_eeg.xdf
// %b already replaced above.
fullfile.replace("%p", ui->lineEdit_participant->text());
fullfile.replace("%s", ui->lineEdit_session->text());
fullfile.replace("%a", ui->lineEdit_acq->text());
fullfile.replace("%m", ui->input_modality->currentText());
// Replace either %r or %n with the counter
QString run = QString("%1").arg(ui->spin_counter->value(), 3, 10, QChar('0'));
fullfile.replace(counterPlaceholder(), run);
return fullfile.trimmed();
}
/**
* Find a config file to load. This is (in descending order or preference):
* - a file supplied on the command line
* - [executablename].cfg in one the the following folders:
* - the current working directory
* - the default config folder, e.g. '~/Library/Preferences' on OS X
* - the executable folder
* @param filename Optional file name supplied e.g. as command line parameter
* @return Path to a found config file
*/
QString MainWindow::find_config_file(const char *filename) {
if (filename) {
QString qfilename(filename);
if (!QFileInfo::exists(qfilename))
QMessageBox(QMessageBox::Warning, "Config file not found",
QStringLiteral("The file '%1' doesn't exist").arg(qfilename), QMessageBox::Ok,
this);
else
return qfilename;
}
QFileInfo exeInfo(QCoreApplication::applicationFilePath());
QString defaultCfgFilename(exeInfo.completeBaseName() + ".cfg");
qInfo() << defaultCfgFilename;
QStringList cfgpaths;
cfgpaths << QDir::currentPath()
<< QStandardPaths::standardLocations(QStandardPaths::AppConfigLocation)
<< QStandardPaths::standardLocations(QStandardPaths::AppDataLocation)
<< exeInfo.path();
for (const auto &path : qAsConst(cfgpaths)) {
QString cfgfilepath = path + QDir::separator() + defaultCfgFilename;
qInfo() << cfgfilepath;
if (QFileInfo::exists(cfgfilepath)) return cfgfilepath;
}
QMessageBox::warning(this, "No config file not found",
QStringLiteral("No default config file could be found"), "Continue with default config");
return "";
}
QString MainWindow::counterPlaceholder() const { return ui->check_bids->isChecked() ? "%r" : "%n"; }
void MainWindow::printReplacedFilename() {
ui->locationLabel->setText(
ui->rootEdit->text() + '\n' + replaceFilename(ui->lineEdit_template->text()));
}
MainWindow::~MainWindow() noexcept = default;
void MainWindow::rcsCheckBoxChanged(bool checked) { enableRcs(checked); }
void MainWindow::enableRcs(bool bEnable) {
if (rcs) {
if (!bEnable) {
disconnect(rcs.get());
rcs = nullptr;
}
} else if (bEnable) {
uint16_t port = ui->rcsport->value();
rcs = std::make_unique<RemoteControlSocket>(port);
// TODO: Add some method to RemoteControlSocket to report if its server is listening (i.e. was successful).
connect(rcs.get(), &RemoteControlSocket::refresh_streams, this, &MainWindow::refreshStreams);
connect(rcs.get(), &RemoteControlSocket::start, this, &MainWindow::rcsStartRecording);
connect(rcs.get(), &RemoteControlSocket::stop, this, &MainWindow::rcsStopRecording);
connect(rcs.get(), &RemoteControlSocket::filename, this, &MainWindow::rcsUpdateFilename);
connect(rcs.get(), &RemoteControlSocket::select_all, this, &MainWindow::selectAllStreams);
connect(rcs.get(), &RemoteControlSocket::select_none, this, &MainWindow::selectNoStreams);
connect(rcs.get(), &RemoteControlSocket::select_stream, this, &MainWindow::selectStreams);
connect(rcs.get(), &RemoteControlSocket::select_stream_regex, this, &MainWindow::selectRegexStreams);
}
bool oldState = ui->rcsCheckBox->blockSignals(true);
ui->rcsCheckBox->setChecked(bEnable);
ui->rcsCheckBox->blockSignals(oldState);
}
void MainWindow::rcsportValueChangedInt(int value) {
if (rcs) {
enableRcs(false); // Will also uncheck box.
enableRcs(true); // Will also check box.
}
}
void MainWindow::rcsStartRecording() {
// since we want to avoid a pop-up window when streams are missing or unchecked,
// we'll check all the streams and start recording
hideWarnings = true;
// Due to the select all function, I assumed it made no sense to force recording all
//selectAllStreams();
startRecording();
}
void MainWindow::rcsStopRecording() {
hideWarnings = true;
stopRecording();
}
void MainWindow::rcsUpdateFilename(QString s) {
//
// format: "filename {option:value}{option:value}
// Options are:
// root: full path to Study root;
// template: legacy filename template, left to default (bids) if unspecified;
// task; run; participant; session; acquisition: base options
// (BIDS) modality: from either the defaults eeg, ieeg, meg, beh or adding a new
// potentially unsupported value.
QRegularExpression re("{(?P<option>\\w+?):(?P<value>[^}]*)}");
QRegularExpressionMatchIterator i = re.globalMatch(s);
while (i.hasNext()) {
QRegularExpressionMatch match = i.next();
QString option = match.captured("option");
QString value = match.captured("value");
// TODO: replace with QStringList and switch
if (option.toLower() == "root") {
ui->rootEdit->setText(QDir::toNativeSeparators(value));
} else if (option.toLower() == "template") {
// legacy
ui->check_bids->setChecked(false);
ui->lineEdit_template->setText(value.toLower());
} else if (option.toLower() == "task") {
ui->input_blocktask->clear();
ui->input_blocktask->addItem(value);
ui->input_blocktask->setCurrentIndex(0);
} else if (option.toLower() == "run") {
ui->spin_counter->setValue(value.toInt());
} else if (option.toLower() == "participant") {
ui->lineEdit_participant->setText(value);
} else if (option.toLower() == "session") {
ui->lineEdit_session->setText(value);
} else if (option.toLower() == "acquisition") {
ui->lineEdit_acq->setText(value);
} else if (option.toLower() == "modality") {
if (ui->input_modality->findText(value.toLower()) != -1)
ui->input_modality->setCurrentIndex(ui->input_modality->findText(value.toLower()));
else {
ui->input_modality->insertItem(ui->input_modality->count(), value.toLower());
ui->input_modality->setCurrentIndex(ui->input_modality->count() - 1);
}
}
}
// to make sure all the values are updated.
printReplacedFilename();
}