-
-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
2144 lines (1992 loc) · 84.2 KB
/
Copy pathmainwindow.cpp
File metadata and controls
2144 lines (1992 loc) · 84.2 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
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 <QFileDialog>
#include <QDir>
#include <QUrl>
#include <QMessageBox>
#include <QDragEnterEvent>
#include <QMimeData>
#include <QAction>
#include <QTextStream>
#include <QHeaderView>
#include <QStyleFactory>
#include <QNetworkInterface>
#include <QNetworkRequest>
#include <QSysInfo>
#include <QStandardPaths>
#include <QDialog>
#include <QLineEdit>
#include <QUuid>
#include <QProcess>
#include <QProcessEnvironment>
#include <QPointer>
#include <QJsonDocument>
#include <QMap>
#include <QJsonObject>
#include <QJsonArray>
#include <QRegularExpression>
#include <algorithm>
#include <filesystem>
#include <mutex>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "ai_agent.hpp"
#include "cmd/ai.hpp"
#include "regtoolbox.h"
#include "reconstruction/reconstruction_window.h"
#include "tracking/tracking_window.h"
#include "opengl/glwidget.h"
#include "dicom/dicom_parser.h"
#include "view_image.h"
#include "mapping/atlas.hpp"
#include "fib_data.hpp"
#include "connectometry/group_connectometry_analysis.h"
#include "connectometry/createdbdialog.h"
#include "connectometry/db_window.h"
#include "connectometry/group_connectometry.hpp"
#include "libs/dsi/image_model.hpp"
#include "manual_alignment.h"
#include "auto_track.h"
#include "xnat_dialog.h"
#include "console.h"
#include "fiber_data_hub.hpp"
QString access_token;
extern MainWindow* main_window;
void checkForVersionSpecificBugs(const QString& bugListText)
{
QDate compDate = QDate::fromString(__DATE__, "MMM dd yyyy");
if (!compDate.isValid())
return;
auto match_date = [&](auto op,auto date) -> bool
{
QDate rangeDate = QDate::fromString(date, "M/d/yyyy");
if (!rangeDate.isValid())
rangeDate = QDate::fromString(date, "MM/dd/yyyy");
if (!rangeDate.isValid())
return false;
if (op == ">=") return (compDate >= rangeDate);
else if (op == "<=") return (compDate <= rangeDate);
else if (op == ">") return (compDate > rangeDate);
else if (op == "<") return (compDate < rangeDate);
return false;
};
QStringList matchingBugs;
for (auto line : bugListText.split('\n', Qt::SkipEmptyParts))
{
if (!line.contains("versions"))
continue;
if (line.contains("windows") && !QSysInfo::productType().contains("windows"))
continue;
if (line.contains("macos") && !QSysInfo::productType().contains("macos"))
continue;
if (line.contains("ubuntu") && !QSysInfo::productType().contains("ubuntu"))
continue;
int start = line.indexOf('['), end = line.indexOf(']');
if (start == -1 || end == -1 || end <= start)
continue;
QString spec = line.mid(start + 1, end - start - 1).trimmed();
QString desc = line.mid(end + 1).trimmed();
if (!spec.startsWith("versions ") || desc.isEmpty())
continue;
QStringList conds = spec.trimmed().split(' ', Qt::SkipEmptyParts);
bool match = true;
for(size_t i = 2;i < conds.size(); i += 2)
if(!match_date(conds[i-1].trimmed(),conds[i].trimmed()))
{
match = false;
break;
}
if (match)
matchingBugs.append(desc);
}
if (!matchingBugs.isEmpty())
QMessageBox::critical(nullptr, "Program Update Recommended",
"This DSI Studio version is affected by the following issues:\n\n- " +
matchingBugs.join("\n- ") +
"\n\nIt is highly recommended to update DSI Studio to the latest version to avoid these issues.");
}
extern std::vector<std::filesystem::path> fib_template_list;
std::vector<tracking_window*> tracking_windows;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
setAcceptDrops(true);
ui->setupUi(this);
ui->styles->addItems(QStringList("default") << QStyleFactory::keys());
ui->styles->setCurrentText(settings.value("styles","Fusion").toString());
for(auto* table : {ui->recentSrc,ui->recentFib})
{
table->setColumnCount(2);
table->horizontalHeader()->setSectionResizeMode(0,QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(1,QHeaderView::Stretch);
table->setAlternatingRowColors(true);
}
QObject::connect(ui->recentFib,SIGNAL(cellDoubleClicked(int,int)),this,SLOT(open_fib_at(int,int)));
QObject::connect(ui->recentSrc,SIGNAL(cellDoubleClicked(int,int)),this,SLOT(open_src_at(int,int)));
updateRecentList();
auto workdir_list = settings.value("WORK_PATH").toStringList();
if (!settings.contains("WORK_PATH"))
ui->workDir->addItem(QDir::currentPath());
tipl::qt::working_dirs << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::DesktopLocation));
tipl::qt::working_dirs << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation));
tipl::qt::working_dirs << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::DownloadLocation));
for(const auto& each : workdir_list)
if(QFileInfo::exists(each))
{
ui->workDir->addItem(each);
tipl::qt::working_dirs << QUrl::fromLocalFile(each);
}
if(!ui->workDir->count())
ui->workDir->addItem(QDir::currentPath());
for(auto& each : fib_template_list)
{
QString name = std::filesystem::path(each).stem().string().c_str();
ui->template_list->addItem(name);
}
ui->tabWidget->setCurrentIndex(0);
ui->template_list->setCurrentRow(0);
{
news = settings.value("login_news").toString();
address = settings.value("login_address",QLocale::countryToString(QLocale::system().country())).toString();
host_name = settings.value("login_hostname",QHostInfo::localHostName().isEmpty() ? QSysInfo::machineHostName() : QHostInfo::localHostName()).toString();
username = settings.value("login_id",
QDir(QStandardPaths::writableLocation(QStandardPaths::HomeLocation)).dirName() + "," +
QUuid::createUuid().toString(QUuid::WithoutBraces) + "," +
QLocale::countryToString(QLocale::system().country())).toString();
if(!settings.contains("login_id"))
settings.setValue("login_id",username);
{
QString licenseText;
{
QFile licenseFile(QApplication::applicationDirPath() + "/LICENSE");
if(!licenseFile.open(QIODevice::ReadOnly))
throw std::runtime_error("cannot locate license file");
licenseText = licenseFile.readAll();
}
QDialog *dialog = new QDialog(this);
dialog->setWindowTitle("DSI Studio");
dialog->setWindowFlags(Qt::Dialog | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
dialog->setModal(true);
QHBoxLayout *main_layout = new QHBoxLayout;
dialog->setLayout(main_layout);
QVBoxLayout *left_layout = new QVBoxLayout;
QVBoxLayout *right_layout = new QVBoxLayout;
{
auto title = new QLabel("License Information:");
title->setStyleSheet("font-weight: bold;");
right_layout->addWidget(title);
}
{
QTextBrowser *licenseBrowser = new QTextBrowser;
licenseBrowser->setMarkdown(licenseText);
licenseBrowser->setReadOnly(true);
licenseBrowser->setOpenExternalLinks(true);
right_layout->addWidget(licenseBrowser);
}
{
QHBoxLayout *h_layout = new QHBoxLayout;
h_layout->addWidget(new QLabel("Registering Entity:"));
auto line_edit = new QLineEdit(username);
line_edit->setReadOnly(true);
h_layout->addWidget(line_edit);
right_layout->addLayout(h_layout);
}
{
auto registry_info = new QLabel("Registering Information: " + host_name + "," + address);
registry_info->setWordWrap(true);
right_layout->addWidget(registry_info);
}
{
auto note = new QLabel("By clicking 'Accept & Sign in', you agree to the licensing terms and sign in using the registration registry and information.");
note->setWordWrap(true);
note->setStyleSheet("font-weight: bold;");
right_layout->addWidget(note);
}
{
QPushButton *closeButton = new QPushButton("Accept && Sign in");
closeButton->setStyleSheet("font-size: 14pt; font-weight: bold;");
auto h = closeButton->sizeHint().height() * 1.5f;
closeButton->setFixedHeight(h);
connect(closeButton, &QPushButton::clicked, dialog, &QDialog::close);
connect(closeButton, &QPushButton::clicked, this, &MainWindow::login);
QPushButton *exitButton = new QPushButton("Decline && Exit");
exitButton->setFixedHeight(h);
exitButton->setMaximumWidth(100);
connect(exitButton, &QPushButton::clicked, dialog, &QDialog::close);
connect(exitButton, &QPushButton::clicked, this, &MainWindow::close);
QHBoxLayout *h_layout = new QHBoxLayout;
h_layout->setSpacing(0);
h_layout->addWidget(closeButton);
h_layout->addWidget(exitButton);
right_layout->addLayout(h_layout);
}
{
auto title = new QLabel("News and Updates:");
title->setStyleSheet("font-weight: bold;");
left_layout->addWidget(title);
}
{
QTextBrowser *NewsBrowser = new QTextBrowser;
NewsBrowser->setMarkdown(news);
NewsBrowser->setReadOnly(true);
NewsBrowser->setOpenExternalLinks(true);
left_layout->addWidget(NewsBrowser);
checkForVersionSpecificBugs(news);
}
main_layout->addLayout(left_layout, 1);
main_layout->addLayout(right_layout, 1);
dialog->resize(1024,800);
dialog->show();
}
}
// Connect command buttons
{
for(auto* button : findChildren<QPushButton*>())
{
QString tip = button->statusTip();
if(!tip.startsWith("run "))
continue;
std::string command_name = tip.mid(4).trimmed().toStdString();
connect(button,&QPushButton::clicked,this,[this,command_name]
{
if(!command({command_name}) && !error_msg.empty())
QMessageBox::critical(this,"ERROR",QString::fromStdString(error_msg));
});
}
}
ai_agent = new AIAgent(this);
}
extern const char* version_string;
void MainWindow::login(void)
{
setWindowTitle(windowTitle() + "(Offline)");
QDnsLookup *dns = new QDnsLookup(this);
dns->setType(QDnsLookup::TXT);
dns->setName(DSI_STUDIO_LOGIN);
connect(dns, &QDnsLookup::finished, [=]()
{
if (dns->error() != QDnsLookup::NoError)
{
qWarning() << "cannot login due to DNS lookup error:" << dns->errorString();
dns->deleteLater();
return;
}
for (const auto &record : dns->textRecords())
{
info = QString(record.values().join("")).split(',');
break;
}
// update news
if(info.size() >= 1)
{
auto reply = get(info[0]);
connect(reply.get(), &QNetworkReply::finished, this, [=]()
{
if (reply->error() == QNetworkReply::NoError)
{
settings.setValue("login_news",QString(reply->readAll()));
settings.sync();
}
});
}
// update registering information
if(info.size() >= 3)
{
auto reply = get(info[1]);
connect(reply.get(), &QNetworkReply::finished, this, [=]()
{
if (reply->error() == QNetworkReply::NoError)
{
auto reply2 = get(info[2].arg(QJsonDocument::fromJson(QString(reply->readAll()).toUtf8()).object().value("ip").toString()));
connect(reply2.get(), &QNetworkReply::finished, this, [=]()
{
if (reply2->error() == QNetworkReply::NoError)
{
QJsonObject jsonObject = QJsonDocument::fromJson(QString(reply2->readAll()).toUtf8()).object();
if(!jsonObject.value("city").toString().isEmpty())
{
settings.setValue("login_address",jsonObject.value("city").toString() + "," +
jsonObject.value("region").toString() + "," +
jsonObject.value("countryCode").toString() + " " +
jsonObject.value("zip").toString() + " ");
settings.setValue("login_hostname",jsonObject.value("as").toString());
settings.sync();
}
}
});
}
});
}
if(info.size() >= 5)
{
QNetworkRequest request(QUrl(info[3].toStdString().c_str()));
request.setRawHeader("Content-Type", "application/json");
QJsonObject data;
data["name"] = username;
data["fn"] = host_name;
data["os"] = QSysInfo::productType() + QSysInfo::productVersion();
data["version"] = QString(version_string) + " " + __DATE__;
data["address"] = address;
auto reply = manager.post(request, QJsonDocument(data).toJson());
QObject::connect(reply, &QNetworkReply::finished, [=]()
{
if (reply->error() == QNetworkReply::NoError)
{
QString result = reply->readAll();
if(result.startsWith('{')) // json format
{
auto data = QJsonDocument::fromJson(result.toUtf8()).object();
if (data.contains("title"))
setWindowTitle(windowTitle().remove("(Offline)") + " " + data["title"].toString());
if (data.contains("token"))
access_token = data["token"].toString();
if (data.contains("notice"))
QMessageBox::critical(this,"Notice",data["notice"].toString());
}
else
setWindowTitle(windowTitle().remove("(Offline)") + " " + result);
}
reply->deleteLater();
});
}
dns->deleteLater();
});
dns->lookup();
}
void MainWindow::openFile(QStringList file_names)
{
if(file_names.isEmpty() || file_names[0].isEmpty())
return;
QString file_name = file_names[0];
auto name = file_name.toLower();
if(!QFileInfo::exists(file_name))
{
if(file_name[0] == '-') // Mac pass a variable
return;
QMessageBox::critical(this,"ERROR",QString("Cannot find ") +
file_name + " at current dir: " + QDir::current().dirName());
}
else
{
if(name.endsWith(".csv"))
{
auto lines = tipl::read_text_file(tipl::qt::to_path(file_name));
if(lines.empty() || !tipl::begins_with(lines[0],"open_fib,"))
{
QMessageBox::critical(this,"ERROR","invalid command csv file");
return;
}
if(!loadFib(QString::fromStdString(tipl::split(lines[0],',')[1])))
return;
if(!tracking_windows.empty())
{
for(size_t i = 1;i < lines.size();++i)
if(!tracking_windows.back()->command(tipl::split(lines[i],',')))
{
if(!tracking_windows.back()->error_msg.empty())
QMessageBox::critical(this,"ERROR",tracking_windows.back()->error_msg.c_str());
return;
}
}
}
else
if(name.endsWith(".tt.gz") ||
name.endsWith(".trk") ||
name.endsWith(".trk.gz"))
{
auto file_list = QFileInfo(file_name).dir().entryList(QStringList("*fz"),QDir::Files|QDir::NoSymLinks);
file_list << QFileInfo(file_name).dir().entryList(QStringList("*fib.gz"),QDir::Files|QDir::NoSymLinks);
if(file_list.size() == 1)
{
if(loadFib(QFileInfo(file_name).absolutePath() + "/" + file_list[0]))
for(const auto& each:file_names)
tracking_windows.back()->command({"open_tract",each.toStdString()});
}
else
loadFib(file_name);
}
else
if(name.endsWith("fib.gz") ||
name.endsWith(".fz") ||
name.endsWith(".dz") ||
name.endsWith("tck"))
{
if(name.endsWith("db.fib.gz") ||
name.endsWith("db.fz") ||
name.endsWith(".dz"))
{
std::shared_ptr<group_connectometry_analysis> database(new group_connectometry_analysis);
if(!database->load_database(file_name.toStdString().c_str()))
{
QMessageBox::critical(
this,"ERROR",database->error_msg.c_str());
return;
}
auto* db = new db_window(this,database);
db->setWindowTitle(file_name);
db->setAttribute(Qt::WA_DeleteOnClose);
db->show();
}
else
loadFib(file_name);
}
else
if(name.endsWith("src.gz") || name.endsWith(".sz"))
{
loadSrc(file_names);
}
else
if(name.endsWith(".nhdr") ||
name.endsWith(".nrrd") ||
name.endsWith(".nii") ||
name.endsWith(".nii.gz") ||
name.endsWith(".dcm") ||
name.endsWith(".nz") ||
name.endsWith(".mz"))
{
loadNii(file_names);
}
else {
QMessageBox::critical(this,"ERROR","Unsupported file extension");
}
}
}
void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
if(event->mimeData()->hasUrls())
{
event->acceptProposedAction();
}
}
void MainWindow::dropEvent(QDropEvent *event)
{
event->acceptProposedAction();
QList<QUrl> droppedUrls = event->mimeData()->urls();
int droppedUrlCnt = droppedUrls.size();
QStringList files;
for(int i = 0; i < droppedUrlCnt; i++)
files << droppedUrls[i].toLocalFile();
openFile(files);
}
void MainWindow::open_fib_at(int row,int)
{
if(auto* item = ui->recentFib->item(row,0))
loadFib(item->data(Qt::UserRole).toString());
}
void MainWindow::open_src_at(int row,int)
{
if(auto* item = ui->recentSrc->item(row,0))
loadSrc({item->data(Qt::UserRole).toString()});
}
void MainWindow::closeEvent(QCloseEvent* event)
{
auto windows = tracking_windows;
for(auto* window : windows)
if(window && !window->close())
{
event->ignore();
return;
}
ai_agent->close(); // its own closeEvent stops every running agent process; ~AIAgent() alone would not
QMainWindow::closeEvent(event);
}
MainWindow::~MainWindow()
{
console.log_window = nullptr;
QStringList workdir_list;
for (int index = 0;index < 10 && index < ui->workDir->count();++index)
workdir_list << ui->workDir->itemText(index);
auto current = ui->workDir->currentIndex();
if(current > 0 && current < workdir_list.size())
workdir_list.move(current,0);
settings.setValue("WORK_PATH", workdir_list);
delete ui;
}
void MainWindow::updateRecentList()
{
auto update = [this](QTableWidget* table,const char* key)
{
auto files = settings.value(key).toStringList();
table->clearContents();
table->setRowCount(files.size());
for(int row = 0;row < files.size();++row)
{
QFileInfo info(files[row]);
table->setRowHeight(row,20);
table->setItem(row,0,new QTableWidgetItem(info.fileName()));
table->setItem(row,1,new QTableWidgetItem(info.absolutePath()));
for(int col = 0;col < 2;++col)
{
auto* item = table->item(row,col);
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
item->setData(Qt::UserRole,files[row]);
if(!info.exists())
item->setForeground(Qt::gray);
}
}
table->setHorizontalHeaderLabels({"File Name","Directory"});
};
update(ui->recentFib,"recentFibFileList");
update(ui->recentSrc,"recentSrcFileList");
}
void MainWindow::addRecent(QString filename,const char* key)
{
auto files = settings.value(key).toStringList();
QFileInfo info(filename);
for(int index = files.size()-1;index >= 0;--index)
if(QFileInfo(files[index]) == info)
files.removeAt(index);
files.prepend(QDir::toNativeSeparators(info.absoluteFilePath()));
while (files.size() > MaxRecentFiles)
files.removeLast();
settings.setValue(key,files);
updateRecentList();
}
void MainWindow::addFib(QString filename)
{
addRecent(filename,"recentFibFileList");
}
void MainWindow::addSrc(QString filename)
{
addRecent(filename,"recentSrcFileList");
}
void shift_track_for_tck(std::vector<std::vector<float> >& loaded_tract_data,tipl::shape<3>& geo);
extern QByteArray default_geo,default_state;
QString command_window_id(QWidget* window)
{
// the one place that maps a widget to its AI-addressable window type; everything downstream
// that needs the type back out of an id string uses command_window_type(const QString&) instead
const char* type =
qobject_cast<MainWindow*>(window) ? "main" :
qobject_cast<tracking_window*>(window) ? "tracking" :
qobject_cast<reconstruction_window*>(window) ? "recon" :
qobject_cast<group_connectometry*>(window) ? "connectometry" :
qobject_cast<view_image*>(window) ? "image" : nullptr;
return type ? command_window_id(window,type) : QString();
}
QString command_window_type(const QString& id)
{
if(id == "main")
return "main";
if(id.startsWith("tracking"))
return "tracking";
if(id.startsWith("recon"))
return "recon";
if(id.startsWith("connectometry"))
return "connectometry";
if(id.startsWith("image"))
return "image";
return QString();
}
void MainWindow::report_and_target_window(QWidget* window)
{
auto id = command_window_id(window);
tipl::out() << "window created, id: " << id.toStdString(); // id itself is "<type><hex>", the type needs no separate extraction here
ai_agent->update_current_window(window);
}
bool MainWindow::loadFib(QString filename)
{
std::shared_ptr<fib_data> new_handle(new fib_data);
if (!new_handle->load_from_file(tipl::qt::to_path(filename)))
{
error_msg = new_handle->error_msg;
if(!new_handle->error_msg.empty())
QMessageBox::critical(this,"ERROR",new_handle->error_msg.c_str());
return false;
}
tracking_windows.push_back(new tracking_window(this,new_handle));
report_and_target_window(tracking_windows.back());
tracking_windows.back()->setAttribute(Qt::WA_DeleteOnClose);
tracking_windows.back()->setWindowTitle(filename);
if(filename.contains("/presentation/"))
{
tracking_windows.back()->command({"load_workspace",QFileInfo(filename).absolutePath().toStdString()});
tracking_windows.back()->command({"presentation_mode"});
}
else
if(!filename.contains(QCoreApplication::applicationDirPath()))
{
addFib(filename);
add_work_dir(QFileInfo(filename).absolutePath());
}
tracking_windows.back()->showNormal();
tracking_windows.back()->resize(1200,700);
if(tipl::ends_with(filename.toStdString(),{".trk.gz",".trk",".tck",".tt.gz"}))
{
tracking_windows.back()->command({"open_tract",filename.toStdString()});
if(filename.endsWith(".tck"))
{
tipl::shape<3> geo;
shift_track_for_tck(tracking_windows.back()->tractWidget->tract_models.back()->get_tracts(),geo);
}
}
if(!default_geo.size())
default_geo = tracking_windows.back()->saveGeometry();
if(!default_state.size())
default_state = tracking_windows.back()->saveState();
QFileInfo info(filename);
auto base = info.completeBaseName();
if(int p = base.lastIndexOf('_');!filename.endsWith("_dseg.nii.gz",Qt::CaseInsensitive) && p >= 0)
{
auto dseg_file = info.dir().filePath(
base.left(p)+"_dseg.nii.gz");
if(QFileInfo::exists(dseg_file))
tracking_windows.back()->command({"open_region",dseg_file.toUtf8().constData()});
}
return true;
}
void MainWindow::loadNii(QStringList file_names)
{
view_image* dialog = new view_image(this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
if(!dialog->open(file_names))
{
delete dialog;
return;
}
report_and_target_window(dialog);
dialog->show();
}
bool MainWindow::loadSrc(QStringList filenames)
{
if(filenames.empty())
{
error_msg = "cannot find SRC.gz files in the directory. Please create SRC files first.";
QMessageBox::critical(this,"ERROR",error_msg.c_str());
return false;
}
try
{
tipl::progress prog("SRC reconstruction");
reconstruction_window* new_mdi = new reconstruction_window(filenames,this);
report_and_target_window(new_mdi);
new_mdi->setAttribute(Qt::WA_DeleteOnClose);
new_mdi->show();
if(filenames.size() == 1)
{
addSrc(filenames[0]);
add_work_dir(QFileInfo(filenames[0]).absolutePath());
}
}
catch(const std::runtime_error& error)
{
error_msg = error.what();
if(!tipl::prog_aborted)
QMessageBox::critical(this,"ERROR",error_msg.c_str());
return false;
}
return true;
}
void MainWindow::open_DWI(QStringList filenames)
{
if(filenames.isEmpty() || filenames[0].isEmpty())
return;
tipl::progress prog("Open DWI");
add_work_dir(QFileInfo(filenames[0]).absolutePath());
if(QFileInfo(filenames[0]).completeBaseName() == "subject")
{
tipl::io::bruker_info subject_file;
if(!subject_file.load_from_file(filenames[0].toStdString().c_str()))
return;
QString dir = QFileInfo(filenames[0]).absolutePath();
filenames.clear();
for(unsigned int i = 1;i < 100;++i)
if(QDir(dir + "/" +QString::number(i)).exists())
{
bool is_dwi =false;
// has dif info in the method file
{
tipl::io::bruker_info method_file;
QString method_name = dir + "/" +QString::number(i)+"/method";
if(method_file.load_from_file(tipl::qt::to_path(method_name)) &&
method_file["PVM_DwEffBval"].length())
is_dwi = true;
}
// has dif info in the imnd file
{
tipl::io::bruker_info imnd_file;
QString imnd_name = dir + "/" +QString::number(i)+"/imnd";
if(imnd_file.load_from_file(tipl::qt::to_path(imnd_name)) &&
imnd_file["IMND_diff_b_value"].length())
is_dwi = true;
}
if(is_dwi)
filenames.push_back(dir + "/" +QString::number(i)+"/pdata/1/2dseq");
}
if(filenames.size() == 0)
{
QMessageBox::critical(this,"ERROR","No diffusion data in this subject");
return;
}
std::string file_name(subject_file["SUBJECT_study_name"]);
file_name.erase(std::remove(file_name.begin(),file_name.end(),' '),file_name.end());
dicom_parser* dp = new dicom_parser(filenames,this);
dp->set_name(dir + "/" + file_name.c_str() + ".sz");
dp->setAttribute(Qt::WA_DeleteOnClose);
dp->showNormal();
return;
}
if(filenames[0].endsWith(".dcm"))
{
QString sel = QString("*.")+QFileInfo(filenames[0]).suffix();
QDir directory = QFileInfo(filenames[0]).absoluteDir();
QStringList file_list = directory.entryList(QStringList(sel),QDir::Files|QDir::NoSymLinks);
if(file_list.size() > filenames.size())
{
QString msg =
QString("There are %1 %2 files in the directory. Select all?").arg(file_list.size()).arg(QFileInfo(filenames[0]).suffix());
int result = QMessageBox::information(this,"Input images",msg,
QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel);
if(result == QMessageBox::Cancel)
return;
if(result == QMessageBox::Yes)
{
filenames = file_list;
for(int index = 0;index < filenames.size();++index)
filenames[index] = directory.absolutePath() + "/" + filenames[index];
}
}
}
dicom_parser* dp = new dicom_parser(filenames,this);
dp->setAttribute(Qt::WA_DeleteOnClose);
dp->showNormal();
if(dp->dwi_files.empty())
dp->close();
}
std::filesystem::path rename_dicom(const std::filesystem::path& file_name,std::filesystem::path output,std::string& error_msg);
void MainWindow::add_work_dir(QString dir)
{
if(ui->workDir->findText(dir) != -1)
ui->workDir->removeItem(ui->workDir->findText(dir));
ui->workDir->insertItem(0,dir);
ui->workDir->setCurrentIndex(0);
if(tipl::qt::working_dirs.indexOf(dir) != -1)
tipl::qt::working_dirs.remove(tipl::qt::working_dirs.indexOf(dir));
tipl::qt::working_dirs << dir;
}
QString MainWindow::work_dir() const
{
return ui->workDir->currentText();
}
std::vector<std::filesystem::path> rename_dicom_at_dir(std::filesystem::path path,
std::filesystem::path output,std::string& error_msg);
bool parse_dwi(const std::vector<std::filesystem::path>& file_list,
std::vector<std::shared_ptr<DwiHeader> >& dwi_files,std::string& error_msg);
std::filesystem::path get_dicom_output_name(const std::filesystem::path& file_name,
const std::string& file_extension, bool add_path);
QStringList search_files(QString dir,QString filter);
void MainWindow::on_workDir_currentTextChanged(const QString &arg1)
{
if(!arg1.isEmpty())
QDir::setCurrent(arg1);
}
bool load_image_from_files(QStringList filenames,tipl::image<3>& ref,tipl::vector<3>& vs,tipl::matrix<4,4>& trans);
void MainWindow::on_linear_reg_clicked()
{
QStringList filename1 = tipl::qt::open_image_files(this,ui->workDir->currentText(),
"Images (*.nii *nii.gz *.dcm);;All files (*)" );
if(filename1.isEmpty())
return;
QStringList filename2 = tipl::qt::open_image_files(this,QFileInfo(filename1[0]).absolutePath(),
"Images (*.nii *nii.gz *.dcm);;All files (*)" );
if(filename2.isEmpty())
return;
tipl::image<3> ref1,ref2;
tipl::vector<3> vs1,vs2;
tipl::matrix<4,4> t1,t2;
if(!load_image_from_files(filename1,ref1,vs1,t1) ||
!load_image_from_files(filename2,ref2,vs2,t2))
return;
std::shared_ptr<manual_alignment> manual(new manual_alignment(this,tipl::reg::subject_image_pre(tipl::image<3>(ref1)),tipl::image<3,unsigned char>(),vs1,
tipl::reg::template_image_pre(tipl::image<3>(ref2)),tipl::image<3,unsigned char>(),vs2,tipl::reg::affine,tipl::reg::mutual_info));
manual->from_T = t1;
manual->to_T = t2;
if(manual->exec() != QDialog::Accepted)
return;
}
std::string quality_check_src_files(const std::vector<std::filesystem::path>& file_list,
bool check_btable,bool use_template,unsigned int template_id);
std::string quality_check_fib_files(const std::vector<std::filesystem::path>& file_list);
std::string quality_check_nii_files(const std::vector<std::filesystem::path>& file_list);
std::vector<std::filesystem::path> search_dwi_nii_bids(const std::filesystem::path& dir);
bool nii2src(const std::vector<std::filesystem::path>& dwi_nii_files,
const std::filesystem::path& output_dir,
bool is_bids,
bool overwrite,
bool topup_eddy,
std::string& error_msg);
void search_dwi_nii(const std::filesystem::path& dir,std::vector<std::filesystem::path>& dwi_nii_files);
bool dicom2src_and_nii(std::vector<std::filesystem::path> files,bool overwrite,std::string& error_msg)
{
auto fail = [&](const std::string& msg){error_msg = msg;return tipl::error() << msg,false;};
if(files.empty())
return fail("no files provided");
std::sort(files.begin(),files.end());
tipl::progress p("processing DICOM at "+files.front().parent_path().u8string());
std::string manu,make,report,sequence;
{
tipl::io::dicom header;
if(!header.load_from_file(files[0]))
return fail("cannot read image volume. skip");
header.get_sequence_id(sequence);
header.get_text(0x0008,0x0070,manu);//Manufacturer
header.get_text(0x0008,0x1090,make);
manu.erase(std::remove(manu.begin(),manu.end(),' '),manu.end());
make.erase(std::remove(make.begin(),make.end(),' '),make.end());
std::ostringstream info;
info << manu.c_str() << " " << make.c_str() << " " << sequence
<< ".TE=" << header.get_float(0x0018,0x0081) << ".TR=" << header.get_float(0x0018,0x0080) << ".";
report = info.str();
if(report.size() < 80)
report.resize(80);
}
std::vector<std::shared_ptr<DwiHeader> > dicom_files;
std::string parse_error;
auto nii_file_name = get_dicom_output_name(files[0],"_" + sequence + ".nii.gz",true);
if(!parse_dwi(files,dicom_files,parse_error) || dicom_files.size() == 1)
{
if(tipl::prog_aborted)
return false;
if(!parse_error.empty())
return fail(parse_error);
if(!overwrite && std::filesystem::exists(nii_file_name))
return tipl::out() << nii_file_name << " exists. skipping",true;
tipl::out() << "handled as structure images";
tipl::image<3> source_images;
tipl::vector<3> vs;
if(files.size()==1)
{
tipl::io::dicom v;
if(!v.load_from_file(files[0]))
return fail("cannot parse dicom file");
v >> std::tie(source_images,vs);
if(source_images.empty())
return fail("cannot read "+files[0].u8string()+" as image, skipping");
}
else
{
tipl::out() << "parsing " << files.size() << " dicom files";
tipl::io::dicom_volume v;
if(!v.load_from_files(files))
return fail(v.error_msg);
tipl::out() << "dim: " << v.dim << " vs: " << v.vs;
tipl::out() << "trans: " << tipl::matrix<3,3,float>(v.orientation_matrix);
tipl::out() << "dim order: " << tipl::vector<3,int>(v.dim_order);
tipl::out() << "flipping: " << tipl::vector<3,int>(v.flip);
v >> source_images;
v.get_voxel_size(vs);
if(source_images.empty())
return fail("cannot read as image volume, skipping");
}
tipl::matrix<4,4,float> trans;
tipl::io::initial_nifti_srow(trans,source_images.shape(),vs);
return tipl::io::gz_nifti(nii_file_name,std::ios::out) << vs << trans << source_images;
}
if(!DwiHeader::has_b_table(dicom_files))
{
if(!overwrite && std::filesystem::exists(nii_file_name))
return tipl::out() << nii_file_name << " exists. skipping",true;
tipl::out() << "The images do not have b-table. Save as 4D NIFTI" << std::endl;
auto dicom = dicom_files[0];
tipl::matrix<4,4> trans;
tipl::io::initial_nifti_srow(trans,dicom->image.shape(),dicom->voxel_size);
tipl::image<4,unsigned short> buffer(dicom->image.shape().expand(dicom_files.size()));
for(unsigned int index = 0;index < dicom_files.size();++index)
{
std::copy(dicom_files[index]->image.begin(),
dicom_files[index]->image.end(),
buffer.begin() + long(index*dicom_files[index]->image.size()));
}
tipl::out() << "output 4D NII file";
return tipl::io::gz_nifti(nii_file_name,std::ios::out) << dicom->voxel_size << trans << report << buffer;
}
auto src_name = get_dicom_output_name(files[0],(std::string("_")+sequence+".sz"),true);
if(!overwrite && std::filesystem::exists(src_name))
return tipl::out() << src_name << " exists. skipping",true;
src_data src;
if(!src.load_from_file(dicom_files,false) ||
!src.save_to_file(src_name))
return fail(src.error_msg);
return true;
}