-
Notifications
You must be signed in to change notification settings - Fork 0
/
turingmachinewindow.cpp
1531 lines (1365 loc) · 55.7 KB
/
turingmachinewindow.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*(C)Copyright 2023 Malone Napier-Jameson
*
* This file is part of Turing Machine Simulator.
* Turing Machine Simulator is free software: you can redistribute it and/or modify it under the terms of
* the GNU Lesser General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
* Turing Machine Simulator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License along with Turing Machine Simulator.
* There is also a copy available inside the application.
* If not, see <https://www.gnu.org/licenses/>.
*/
#include "turingmachinewindow.h"
#include "ui_turingmachinewindow.h"
#include <QGraphicsSceneMouseEvent>
#include <QDebug>
#include <QObject>
#include <QMessageBox>
#include <QFileDialog>
#include <QFile>
#include <QScrollBar>
#include <QGraphicsProxyWidget>
#include <QTextEdit>
#include <QColorDialog>
#include <QDesktopServices>
#include <QVBoxLayout>
#include <QListWidgetItem>
#include "popupmessagebox.h"
#include "pixmapbutton.h"
#include "savedialog.h"
TuringMachineWindow::TuringMachineWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::TuringMachineWindow)
{
ui->setupUi(this);
//Load saved settings:
this->loadSettings();
ui->tapeLengthSpinBox->setValue(m_TapeLength);
ui->playSpeedSpinBox->setValue(m_Speed);
//Window configurations:
this->setWindowIcon(QIcon(":/new/prefix1/Images and Icons/sim3.png"));
this->setFont(QFont("Corbel Light"));
ui->menuBar->setFont(QFont("Corbel Light", 11));
ui->actionLoadTM->setFont(QFont("Corbel Light", 11));
ui->actionLoadTM->setIcon(QIcon(":/new/prefix1/Images and Icons/load icon.png"));
ui->actionSaveTM->setFont(QFont("Corbel Light", 11));
ui->actionSaveTM->setIcon(QIcon(":/new/prefix1/Images and Icons/save icon.png"));
ui->actionExit->setFont(QFont("Corbel Light", 11));
ui->actionExit->setIcon(QIcon(":/new/prefix1/Images and Icons/exit icon.png"));
ui->label->setFont(QFont("Corbel Light", 12));
ui->clearPushButton->setFont(QFont("Corbel Light", 11));
//Tab icons and font size:
ui->tabWidget->setTabIcon(0, QIcon(":/new/prefix1/Images and Icons/design icon.png"));
ui->tabWidget->setTabIcon(1, QIcon(":/new/prefix1/Images and Icons/summary icon.png"));
ui->tabWidget->setTabIcon(2, QIcon(":/new/prefix1/Images and Icons/options icon.png"));
ui->tabWidget->setTabIcon(3, QIcon(":/new/prefix1/Images and Icons/help icon.png"));
ui->tabWidget->setFont(QFont("Corbel Light", 10));
//Initialize variables:
m_HasHALTState = false;
m_HasSTARTState = false;
m_SettingsChanged = false;
m_Modified = false;
m_FileLoaded = false;
m_TMModel = nullptr;
m_Processor = new TMProcessor(this);
if(m_SavePath == "")
m_SavePath = QDir::homePath() + "/Documents/Saved TMs";
m_LoadedFile = "";
m_LoadedDescription = "";
m_CellWidth = 32;
//Setup the TM scene:
m_Scene = new TMSScene(this);
ui->graphicsView->setScene(m_Scene);
ui->graphicsView->setRenderHint(QPainter::Antialiasing);
ui->graphicsView->setFrameStyle(QFrame::StyledPanel);
ui->graphicsView->setFrameShadow(QFrame::Raised);
ui->graphicsView->setAlignment(Qt::AlignLeft | Qt::AlignTop);
ui->graphicsView->setFocus();
ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
//Setup variables:
m_NumOfStates = 0;
connect(ui->addStateButton, SIGNAL(clicked(bool)), this, SLOT(addStateButtonClicked()));
connect(ui->deleteStateButton, SIGNAL(clicked()), this, SLOT(deleteStateButtonClicked()));
connect(ui->setAsStartButton, SIGNAL(clicked()), this, SLOT(setSTARTStateButtonClicked()));
connect(ui->setAsHaltButton, SIGNAL(clicked()), this, SLOT(setHALTStateButtonClicked()));
connect(ui->addArrowButton, SIGNAL(clicked()), this, SLOT(addArrowButtonClicked()));
connect(ui->addLoopArrowButton, SIGNAL(clicked()), this, SLOT(addLoopArrowButtonClicked()));
connect(ui->deleteArrowButton, SIGNAL(clicked()), this, SLOT(deleteArrowButtonClicked()));
connect(ui->testInputButton, SIGNAL(clicked()), this, SLOT(testInputButtonClicked()));
connect(ui->buildButton, SIGNAL(clicked()), this, SLOT(buildButtonClicked()));
connect(ui->clearSceneButton, SIGNAL(clicked()), this, SLOT(clearSceneButtonClicked()));
connect(ui->exitButton, SIGNAL(clicked()), this, SLOT(exitButtonClicked()));
//Input line edit:
ui->inputLineEdit->setMaximumWidth(2000);
ui->inputLineEdit->setMinimumWidth(500);
//Set up spawn box:
m_SpawnBox = new SquareSpawnBox(5, 5, 60, 60, nullptr);
m_Scene->addItem(m_SpawnBox);
QGraphicsTextItem *boxLabel = m_Scene->addText("Spawn box");
boxLabel->setDefaultTextColor(Qt::darkGray);
boxLabel->setPos(0, m_SpawnBox->sceneBoundingRect().height());
boxLabel->setOpacity(0.8);
//Setup the tape scene:
m_TapeScene = new QGraphicsScene(this);
//Set up tape view:
ui->tapeGraphicsView->setMinimumWidth(500);
ui->tapeGraphicsView->setMaximumHeight(80);
ui->tapeGraphicsView->setAlignment(Qt::AlignVCenter | Qt::AlignLeft);
ui->tapeGraphicsView->setRenderHint(QPainter::Antialiasing);
ui->tapeGraphicsView->setScene(m_TapeScene);
ui->tapeGraphicsView->horizontalScrollBar()->setValue(ui->tapeGraphicsView->horizontalScrollBar()->minimum());
//Set up the tape:
qreal offset = 0;
for(int i = 0; i < m_TapeLength; i++)
{
SquareTapeCell *temp = new SquareTapeCell(QRectF(5 + offset, 16, m_CellWidth, m_CellWidth));
m_Tape.append(temp);
temp->setLabel("-");
m_TapeScene->addItem(temp);
offset += m_CellWidth;
}
//Set up tape head:
m_TapeHead = new TapeHead(this);
m_TapeScene->addItem(m_TapeHead);
m_TapeHeadStartXPos = 5 + (m_CellWidth / 2.0) - m_TapeHead->sceneBoundingRect().width()/2.0;
m_TapeHead->setPos(m_TapeHeadStartXPos, 1);
//Set up timers:
m_MoveLeftTimer = new QTimer(this);
m_MoveLeftTimer->setInterval(10);
connect(m_MoveLeftTimer, SIGNAL(timeout()), this, SLOT(moveLeft()));
m_MoveRightTimer = new QTimer(this);
m_MoveRightTimer->setInterval(10);
connect(m_MoveRightTimer, SIGNAL(timeout()), this, SLOT(moveRight()));
m_PauseTimer = new QTimer(this);
m_PauseTimer->setInterval(500);
connect(m_PauseTimer, SIGNAL(timeout()), this, SLOT(unpause()));
connect(this, SIGNAL(doneMoving()), this, SLOT(play()));
//Summary page:
this->setupSummaryPage();
//Description timer:
m_DescTimer = new QTimer(this);
m_DescTimer->setInterval(500);
connect(m_DescTimer, SIGNAL(timeout()), this, SLOT(fadeOutDescription()));
//Options page:
this->setupOptionsPage();
//Help page:
this->setupHelpPage();
//Create save file if there isn't one
QDir tempDir(QDir::homePath() + "/Documents");
tempDir.mkdir("Saved TMs");
//Show logo:
m_Logo = m_Scene->addPixmap(QPixmap(":/new/prefix1/Images and Icons/sim3.png"));
m_Logo->setScale(0.8);
m_Logo->setOpacity(0.3);
m_Logo->setPos(694 - m_Logo->sceneBoundingRect().width()/2.0, 299 - m_Logo->sceneBoundingRect().height()/2.0);
m_LogoTimer = new QTimer(this);
m_LogoTimer->setInterval(100);
connect(m_LogoTimer, SIGNAL(timeout()), this, SLOT(fadeOutLogo()));
m_TimeCounter = 0;
m_LogoTimer->start();
}
TuringMachineWindow::~TuringMachineWindow()
{
if(m_SettingsChanged)
{
//Save the new Settings:
QFile saveFile("TMS.settings");
if(saveFile.open(QIODevice::WriteOnly))
{
QTextStream outStream(&saveFile);
outStream << m_SavePath << '\n';
outStream << m_TapeLength << '\n';
outStream << m_AHCColor.name() << '\n';
outStream << m_CSCColor.name() << '\n';
saveFile.close();
}
}
delete ui;
}
void TuringMachineWindow::clearTapeView()
{
//Move the tape head back to the start:
m_TapeHead->setPos(m_TapeHeadStartXPos, 1);
//Replace all letter in the tape with blanks:
for(int i = 0; i < m_TapeLength; i++)
m_Tape[i]->setLabel("-");
ui->tapeGraphicsView->horizontalScrollBar()->setValue(ui->tapeGraphicsView->horizontalScrollBar()->minimum());
m_TapeScene->update();
ui->tapeGraphicsView->update();
}
void TuringMachineWindow::setupSummaryPage()
{
//Summary table view:
ui->summaryTable->setFrameStyle(QFrame::Raised);
ui->summaryTable->setFont(QFont("Corbel", 11));
ui->summaryTable->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
m_TableModel = new QStandardItemModel(this);
//Create the table labels:
QStringList headerLabels;
headerLabels.append("From");
headerLabels.append("To");
headerLabels.append("Read");
headerLabels.append("Write");
headerLabels.append("Move");
m_TableModel->setHorizontalHeaderLabels(headerLabels);
ui->summaryTable->setModel(m_TableModel);
}
void TuringMachineWindow::setupOptionsPage()
{
// Connect Buttons
ui->saveLocationLineEdit->setText(m_SavePath);
connect(ui->browseButton, SIGNAL(clicked()), this, SLOT(getSaveFileLocation()));
connect(ui->playSpeedSpinBox, SIGNAL(valueChanged(int)), this, SLOT(speedSpinBoxValueChanged(int)));
connect(ui->tapeLengthSpinBox, SIGNAL(valueChanged(int)), this, SLOT(tapeLengthSpinBoxValueChanged(int)));
connect(ui->AHCButton, SIGNAL(clicked()), this, SLOT(changeAHCColor()));
connect(ui->CSCButton, SIGNAL(clicked()), this, SLOT(changeCSCColor()));
ui->AHCButton->setStyleSheet(QString("QPushButton {background-color: %1; border-radius: 3;}"
"QPushButton:hover { border: 1px solid #ffffff;}"
"QPushButton:pressed { border: 2px solid #ffffff; }").arg(m_AHCColor.name()));
ui->CSCButton->setStyleSheet(QString("QPushButton {background-color: %1; border-radius: 3;}"
"QPushButton:hover { border: 1px solid #ffffff;}"
"QPushButton:pressed { border: 2px solid #ffffff; }").arg(m_CSCColor.name()));
ui->AHC_Label->setText(m_AHCColor.name());
ui->CSC_Label->setText(m_CSCColor.name());
}
void TuringMachineWindow::setupHelpPage()
{
QString licenseMessage = "";
QString licenseMessage2 = "";
//Get license data from the files:
//GNU License:
/*QFile file1("COPYING.txt");
if(file1.open(QIODevice::ReadOnly))
{
QTextStream instream(&file1);
licenseMessage.append(instream.readAll());
file1.close();
}*/
//LGPL License:
QFile file2("COPYING.LESSER");
if(file2.open(QIODevice::ReadOnly))
{
QTextStream instream(&file2);
licenseMessage2.append(instream.readAll());
file2.close();
}
//Page configurations:
connect(ui->aboutAppButton, SIGNAL(clicked()), this, SLOT(aboutAppButtonClicked()));
connect(ui->aboutQtButton, SIGNAL(clicked()), this, SLOT(aboutQtButtonClicked()));
connect(ui->aboutAuthorButton, SIGNAL(clicked()), this, SLOT(aboutAuthorButtonClicked()));
connect(ui->openUserManualButton, SIGNAL(clicked()), this, SLOT(openUserManualButtonClicked()));
//ui->license1TextEdit->setPlainText(licenseMessage);
ui->license2TextEdit->setPlainText(licenseMessage2);
}
void TuringMachineWindow::populateSummaryTable(QStringList tableData)
{
m_TableModel->setRowCount(0);
//Add data to the model:
QList<QStandardItem*> row;
for(int i = 0; i < tableData.length(); i++)
{
row.clear();
row.append(new QStandardItem(QString("%1%2") .arg(tableData[i][0]) .arg(tableData[i][1])));
row.append(new QStandardItem(QString("%1%2") .arg(tableData[i][3]) .arg(tableData[i][4])));
row.append(new QStandardItem(tableData[i][6]));
row.append(new QStandardItem(tableData[i][8]));
row.append(new QStandardItem(tableData[i][10]));
m_TableModel->appendRow(row);
ui->summaryTable->setRowHeight(i, 35);
}
}
void TuringMachineWindow::displayTestSummary()
{
//Display the crash messege if any:
QString crashMessege = m_Processor->getCrashString();
if(crashMessege == "")
ui->crashMessageLabel->setText("Input was accepted. No crash message.");
else
ui->crashMessageLabel->setText(crashMessege);
//Set accept or reject color on box:
if(crashMessege == "")
{
ui->acceptedButton->setStyleSheet("QPushButton {"
"color: rgb(255, 255, 255);"
"background-color: #007016;"
"}"
);
ui->rejectedButton->setStyleSheet("QPushButton {"
"color: rgb(255, 255, 255);"
"background-color: rgb(61, 61, 61);"
"}"
);
}
else
{
ui->acceptedButton->setStyleSheet("QPushButton {"
"color: rgb(255, 255, 255);"
"background-color: rgb(61, 61, 61);"
"}"
);
ui->rejectedButton->setStyleSheet("QPushButton {"
"color: rgb(255, 255, 255);"
"background-color: #7f0000;"
"}"
);
}
//Retrieve and display the tape and transition records:
QStringList transitionRecord = m_Processor->getTransitionRecord().split('\n', Qt::SkipEmptyParts);
QStringList tapeRecord = m_Processor->getTapeRecord();
if(!transitionRecord.isEmpty() && !tapeRecord.isEmpty())
{
//Declare variables:
QStringList recordDetail;
QStringList transitionEntry;
QFont inpTextFont;
int index = 0;
//Set up the font:
inpTextFont.setFamily("Corbel");
inpTextFont.setLetterSpacing(QFont::AbsoluteSpacing, 5);
QString summaryText = "";
QString transitionText = "";
//Display all test result data:
for(int i = 0; i< tapeRecord.length(); i++)
{
if(i < tapeRecord.length() - 1)
{
// Add Tape data to the transition text
recordDetail = tapeRecord[i].split('-', Qt::SkipEmptyParts);
index = recordDetail[1].toInt();
//Add Transition data to the transition text
transitionEntry = transitionRecord[i].split(',', Qt::SkipEmptyParts);
transitionText += transitionEntry[0] + " ";
transitionText += transitionEntry[1] + " ";
transitionText += transitionEntry[2] + " ";
transitionText += transitionEntry[3] + " ";
transitionText += transitionEntry[4];
// HTML tags to highlight the character on the tape in focus
recordDetail[0].insert(index, "<b><u>");
recordDetail[0].insert(index + 7, "</u></b>");
summaryText += "<p>" + recordDetail[0] + "---------------------" + transitionText + "</p>";
transitionText = "";
}
}
this->ui->textEdit->setHtml(summaryText);
}
}
void TuringMachineWindow::loadSettings()
{
//Load Settings:
QFile loadFile("TMS.settings");
if(loadFile.open(QIODevice::ReadOnly))
{
QTextStream inStream(&loadFile);
m_SavePath = inStream.readLine();
QString tl = inStream.readLine();
m_TapeLength = tl.toInt();
m_Speed = 1;
m_AHCColor = QColor(inStream.readLine());
m_CSCColor = QColor(inStream.readLine());
loadFile.close();
}
else
{
QDir dir(QDir::homePath() + "/Documents");
dir.mkdir("Saved TMs");
m_SavePath = dir.path() + "/Saved TMs";
m_TapeLength = 50;
m_Speed = 1;
m_AHCColor = QColor("#55aa00");
m_CSCColor = QColor("#55ffff");
}
}
void TuringMachineWindow::quitApp()
{
if(m_Modified)
{
QString message = "Your design has unsaved changes. If you do not save, the changes will be lost";
int choice = QMessageBox::warning(this, "Changes unsaved", message, QMessageBox::Close, QMessageBox::Cancel);
if(choice == QMessageBox::Close)
qApp->quit();
}
else
qApp->quit();
}
void TuringMachineWindow::exitButtonClicked()
{
this->quitApp();
}
void TuringMachineWindow::addArrowButtonClicked()
{
QList<QGraphicsItem *> list = m_Scene->selectedItems();
if(!list.isEmpty())
{
MyStateItem *temp = qgraphicsitem_cast<MyStateItem*>(list.first());
if(temp)
temp->createStraightArrow();
//Signal changes as unsaved:
if(!m_Modified)
m_Modified = true;
}
}
void TuringMachineWindow::addLoopArrowButtonClicked()
{
QList<QGraphicsItem *> list = m_Scene->selectedItems();
if(!list.isEmpty())
{
MyStateItem *temp = qgraphicsitem_cast<MyStateItem*>(list.first());
if(temp)
temp->createLoopArrow();
//Signal changes as unsaved:
if(!m_Modified)
m_Modified = true;
}
}
void TuringMachineWindow::addStateButtonClicked()
{
QString label = QString("q%1") .arg(m_NumOfStates);
MyStateItem *state = new MyStateItem(this, 0, label);
state->setConnectedArrowColor(m_AHCColor);
m_Scene->addItem(state);
m_TM.append(state);
m_NumOfStates++;
//Signal changes as unsaved:
if(!m_Modified)
m_Modified = true;
}
void TuringMachineWindow::deleteStateButtonClicked()
{
QList<QGraphicsItem *> list = m_Scene->selectedItems();
QString stateNum = "";
if(!list.isEmpty())
{
//Find the first state pointed to and mark it for deletion:
MyStateItem *toBeDeleted = nullptr;
for(int i = 0; i < list.length(); i++)
{
toBeDeleted = qgraphicsitem_cast<MyStateItem*>(list[i]);
if(toBeDeleted != nullptr)
break;
}
//Look of the marked state in the list of states and delete it;
for(int i = 0; i < m_TM.length(); i++)
{
if(m_TM[i] == toBeDeleted)
{
if(i > 9)
stateNum = QString("%1%2") .arg(m_TM[i]->getStateName()[1]) .arg(m_TM[i]->getStateName()[2]);
else
stateNum = m_TM[i]->getStateName()[1];
//Detatch from arrows pointing at this state:
m_TM[i]->detachFromPointedArrows();
//Detatch this state's arrows from other states:
m_TM[i]->detachMyArrowsFromOtherStates();
//Check if the state being deleted is a halt state:
if(m_TM[i]->isSTARTState())
m_HasSTARTState = false;
if(m_TM[i]->isHALTState())
m_HasHALTState = false;
//Rename the states:
for(int i = stateNum.toInt(); i < m_TM.length(); i++)
m_TM[i]->decrementStateNameNum(i);
//Delete the state:
delete m_TM[i];
m_TM.removeAt(i);
//Signal changes as unsaved:
if(!m_Modified)
m_Modified = true;
break;
}
}
m_NumOfStates--;
}
}
void TuringMachineWindow::deleteArrowButtonClicked()
{
QList<QGraphicsItem *> list = m_Scene->selectedItems();
if(!list.isEmpty())
{
char type = ' ';
//Check if the arrow to be deleted is a loop arrow:
LoopArrow *tempLoop = nullptr;
SolidArrow *temp = nullptr;
for(int i = 0; i < list.length(); i++)//Find the first selected arrow:
{
//Check if the arrow to be deleted is a loop arrow:
tempLoop = qgraphicsitem_cast<LoopArrow*>(list[i]);
if(tempLoop)
{
type = 'l';
break;
}
//Check if it is a solid arrow
temp = qgraphicsitem_cast<SolidArrow*>(list[i]);
if(temp)
{
type = 's';
break;
}
}
//Find the owner of the arrow and tell them to delete it:
for(int i = 0; i <m_TM.length(); i++)
{
if(type == 's')
{
if(m_TM[i]->isAncestorOf(temp) && temp)
{
m_TM[i]->deleteArrow(temp);
break;
}
}
else if(type == 'l')
{
if(m_TM[i]->isAncestorOf(tempLoop) && tempLoop)
{
m_TM[i]->deleteArrow(tempLoop);
//Signal changes as unsaved:
if(!m_Modified)
m_Modified = true;
break;
}
}
}
}
}
void TuringMachineWindow::buildButtonClicked()
{
//Check if the TM has a start and halt state:
bool startAvailable = false;
bool haltAvailable = false;
for(MyStateItem *s : m_TM)
{
if(s->isSTARTState())
startAvailable = true;
if(s->isHALTState())
haltAvailable = true;
}
if(m_TM.isEmpty())//If TM is empty:
{
PopUpMessagebox *noTMFound = new PopUpMessagebox(this, "No TM Detected", "Please design a TM before trying to buid one."
"\n\n\nHints:"
"\n- Make sure that every arrow is connected to a state.",
QPixmap(":/new/prefix1/Images and Icons/warning.png"));
noTMFound->show();
}
else if(!startAvailable)
{
QString message = "No START state was detected in your TM. Please add one then build again.";
PopUpMessagebox *noStart = new PopUpMessagebox(this, "No START state detected", message,
QPixmap(":/new/prefix1/Images and Icons/warning.png"));
noStart->show();
}
else if(!haltAvailable)
{
QString message = "No HALT state was detected in your TM. Please add one then build again.";
PopUpMessagebox *noHalt = new PopUpMessagebox(this, "No HALT state detected", message,
QPixmap(":/new/prefix1/Images and Icons/warning.png"));
noHalt->show();
}
else
{
int badStateIndex = -1;
MyStateItem::Status s;
//Check if all the arrows are pointing to a state and have proper labels:
for(int i = 0; i < m_TM.length(); i++)
{
s = m_TM[i]->readyForProcessing();
if(s != MyStateItem::Ready || (!m_TM[i]->hasArrows() && !m_TM[i]->isHALTState()))
{
badStateIndex = i;
break;
}
}
if(badStateIndex > -1)//If there is a state not ready:
{
QString message;
if(s == MyStateItem::ArrowNotPointingToState)
{
message = QString("The state %1 is not ready for processing."
"\n\nPlease make sure that the state has edges and that all edges point to a state.")
.arg(m_TM[badStateIndex]->getStateName());
}
else if(s == MyStateItem::ArrowLabelInvalid)
{
message = QString("The state %1 is not ready for processing."
"\n\nOne or more of the arrows has an invalid label. Please make sure the labels are of the form:\n\n"
"(Read Letter),(Write Letter), (Move direction letter)\n\nIf there is more than one label on an arrow,"
"please enter these on separate lines.")
.arg(m_TM[badStateIndex]->getStateName());
}
PopUpMessagebox *notReady = new PopUpMessagebox(this, "TM not ready for processing", message, QPixmap(":/new/prefix1/Images and Icons/warning.png"));
notReady->show();
}
else//If all states are ready:
{
QStringList statesData;
QString entry = "";
for(int i = 0; i < m_TM.length(); i++)
{
entry = m_TM[i]->getStateData();
statesData.append(entry);
}
//Give the data to the machine model:
if(m_TMModel != nullptr)
delete m_TMModel;
m_TMModel = new TuringMachine(statesData);
m_TMModel->build();
//Update the summary table:
this->populateSummaryTable(m_TMModel->getSummaryTableData());
//Inform the user that the machine built successfully:
PopUpMessagebox *success = new PopUpMessagebox(this, "TM built successfully", "Your TM was built successfully."
"\n\nYou may now begin testing input.",
QPixmap(":/new/prefix1/Images and Icons/hammer.png"));
success->show();
}
}
}
void TuringMachineWindow::setHALTStateButtonClicked()
{
if(!m_HasHALTState)
{
QList<QGraphicsItem *> list = m_Scene->selectedItems();
if(!list.isEmpty())
{
MyStateItem* temp = nullptr;
for(int i = 0; i < list.length(); i++)
{
temp = qgraphicsitem_cast<MyStateItem*>(list[i]);
if(temp && !temp->isHALTState() && !temp->isSTARTState())
{
temp->setIsHALTState();
m_HasHALTState = true;
//Signal changes as unsaved:
if(!m_Modified)
m_Modified = true;
break;
}
}
}
}
}
void TuringMachineWindow::setSTARTStateButtonClicked()
{
if(!m_HasSTARTState)
{
QList<QGraphicsItem *> list = m_Scene->selectedItems();
if(!list.isEmpty())
{
MyStateItem* temp = nullptr;
for(int i = 0; i < list.length(); i++)
{
temp = qgraphicsitem_cast<MyStateItem*>(list[i]);
if(temp && !temp->isHALTState() && !temp->isSTARTState())
{
temp->setIsSTARTState();
m_HasSTARTState = true;
//Signal changes as unsaved:
if(!m_Modified)
m_Modified = true;
break;
}
}
}
}
}
void TuringMachineWindow::testInputButtonClicked()
{
if(m_TMModel == nullptr)
{
QString message = "No TM detected. \n\nPlease click the \"Build\" button after designing your TM to build it before testing input.";
PopUpMessagebox *noTMDetected = new PopUpMessagebox(this, "No TM Detected", message, QPixmap(":/new/prefix1/Images and Icons/warning.png"));
noTMDetected->show();
}
else
{
// Stop the timers if they are running
if(m_MoveLeftTimer->isActive())
m_MoveLeftTimer->stop();
if(m_MoveRightTimer->isActive())
m_MoveRightTimer->stop();
if(m_PauseTimer->isActive())
m_PauseTimer->stop();
// Disable the lear button
ui->clearPushButton->setEnabled(false);
// Set the input edit as read-only
ui->inputLineEdit->setReadOnly(true);
// Disable tape length spinbox
ui->tapeLengthSpinBox->setReadOnly(true);
//Reset TM colors:
for(MyStateItem *s: m_TM)
s->changeColor(Qt::white);
//Reset the tape:
this->on_inputLineEdit_editingFinished();
//Get the input string, set parameters and test the string:
QString input = ui->inputLineEdit->text() + '-';
m_Processor->setParameters(input, m_TMModel);
TMProcessor::ProcessResult result = m_Processor->start();
if(result == TMProcessor::Successful)
{
//Play the hops:
m_MachineData = m_Processor->getMachineData();
m_TapeData = m_Processor->getTapeData();
m_CurrentCell = 0;
m_TapeCounter = 0;
m_Count = 0;
m_TapeHeadStartXPos = 5 + (m_CellWidth / 2.0) - m_TapeHead->sceneBoundingRect().width()/2.0;
this->play();
//Display the test summary:
this->displayTestSummary();
}
else
{
QString message = "There is a possible infinite loop in your TM.\n"
"1 000 000 read, write and move iterations where executed.\n"
"Please revise your TM design so as to remove the infinite loop.\n\n"
"Hint\n- See the help section for help identifying infinite loops.";
PopUpMessagebox *infLoopMessage = new PopUpMessagebox(this, "Infinite loop warning", message,
QPixmap(":/new/prefix1/Images and Icons/warning.png"));
infLoopMessage->show();
}
}
}
void TuringMachineWindow::clearSceneButtonClicked()
{
for(int i = 0; i < m_TM.length(); i++)
{
m_Scene->removeItem(m_TM[i]);
delete m_TM[i];
}
m_NumOfStates = 0;
m_TM.clear();
m_TableModel->setRowCount(0);
m_FileLoaded = false;
m_LoadedFile = "";
m_LoadedDescription = "";
//Reset the summary page details:
ui->acceptedButton->setStyleSheet("QPushButton {"
"color: rgb(255, 255, 255);"
"background-color: rgb(61, 61, 61);"
"}");
ui->rejectedButton->setStyleSheet("QPushButton {"
"color: rgb(255, 255, 255);"
"background-color: rgb(61, 61, 61);"
"}");
m_NumOfStates = 0;
ui->crashMessageLabel->setText("Reason for crash will appear here");
ui->textEdit->clear();
}
void TuringMachineWindow::on_inputLineEdit_editingFinished()
{
//Clear the tape view:
this->clearTapeView();
//Enter the string in the tape:
if(!m_Tape.isEmpty())
{
QString inputString = ui->inputLineEdit->text();
for(int i = 0; i < inputString.length(); i++)
{
//In case the input string is longer than the tape:
if(i == m_TapeLength - 1)
break;
m_Tape[i]->setLabel(inputString[i]);
}
}
}
void TuringMachineWindow::play()
{
if(m_Count < m_MachineData.length() - 1)
{
//Change the previous state's color to white:
if(m_Count > 0)
m_TM[m_MachineData[m_Count]]->changeColor(Qt::white);
//Change the current state's color:
if(m_MachineData.length() > m_Count + 1)
m_TM[m_MachineData[m_Count + 1]]->changeColor(m_CSCColor);
//Move tapehead:
this->moveTapeHead();
m_Count++;
}
else
{
//Change the last state that the input got us to green if the word was accepted otherwise red:
if(m_Processor->getCrashString() == "")
m_TM[m_MachineData[m_Count]]->changeColor(Qt::green);
else
m_TM[m_MachineData[m_Count]]->changeColor(Qt::red);
// Re-enable everything that was disabled
ui->clearPushButton->setEnabled(true);
ui->inputLineEdit->setReadOnly(false);
ui->tapeLengthSpinBox->setReadOnly(false);
}
}
void TuringMachineWindow::unpause()
{
m_TapeHead->setBrush(Qt::black);
m_PauseTimer->stop();
emit this->doneMoving();
}
void TuringMachineWindow::moveTapeHead()
{
//Move tape head:
if(m_TapeCounter < m_TapeData.length() - 1)
{
m_MoveCounter = 0;
m_PrevHeadPos = m_TapeHead->scenePos();
//Write letter on tape:
m_Tape[m_CurrentCell]->setLabel(m_TapeData[m_TapeCounter][0]);
if(m_TapeData[m_TapeCounter][1].toLower() == QString("l"))
{
m_MoveLeftTimer->start();
m_CurrentCell--;
}
else if(m_TapeData[m_TapeCounter][1].toLower() == QString("r"))
{
m_MoveRightTimer->start();
m_CurrentCell++;
}
}
}
void TuringMachineWindow::moveLeft()
{
if(m_MoveCounter < m_CellWidth)
{
m_TapeHead->setPos(m_TapeHead->pos().x() - 1, m_TapeHead->scenePos().y());
m_MoveCounter++;
}
else
{
m_MoveLeftTimer->stop();
m_TapeCounter++;
m_TapeHead->setBrush(Qt::white);
m_PauseTimer->start();
}
}
void TuringMachineWindow::moveRight()
{
if(m_MoveCounter < m_CellWidth)
{
m_TapeHead->setPos(m_TapeHead->scenePos().x() + 1, m_TapeHead->scenePos().y());
m_MoveCounter++;
}
else
{
m_MoveRightTimer->stop();
m_TapeCounter++;
m_TapeHead->setBrush(Qt::white);
m_PauseTimer->start();
}
}
void TuringMachineWindow::on_clearPushButton_clicked()
{
ui->inputLineEdit->clear();
this->on_inputLineEdit_editingFinished();
}
void TuringMachineWindow::on_actionSaveTM_triggered()
{
auto saveDialog = [this](){
SaveDialog *sv = new SaveDialog(this);
connect(sv, SIGNAL(saveDetailsReady(QStringList)), this, SLOT(getSaveDetails(QStringList)));
sv->show();
};
if(m_FileLoaded)
{
QStringList datList = m_LoadedFile.split('/');
m_LoadedFile = datList[datList.length() - 1];
QString message = QString("Save over the loaded file: %1?") .arg(m_LoadedFile);
int choice = QMessageBox::question(this, "Override File?", message, QMessageBox::Yes, QMessageBox::No);
if(choice == QMessageBox::Yes)
{
//Save over currently open file
QStringList tempList;
m_LoadedFile.remove(".xml");
tempList.append(m_LoadedFile);
tempList.append(m_LoadedDescription);
this->getSaveDetails(tempList);
}
else
saveDialog();
}
else
saveDialog();
}
void TuringMachineWindow::on_actionLoadTM_triggered()
{
QString loadPath = QDir::homePath() + "/Documents/Saved TMs";
QString loadFileName = QFileDialog::getOpenFileName(this, "Open TM", loadPath, "XML files (*.xml)");
m_LoadedFile = loadFileName;
//Temporary objects for loading purposes:
MyStateItem *tempState = nullptr;