-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathmaskromtool.cpp
2080 lines (1760 loc) · 62.2 KB
/
maskromtool.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
/* The MaskRomTool class represents the main window of the GUI,
* but also a model of the current project and references to the other
* dialog windows.
*
* While I did not take time to properly abstract all of the GUI elements,
* the decoding of bits to bytes is properly isolated in the GatoROM class.
* It shares the same GUI but has its own CLI.
*
* The CLI and main() method are found in main.cpp and the GatoROM
* CLI can be found in gatomain.cpp.
*/
#include "maskromtool.h"
#include "gatorom.h"
#include "maskromtool_autogen/include/ui_maskromtool.h"
#include "romsecond.h"
#include "romlineitem.h"
#include "rombititem.h"
#include "rombitfix.h"
#include "romscene.h"
#include "romthresholddialog.h"
#include "aboutdialog.h"
//Aligners and samplers are pluggable.
#include "romalignerreliable.h"
#include "romalignertilting.h"
#include "rombitsamplerwide.h"
#include "rombitsamplertall.h"
//Decoders should be abstracted more, and menus auto-generated.
#include "romdecoderascii.h"
#include "romdecodercsv.h"
#include "romdecoderpython.h"
#include "romdecoderjson.h"
#include "romdecoderphotograph.h"
#include "romdecodergato.h" //GatoROM implements most binary decoders.
#include "romdecoderhistogram.h"
//Importers too, weird as they are.
#include "romencoderdiff.h"
//DRC rules.
#include "romrulecount.h"
#include "romruleduplicate.h"
#include "romrulesanity.h"
#include "romruleambiguous.h"
//Qt libraries.
#include <QFileDialog>
#include <QKeyEvent>
#include <QMouseEvent>
#include <QGraphicsItem>
#include <QImageReader>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QtGlobal>
#include <QTextStream>
#include <QDebug>
#include <QMessageBox>
#include <QtMath>
#include <QProgressDialog>
#include <QGraphicsPixmapItem>
//Printing. See https://github.com/travisgoodspeed/maskromtool/issues/75
#include <QPrinter>
#include <QPrintDialog>
using namespace std;
MaskRomTool::MaskRomTool(QWidget *parent, bool opengl)
: QMainWindow(parent)
, ui(new Ui::MaskRomTool) {
//Setup caches
QPixmapCache::setCacheLimit(0x100000); //1GB
if(verbose) qDebug()<<"Cache limit is "<<QPixmapCache::cacheLimit()<<"kb";
//Set up the main window.
ui->setupUi(this);
scene=new RomScene();
scene->maskRomTool=this;
ui->graphicsView->setScene(scene);
view=ui->graphicsView;
activeView=view; //Default to active window.
//Important to have a monospace font when updating the status.
QFont font("Andale Mono"); // macOS
font.setStyleHint(QFont::Monospace);
ui->statusbar->setFont(font);
//Some child dialogs need pointers back to the main project.
disDialog.setMaskRomTool(this);
violationDialog.setMaskRomTool(this);
decodeDialog.setMaskRomTool(this);
hexDialog.setMaskRomTool(this);
stringsDialog.setMaskRomTool(this);
solverDialog.setMaskRomTool(this);
solutionsDialog.setMaskRomTool(this);
RomRuleViolation::bitSize=bitSize;
lineColor = QColor(Qt::black);
selectionColor = QColor(Qt::green);
//Strategies should be initialized.
addAligner(new RomAlignerReliable()); //First is default.
addAligner(new RomAlignerTilting());
addSampler(new RomBitSampler()); //First is default.
addSampler(new RomBitSamplerWide());
addSampler(new RomBitSamplerTall());
//Set up the second view.
second.view->setScene(scene);
//Enable OpenGL without antialiasing, now that it's stable.
if(opengl)
enableOpenGL(0);
}
void MaskRomTool::closeEvent(QCloseEvent *event){
/* Closing any other window leaves the program running,
* but closing the main window will kill it out.
*
* Perhaps we should ask about saving first?
*/
//Use this instead of exit(0) to avoid crashing OpenGL on Windows.
QCoreApplication::quit();
}
/* Differences in angle are ignored here. We might later
* adjust these to respect that.
*/
static bool leftline(RomLineItem * left, RomLineItem * right){
return (left->x() < right->x());
}
static bool aboveline(RomLineItem * top, RomLineItem * bottom){
return (top->y() < bottom->y());
}
//Also handle it for bits.
static bool leftbit(RomBitItem * left, RomBitItem * right){
return (left->x() < right->x());
}
//Sorts the row and column lines.
void MaskRomTool::sortLines(){
std::sort(cols.begin(), cols.end(), leftline);
std::sort(rows.begin(), rows.end(), aboveline);
}
//Sorts the bits from the left. Fast if already sorted.
void MaskRomTool::sortBits(){
std::sort(bits.begin(), bits.end(), leftbit);
}
/* Undo works by saving the state during important actions
* to one of two stacks, and moving the state between those
* stacks.
*/
void MaskRomTool::undo(){
if(undostack.isEmpty())
return;
if(verbose)
qDebug()<<"Proceeding with undo. "<<undostack.size()<<"undos available.";
//Move an item from the undo stack to redo stack.
QJsonObject oldstate=exportJSON();
QJsonObject newstate=undostack.pop();
redostack.push(oldstate);
clear();
importJSON(newstate);
}
void MaskRomTool::redo(){
if(redostack.isEmpty())
return;
//Move a item from the redo stack to undo stack.
QJsonObject oldstate=exportJSON();
QJsonObject newstate=redostack.pop();
undostack.push(oldstate);
clear();
importJSON(newstate);
}
void MaskRomTool::markUndoPoint(){
/* We don't mark save states in the middle of file loads,
* as that would trigger recursion that would exhaust the
* call stack. Same goes for restoring undoes.
*/
if(importLock>0)
return;
if(verbose)
qDebug()<<"Marking undo point"<<undostack.size();
//Marking a point is just saving the state and emptying the redo buffer.
undostack.push(exportJSON());
if(undostack.size()>maxUndoCount)
undostack.pop_front();
redostack.empty();
}
void MaskRomTool::clear(){
/* For performance, we are just obliterating the entire state
* and not taking care to update things individually. This is
* why we call .remove() and delete directly, rather than
* calling MaskRomTool::removeItem().
*/
//Select nothing.
scene->selection=QList<QGraphicsItem*>();
for(auto i=bits.constBegin(); i!=bits.constEnd(); i++)
delete *i;
bits.clear();
assert(bits.isEmpty());
bits.empty();
bitcount=0;
for(auto i=bitfixes.constBegin(); i!=bitfixes.constEnd(); i++)
delete *i;
bitfixes.clear();
assert(bitfixes.isEmpty());
bitfixes.empty();
for(auto i = rows.constBegin(); i != rows.constEnd(); i++)
delete *i;
rows.clear();
assert(rows.isEmpty());
rows.empty();
for(auto i = cols.constBegin(); i != cols.constEnd(); i++)
delete *i;
cols.clear();
assert(cols.isEmpty());
cols.empty();
//There are no bits, so this mostly serves to zero counters.
markBits();
}
//Returns a GatoROM structure of the bits.
GatoROM MaskRomTool::gatorom(){
RomDecoderGato exporter;
exporter.gatorom(this);
QByteArray ga=gr.decode();
hexDialog.updatebinary(ga);
stringsDialog.updatebinary(ga);
disDialog.update();
return this->gr;
}
//Prints the bits.
void MaskRomTool::on_actionPrint_triggered(){
GatoROM gr=gatorom();
QPrinter printer;
QPrintDialog dialog(&printer);
dialog.setWindowTitle("Print Bits");
if (dialog.exec() == QDialog::Accepted)
gr.print(printer);
}
//Adds support for a sampler. Does not select it.
void MaskRomTool::addSampler(RomBitSampler *sampler){
samplers.insert(sampler);
//The first one to be inserted is the default.
if(!this->sampler)
this->sampler=sampler;
}
//Chooses a sampler by name.
void MaskRomTool::chooseSampler(QString name){
//Fast path if we've already selected it.
if(sampler->name==name)
return;
//Slow path if we need to find it.
foreach(RomBitSampler* sampler, samplers){
if(sampler->name==name){
this->sampler=sampler;
if(verbose)
qDebug()<<"Selected sampler"<<sampler->name;
remarkBits();
return;
}
}
//Error path.
qDebug()<<"Missing sampler algorithm"<<name;
qDebug()<<"Defaulting to sampler algoirthm"<<sampler->name;
}
//Alignment strategies.
void MaskRomTool::addAligner(RomAligner *aligner){
aligners.insert(aligner);
//First one is default.
if(!this->aligner)
this->aligner=aligner;
}
void MaskRomTool::chooseAligner(QString name){
if(aligner->name==name)
return;
foreach(RomAligner* aligner, aligners){
if(aligner->name==name){
this->aligner=aligner;
if(verbose) qDebug()<<"Changing aligner to"<<aligner->name;
remarkBits();
return;
}
}
qDebug()<<"Couldn't find aligner"<<name<<"defaulting to"<<aligner->name;
}
void MaskRomTool::setSamplerSize(int size){
sampler->setSize(size);
getSamplerSize(); //Grab it back in case the size was illegal.
}
int MaskRomTool::getSamplerSize(){
int size=sampler->getSize();
return size;
}
void MaskRomTool::on_actionOpenGL_triggered(){
//Do the switch!
enableOpenGL();
}
void MaskRomTool::enableOpenGL(unsigned int antialiasing){
//Enabled OpenGL.
QOpenGLWidget *gl = new QOpenGLWidget();
if(antialiasing>0){
QSurfaceFormat format;
format.setSamples(antialiasing);
gl->setFormat(format);
}
gl->setMouseTracking(true); //Required to track all mouse clicks.
view->setViewport(gl);
second.enableOpenGL(antialiasing);
//One way street.
ui->actionOpenGL->setEnabled(false);
ui->actionOpenGL->setChecked(true);
}
//Defined as extern in maskromtool.h.
unsigned int verbose=0;
//Set the verbose value.
void MaskRomTool::enableVerbose(unsigned int level){
qDebug()<<"Enabling verbose mode level"<<level;
verbose=level;
}
MaskRomTool::~MaskRomTool() {
//ui->graphicsView->setScene(0);
//delete scene;
delete ui;
}
//Marks all of the bits that are on a line.
void MaskRomTool::removeLine(RomLineItem* line, bool fromsets){
/* Regenerating all bits takes forever. The purpose of this function
* is to quickly remove the bits from a single line along with the
* line itself.
*
* If 'fromsets' is true, we're completely removing it.
* If 'fromsets' is false, we're just removing the bits and probably moving the line.
*/
//Removing a line always dirties the alignment.
alignmentdirty=true;
markingdirty=true;
//qDebug()<<"Removing all bits from a line.";
foreach(QGraphicsItem* item, scene->collidingItems(line)){
if(item->type()==QGraphicsItem::UserType+2){ //Is it a bit?
RomBitItem *bit=(RomBitItem*) item;
if(bit->rlcol==line || bit->rlrow==line)
removeItem(item);
}
}
//After removing the bits, we've gotta remove the line itself.
if(fromsets){
switch(line->type()){
case QGraphicsItem::UserType: //row
rows.removeOne((RomLineItem*) line);
break;
case QGraphicsItem::UserType+1: //column
cols.removeOne((RomLineItem*) line);
break;
}
scene->selection.removeOne(line);
delete line;
}
}
//Duplicates an item, returning a pointer to the clone.
QGraphicsItem* MaskRomTool::duplicateItem(QGraphicsItem* item, bool move){
RomLineItem* line=0;
switch(item->type()){
case QGraphicsItem::UserType: //Row
line=new RomLineItem(RomLineItem::LINEROW);
case QGraphicsItem::UserType+1: //Column
if(!line)
line=new RomLineItem(RomLineItem::LINECOL);
line->setPos(((RomLineItem*) item)->pos());
line->setLine(((RomLineItem*) item)->line());
if(line->type()==QGraphicsItem::UserType) //row
rows.append(line);
else
cols.append(line);
scene->addItem(line);
if(move)
item->setPos(item->pos()+QPointF(5,5));
markLine(line);
return line;
break;
}
//Shit happens. Return null if we can't copy the item.
return 0;
}
//Removes all duplicate rows and columns.
void MaskRomTool::removeDuplicates(){
bool bitswerevisible=bitsVisible;
sortLines();
/* foreach will return lines that no longer exist,
* so it's important to check for their existence before
* culling their duplicates.
*/
if(verbose)
qDebug()<<"Removing duplicate lines.";
setBitsVisible(true);
RomLineItem* lastline=0;
foreach(RomLineItem* r, rows){
if(lastline && lastline->globalline()==r->globalline()){
if(verbose) qDebug()<<"Removing duplicate row.";
removeLine(lastline, true);
}
lastline=r;
}
foreach(RomLineItem* c, cols){
if(lastline && lastline->globalline()==c->globalline()){
if(verbose) qDebug()<<"Removing duplicate column.";
removeLine(lastline, true);
}
lastline=c;
}
if(verbose)
qDebug()<<"Duplicates removed.";
setBitsVisible(bitswerevisible);
}
//Always call this to remove an item, to keep things clean.
void MaskRomTool::removeItem(QGraphicsItem* item){
static QGraphicsItem* lastitem=0;
if(!item){
qDebug()<<"Cowardly refusing to delete null item.";
return;
}
lastitem=item;
/* It's critically important that we remove
* the item from any active selections. Without that,
* a user who selects both lines and bits on those lines
* might trigger a double-free in erasing the selection.
*/
if(scene->selection.contains(item))
scene->selection.removeOne(item);
switch(item->type()){
case QGraphicsItem::UserType: //row
case QGraphicsItem::UserType+1: //column
removeLine((RomLineItem*) item);
return; //We've already deleted this.
break;
case QGraphicsItem::UserType+2: //bit
//qDebug()<<"THIS IS SLOW! Removing bit "<<item;
bits.removeOne((RomBitItem*) item);
alignmentdirty=true;
bitcount--;
break;
case QGraphicsItem::UserType+3: //bit fix
bitfixes.removeOne((RomBitFix*) item);
alignmentdirty=true;
break;
case QGraphicsItem::UserType+4: //rule violation
violations.removeOne((RomRuleViolation*) item);
//Gotta remove the violation so that it isn't used after a free.
violationDialog.removeViolation((RomRuleViolation*) item);
//Violations do not dirty the alignment.
break;
default:
qDebug()<<"Removing unknown type"<<item->type()<<"in object"<<item;
}
/* Documentation of QGraphicsItem says that it's
* faster to remove it first and then destroy it,
* but my benchmarking says the opposite.
* --Travis
*/
//if(item->scene()==scene) scene->removeItem(item);
//Leaking memory would be bad.
delete item;
}
//Switch between viewing modes.
void MaskRomTool::nextMode(){
setBitsVisible(!bitsVisible);
setViolationsVisible(bitsVisible);
ui->actionBits->setChecked(bitsVisible);
ui->actionViolations->setChecked(bitsVisible);
//Redraw the bits when bringing them back.
if(bitsVisible) markBits(false);
}
void MaskRomTool::on_actionPhotograph_triggered(){
backgroundpixmap->setVisible(ui->actionPhotograph->isChecked());
}
void MaskRomTool::on_actionRowsColumns_triggered(){
setLinesVisible(ui->actionRowsColumns->isChecked());
}
void MaskRomTool::on_actionBits_triggered(){
setBitsVisible(ui->actionBits->isChecked());
}
void MaskRomTool::on_actionViolations_triggered(){
setViolationsVisible(ui->actionViolations->isChecked());
}
void MaskRomTool::on_actionViolationsDialog_triggered(){
this->violationDialog.show();
}
void MaskRomTool::on_actionCrosshair_triggered(){
scene->setCrosshairVisible(ui->actionCrosshair->isChecked());
}
void MaskRomTool::setLinesVisible(bool b){
linesVisible=b;
foreach (QGraphicsLineItem* item, rows)
item->setVisible(b);
foreach (QGraphicsLineItem* item, cols)
item->setVisible(b);
if(linesVisible)
scene->highlightSelection();
}
void MaskRomTool::setBitsVisible(bool b){
bitsVisible=b; //Default for new bits.
for(auto i=bits.constBegin(); i!=bits.constEnd(); i++)
(*i)->setVisible(b);
for(auto i=bitfixes.constBegin(); i!=bitfixes.constEnd(); i++)
(*i)->setVisible(b);
}
void MaskRomTool::setViolationsVisible(bool b){
for(auto i=violations.constBegin(); i!=violations.constEnd(); i++)
(*i)->setVisible(b);
}
//Highlights one item close to the center.
void MaskRomTool::centerOn(QGraphicsItem* item){
activeView->centerOn(item);
}
//Inserts a new line, either row or column.
bool MaskRomTool::insertLine(RomLineItem* rlitem){
/* We add the line to the scene here, but the parent
* function is responsible for marking the undo point.
*/
scene->addItem(rlitem);
rlitem->setPos(scene->scenepos);
markingdirty=true;
//Correct the mistake in case we mix rows and columns.
lastlinetype=rlitem->setType()-RomLineItem::UserType;
/* Duplicate lines will appear when the space bar is hit twice.
* We have to handle this situation, or users will get confused
* with broken projects.
*/
foreach(QGraphicsItem* item, scene->collidingItems(rlitem)){
if(item->type()==QGraphicsItem::UserType || //Row
item->type()==QGraphicsItem::UserType+1 //Column
){
RomLineItem* oldline=(RomLineItem*) item;
if(oldline->line()==rlitem->line()){
/* By this point, we are trying to place a line exactly over itself.
* So we'll refuse it and return.
*/
qDebug()<<"Removing old line to avoid duplication.";
removeItem(oldline);
}
}
}
//Focus on the new item, and also select it as the only item of a list.
scene->setFocusItem(rlitem);
if(rlitem->type()==QGraphicsItem::UserType) //row
rows.append(rlitem);
else //Column, UserType+1
cols.append(rlitem);
markLine(rlitem);
return true;
}
//We might be a GUI, but keyboards are where it's at!
void MaskRomTool::keyPressEvent(QKeyEvent *event){
RomLineItem *rlitem;
int key=event->key();
/* Key combos are handled in three places:
* 1. RomView
* 2. RomScene
* 3. MaskRomTool.
*/
bool alt=event->modifiers()&Qt::AltModifier;
bool shift=event->modifiers()&Qt::ShiftModifier;
bool ctrl=event->modifiers()&Qt::CTRL;
bool none=!ctrl && !shift && !alt;
switch(key){
/* These are keys which are handled for the global
* environment. See RomView for those specific to a
* single window's view.
*/
case Qt::Key_H: //Home button.
if((ctrl || shift) & !alt) //Set home.
home=scene->scenepos;
break;
case Qt::Key_A:
if(shift && !ctrl && !alt){ //Damage/Ambiguate bit.
markUndoPoint();
damageBit(scene->scenepos);
}
break;
case Qt::Key_Z: //Undo, Redo
if(ctrl && !shift && !alt)
undo();
else if(ctrl && shift && !alt)
redo();
break;
case Qt::Key_Tab: //Show/Hide BG
/* I'd love to use tab with modifiers here to hide and show
* other layers, but that doesn't work on macOS. --Travis
*/
nextMode();
break;
case Qt::Key_Backslash:
if(!ctrl && !shift && !alt){ // No modifiers for lines.
setLinesVisible(!linesVisible);
}else if(ctrl && !shift && !alt){ // Ctrl for background.
ui->actionPhotograph->setChecked(
!ui->actionPhotograph->isChecked());
on_actionPhotograph_triggered();
}else if(!ctrl && !shift && alt){ // Alt for crosshair.
ui->actionCrosshair->setChecked(
!ui->actionCrosshair->isChecked());
on_actionCrosshair_triggered();
}
break;
case Qt::Key_F:
if(shift && !ctrl && !alt){ //Force a Bit
markUndoPoint();
fixBit(scene->scenepos);
statusBar()->showMessage(tr("Forced a bit."));
}
break;
case Qt::Key_V: //DRC
if(shift && !ctrl && !alt)
clearViolations(); //Clear out the violations for now.
else if(none)
runDRC(false); //Just run the normal DRC, no key combo for the long one.
break;
//Show errors.
case Qt::Key_E: // Errors
nextViolation(); //Select the next violation.
break;
//Modify the focus object.
case Qt::Key_D: //Delete an object or many objects.
case Qt::Key_Backspace:
case Qt::Key_Delete:
markUndoPoint();
if(shift && !ctrl && !alt){ //Duplicate
/* This works by duplicating each selected line. The original
* plan was to then select the duplicates, but it makes just as
* much sense to hold a selection of the original lines.
*/
foreach(QGraphicsItem* item, scene->selection){
if(item &&
(item->type()==QGraphicsItem::UserType
|| item->type()==QGraphicsItem::UserType+1)){
//The original remains selected, so that's the one we move a bit to the side.
duplicateItem(item);
}
}
//Don't bother forcing an update. That can come later.
}else if(none){ //Delete
bool bitswerevisible=bitsVisible;
if(!bitsVisible) setBitsVisible(true);
foreach(QGraphicsItem* item, scene->selection){
removeItem(item);
scene->selection.removeOne(item);
}
setBitsVisible(bitswerevisible);
}
break;
//Save or set Position
case Qt::Key_S:
if(ctrl && !shift && !alt){
on_saveButton_triggered();
}else if(none && scene->focusItem()){
markUndoPoint();
switch(scene->focusItem()->type()){
case QGraphicsItem::UserType: //row
case QGraphicsItem::UserType+1: //column
RomLineItem *line=(RomLineItem*)scene->focusItem();
moveLine(line, scene->scenepos);
}
}
break;
//These insert an object and set its focus.
case Qt::Key_Space:
markUndoPoint();
rlitem=new RomLineItem(lastlinetype);
rlitem->setLine(lastlinetype==RomLineItem::LINEROW
? lastrow : lastcol);
insertLine(rlitem);
break;
case Qt::Key_R: //Row line.
markUndoPoint();
rlitem=new RomLineItem(lastlinetype=RomLineItem::LINEROW);
if(shift)
rlitem->setLine(lastrow);
else
rlitem->setLine(0, 0,
scene->presspos.x()-scene->scenepos.x(),
scene->presspos.y()-scene->scenepos.y()
);
insertLine(rlitem);
break;
case Qt::Key_C: //Column line.
markUndoPoint();
rlitem=new RomLineItem(lastlinetype=RomLineItem::LINECOL);
if(shift)
rlitem->setLine(lastcol);
else
rlitem->setLine(0, 0,
scene->presspos.x()-scene->scenepos.x(),
scene->presspos.y()-scene->scenepos.y()
);
insertLine(rlitem);
break;
//These operate on the loaded data.
case Qt::Key_M: //Mark Bits.
//This kicks off the state machine to redraw all bits.
clearBits(false);
if(shift){
on_actionHexView_triggered();
}
break;
}
}
//Direction function to run the rules, called by CLI and GUI.
bool MaskRomTool::runDRC(bool all){
//Clear the field for new violations.
clearViolations();
//We'll crash if the bits aren't aligned, and duplicate lines are always a pain.
removeDuplicates();
markBits(true);
statusBar()->showMessage(tr("Running the Design Rule Checks. (DRC)"));
RomRuleCount count;
if(ui->drcCount->isChecked() || all){
if(verbose) qDebug()<<"DRC Count";
count.evaluate(this);
}
RomRuleDuplicate dupes;
if(ui->drcDuplicates->isChecked() || all){
if(verbose) qDebug()<<"DRC Dupes";
dupes.evaluate(this);
}
RomRuleSanity sanity;
if(ui->drcSanity->isChecked() || all){
if(verbose) qDebug()<<"DRC Sanity";
sanity.evaluate(this);
}
RomRuleAmbiguous ambiguity;
if(ui->drcAmbiguous->isChecked() || all){
if(verbose) qDebug()<<"DRC Ambiguity";
ambiguity.evaluate(this);
}
if(verbose) qDebug()<<"DRC done.";
statusBar()->showMessage(tr("Found %1 Design Rule Check (DRC) violations.").arg(violations.count()));
if(violations.count()>0)
on_actionViolationsDialog_triggered();
return true;
}
//Menu item to run the rules.
void MaskRomTool::on_actionRunDRC_triggered(){
runDRC(false);
}
//Runs all the rules, even those not checked.
void MaskRomTool::on_actionRunAllDRC_triggered(){
runDRC(true);
}
//This just clears out the pending violations.
void MaskRomTool::on_actionClearViolations_triggered(){
clearViolations();
}
//Marks a DRC violation in the scene.
void MaskRomTool::addViolation(RomRuleViolation* violation){
QString message("%1: %2");
qDebug()<<message.arg((violation->error?"ERROR":"WARNING"),
violation->title);
violations.append(violation);
scene->addItem(violation);
violationDialog.addViolation(violation);
}
//Clears all DRC violation. Called before redrawing them.
void MaskRomTool::clearViolations(){
violationDialog.clearViolations();
foreach (RomRuleViolation* v, violations){
removeItem(v);
}
}
//Select the next violation.
void MaskRomTool::nextViolation(){
violationDialog.nextViolation();
}
void MaskRomTool::on_importDiff_triggered(){
if(verbose)
qDebug()<<"Importing a diff.";
RomEncoderDiff differ;
QString filename = QFileDialog::getOpenFileName(this, tr("Diff Bits as ASCII"),"",tr("Textfiles (*.txt)"));
if(!filename.isEmpty()){
//Remove the old violations.
clearViolations();
differ.readFile(this, filename);
}
statusBar()->showMessage(tr("Found %1 bit differences.").arg(violations.count()));
if(violations.count()>0)
on_actionViolationsDialog_triggered();
}
//Exports ASCII for ZORROM/Bitviewer.
void MaskRomTool::on_exportASCII_triggered(){
RomDecoderAscii exporter;
QString filename = QFileDialog::getSaveFileName(this,tr("Export Bits as ASCII"),
"bits.txt",
tr("Textfiles (*.txt)"));
if(!filename.isEmpty())
exporter.writeFile(this,filename);
}
//Exports CSV for Matlab or Excel.
void MaskRomTool::on_exportCSV_triggered(){
RomDecoderCSV exporter;
QString filename = QFileDialog::getSaveFileName(this,tr("Export Bits as CSV"),
"bits.csv",
tr("CSV (*.csv)"));
if(!filename.isEmpty())
exporter.writeFile(this,filename);
}
//Exports Python for custom scripts.
void MaskRomTool::on_exportPython_triggered(){
RomDecoderPython exporter;
QString filename = QFileDialog::getSaveFileName(this,tr("Save Python"),
"bits.py",
tr("Python (*.py)"));
if(!filename.isEmpty())
exporter.writeFile(this,filename);
}
//Exports just the bit values and location as JSON.
void MaskRomTool::on_exportJSONBits_triggered(){
RomDecoderJson json;
QString filename = QFileDialog::getSaveFileName(this,tr("Save JSON"), tr("bits.json"));
if(!filename.isEmpty())
json.writeFile(this, filename);
}
//New exported, uses GatoROM and decoding dialog.
void MaskRomTool::on_exportROMBytes_triggered(){
GatoROM gato=gatorom();
if(gato.decoder==0){
QMessageBox::warning(this, "Mask ROM Tool",
"Use Edit/Decoding to set a decoder.",
QMessageBox::Ok,
QMessageBox::Ok);
return;
}
QString filename = QFileDialog::getSaveFileName(this,tr("Save ROM"), tr("rom.bin"));
if(!filename.isEmpty()){
QFile fout(filename);
fout.open(QIODevice::WriteOnly);
fout.write(gato.decode());
}
}
//Exports a .png image from the current project.
void MaskRomTool::on_exportPhotograph_triggered(){
RomDecoderPhotograph photo;
QString filename = QFileDialog::getSaveFileName(this,tr("Save Photograph"), tr("romphoto.png"));
if(!filename.isEmpty()){
photo.writeFile(this, filename);
}
}
//Exports a GNUPlot data file.
void MaskRomTool::on_exportHistogram_triggered(){
RomDecoderHistogram hist;
QString filename = QFileDialog::getSaveFileName(this,tr("Save Histogram"), tr("histogram.txt"));
if(!filename.isEmpty()){
hist.writeFile(this, filename);
}
}
//Pop up the about dialog.
void MaskRomTool::on_aboutButton_triggered(){
aboutDialog about;
about.exec();
}
//Display the ASCII preview window.
void MaskRomTool::on_asciiButton_triggered(){
RomDecoderAscii exporter;
asciiDialog.setText(exporter.preview(this));
asciiDialog.show();
}
//Display the Hex preview window.
void MaskRomTool::on_actionHexView_triggered(){
gatorom();
hexDialog.show();
}